update: Make sure to detach branch when checking out a specific revision
[platform/upstream/gstreamer.git] / git-update
1 #!/usr/bin/env python3
2 import argparse
3 import os
4 import subprocess
5 import xml.etree.ElementTree as ET
6 import sys
7
8 from common import git
9 from common import Colors
10 from common import accept_command
11
12
13 SCRIPTDIR = os.path.normpath(os.path.dirname(__file__))
14
15
16 def manifest_get_commits(manifest):
17     res = {}
18     tree = ET.parse(manifest)
19     root = tree.getroot()
20     remotes = {}
21     for child in root:
22         if child.tag == 'remote':
23             remotes[child.attrib['name']] = child.attrib['fetch']
24         if child.tag == 'project':
25             name = child.attrib['name']
26
27             remote = child.attrib.get('remote')
28             if remote:
29                 res[name] = ['FETCH_HEAD', [os.path.join(remotes[remote], name), child.attrib['revision']]]
30             else:
31                 res[name] = [child.attrib["revision"], []]
32
33     return res
34
35
36 def get_branch_name(repo_dir):
37     return git('-C', repo_dir, 'rev-parse', '--symbolic-full-name', 'HEAD').strip()
38
39
40 def ensure_revision_if_necessary(repo_dir, revision):
41     """
42     Makes sure that @revision is set if the current repo is detached.
43     """
44     if not revision:
45         if get_branch_name(repo_dir) == 'HEAD':
46             revision = git('-C', repo_dir, 'rev-parse', 'HEAD').strip()
47
48     return revision
49
50
51 def update_subprojects(repos_commits, no_interaction=False):
52     subprojects_dir = os.path.join(SCRIPTDIR, "subprojects")
53     for repo_name in os.listdir(subprojects_dir):
54         repo_dir = os.path.normpath(os.path.join(SCRIPTDIR, subprojects_dir, repo_name))
55         if not os.path.exists(os.path.join(repo_dir, '.git')):
56             continue
57
58         revision, args = repos_commits.get(repo_name, [None, []])
59         if not update_repo(repo_name, repo_dir, revision, no_interaction, args):
60             return False
61
62     return True
63
64
65 def update_repo(repo_name, repo_dir, revision, no_interaction, fetch_args=[], recurse_i=0):
66     revision = ensure_revision_if_necessary(repo_dir, revision)
67     git("config", "rebase.autoStash", "true", repository_path=repo_dir)
68     try:
69         if revision:
70             print("Checking out %s in %s" % (revision, repo_name))
71             git("fetch", *fetch_args, repository_path=repo_dir)
72             git("checkout", "--detach", revision, repository_path=repo_dir)
73         else:
74             print("Updating branch %s in %s" % (get_branch_name(repo_dir), repo_name))
75             git("pull", "--rebase", repository_path=repo_dir)
76         git("submodule", "update", repository_path=repo_dir)
77     except Exception as e:
78         out = getattr(e, "output", b"").decode()
79         if not no_interaction:
80             print("====================================="
81                   "\n%s\nEntering a shell in %s to fix that"
82                   " just `exit 0` once done, or `exit 255`"
83                   " to skip update for that repository"
84                   "\n=====================================" % (
85                         out, repo_dir))
86             try:
87                 if os.name is 'nt':
88                     shell = os.environ.get("COMSPEC", r"C:\WINDOWS\system32\cmd.exe")
89                 else:
90                     shell = os.environ.get("SHELL", os.path.realpath("/bin/sh"))
91                 subprocess.check_call(shell, cwd=repo_dir)
92             except subprocess.CalledProcessError as e:
93                 if e.returncode == 255:
94                     print("Skipping '%s' update" % repo_name)
95                     return True
96             except:
97                 # Result of subshell does not really matter
98                 pass
99
100             if recurse_i < 3:
101                 return update_repo(repo_name, repo_dir, revision, no_interaction,
102                                     recurse_i + 1)
103             return False
104         else:
105             print("\nCould not rebase %s, please fix and try again."
106                     " Error:\n\n%s %s" % (repo_dir, out, e))
107
108             return False
109
110
111     commit_message = git("show", "--shortstat", repository_path=repo_dir).split("\n")
112     print(u"  -> %s%s%s - %s" % (Colors.HEADER, commit_message[0][7:14], Colors.ENDC,
113                                     commit_message[4].strip()))
114
115     return True
116
117
118 if __name__ == "__main__":
119     parser = argparse.ArgumentParser(prog="git-update")
120
121     parser.add_argument("--no-color",
122                         default=False,
123                         action='store_true',
124                         help="Do not output ansi colors.")
125     parser.add_argument("--builddir",
126                         default=None,
127                         help="Specifies the build directory where to"
128                         " invoke ninja after updating.")
129     parser.add_argument("--no-interaction",
130                         default=False,
131                         action='store_true',
132                         help="Do not allow interaction with the user.")
133     parser.add_argument("--manifest",
134                         default=None,
135                         help="Use a android repo manifest to sync repositories"
136                         " Note that it will let all repositories in detached state")
137     options = parser.parse_args()
138     if options.no_color:
139         Colors.disable()
140
141     if options.no_interaction:
142         sys.stdin.close()
143
144     if options.manifest:
145         repos_commits = manifest_get_commits(options.manifest)
146     else:
147         repos_commits = {}
148
149     revision, args = repos_commits.get('gst-build', [None, []])
150     if not update_repo('gst-build', SCRIPTDIR, revision, options.no_interaction, args):
151         exit(1)
152
153     if not update_subprojects(repos_commits, options.no_interaction):
154         exit(1)
155
156     if options.builddir:
157         ninja = accept_command(["ninja", "ninja-build"])
158         if not ninja:
159             print("Can't find ninja, other backends are not supported for rebuilding")
160             exit(1)
161
162         if not os.path.exists(os.path.join (options.builddir, 'build.ninja')):
163             print("Can't rebuild in %s as no build.ninja file found." % options.builddir)
164
165         print("Rebuilding all GStreamer modules.")
166         exit(subprocess.call([ninja, '-C', options.builddir]))