blob: 471dadc4074454bc534208da3fcf2fb7856b4157 [file] [log] [blame]
Raman Tenneti6a872c92021-01-14 19:17:50 -08001# Copyright (C) 2021 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Raman Tenneti21dce3d2021-02-09 00:26:31 -080015"""Provide functionality to get all projects and their commit ids from Superproject.
Raman Tenneti6a872c92021-01-14 19:17:50 -080016
17For more information on superproject, check out:
18https://en.wikibooks.org/wiki/Git/Submodules_and_Superprojects
19
20Examples:
21 superproject = Superproject()
Raman Tenneti21dce3d2021-02-09 00:26:31 -080022 project_commit_ids = superproject.UpdateProjectsRevisionId(projects)
Raman Tenneti6a872c92021-01-14 19:17:50 -080023"""
24
25import os
26import sys
27
Raman Tenneti21dce3d2021-02-09 00:26:31 -080028from error import BUG_REPORT_URL
Raman Tenneti6a872c92021-01-14 19:17:50 -080029from git_command import GitCommand
Raman Tenneti21dce3d2021-02-09 00:26:31 -080030from git_refs import R_HEADS
Raman Tenneti1fd7bc22021-02-04 14:39:38 -080031import platform_utils
Raman Tenneti6a872c92021-01-14 19:17:50 -080032
Raman Tenneti8d43dea2021-02-07 16:30:27 -080033_SUPERPROJECT_GIT_NAME = 'superproject.git'
34_SUPERPROJECT_MANIFEST_NAME = 'superproject_override.xml'
35
Raman Tenneti6a872c92021-01-14 19:17:50 -080036
37class Superproject(object):
Raman Tenneti21dce3d2021-02-09 00:26:31 -080038 """Get commit ids from superproject.
Raman Tenneti6a872c92021-01-14 19:17:50 -080039
Raman Tenneti21dce3d2021-02-09 00:26:31 -080040 It does a 'git clone' of superproject and 'git ls-tree' to get list of commit ids
41 for all projects. It contains project_commit_ids which is a dictionary with
42 project/commit id entries.
Raman Tenneti6a872c92021-01-14 19:17:50 -080043 """
Raman Tenneti21dce3d2021-02-09 00:26:31 -080044 def __init__(self, manifest, repodir, superproject_dir='exp-superproject'):
Raman Tenneti6a872c92021-01-14 19:17:50 -080045 """Initializes superproject.
46
47 Args:
Raman Tenneti21dce3d2021-02-09 00:26:31 -080048 manifest: A Manifest object that is to be written to a file.
Raman Tenneti6a872c92021-01-14 19:17:50 -080049 repodir: Path to the .repo/ dir for holding all internal checkout state.
Raman Tenneti21dce3d2021-02-09 00:26:31 -080050 It must be in the top directory of the repo client checkout.
Raman Tenneti6a872c92021-01-14 19:17:50 -080051 superproject_dir: Relative path under |repodir| to checkout superproject.
52 """
Raman Tenneti21dce3d2021-02-09 00:26:31 -080053 self._project_commit_ids = None
54 self._manifest = manifest
55 self._branch = self._GetBranch()
Raman Tenneti6a872c92021-01-14 19:17:50 -080056 self._repodir = os.path.abspath(repodir)
57 self._superproject_dir = superproject_dir
58 self._superproject_path = os.path.join(self._repodir, superproject_dir)
Raman Tenneti1fd7bc22021-02-04 14:39:38 -080059 self._manifest_path = os.path.join(self._superproject_path,
Raman Tenneti8d43dea2021-02-07 16:30:27 -080060 _SUPERPROJECT_MANIFEST_NAME)
61 self._work_git = os.path.join(self._superproject_path,
62 _SUPERPROJECT_GIT_NAME)
Raman Tenneti6a872c92021-01-14 19:17:50 -080063
64 @property
Raman Tenneti21dce3d2021-02-09 00:26:31 -080065 def project_commit_ids(self):
66 """Returns a dictionary of projects and their commit ids."""
67 return self._project_commit_ids
Raman Tenneti6a872c92021-01-14 19:17:50 -080068
Raman Tenneti21dce3d2021-02-09 00:26:31 -080069 def _GetBranch(self):
70 """Returns the branch name for getting the approved manifest."""
71 p = self._manifest.manifestProject
72 b = p.GetBranch(p.CurrentBranch)
73 if not b:
74 return None
75 branch = b.merge
76 if branch and branch.startswith(R_HEADS):
77 branch = branch[len(R_HEADS):]
78 return branch
79
80 def _Clone(self, url):
81 """Do a 'git clone' for the given url.
Raman Tenneti6a872c92021-01-14 19:17:50 -080082
83 Args:
84 url: superproject's url to be passed to git clone.
Raman Tenneti6a872c92021-01-14 19:17:50 -080085
86 Returns:
Raman Tenneti21dce3d2021-02-09 00:26:31 -080087 True if git clone is successful, or False.
Raman Tenneti6a872c92021-01-14 19:17:50 -080088 """
Raman Tenneti8d43dea2021-02-07 16:30:27 -080089 if not os.path.exists(self._superproject_path):
90 os.mkdir(self._superproject_path)
91 cmd = ['clone', url, '--filter', 'blob:none', '--bare']
Raman Tenneti21dce3d2021-02-09 00:26:31 -080092 if self._branch:
93 cmd += ['--branch', self._branch]
Raman Tenneti6a872c92021-01-14 19:17:50 -080094 p = GitCommand(None,
95 cmd,
96 cwd=self._superproject_path,
97 capture_stdout=True,
98 capture_stderr=True)
99 retval = p.Wait()
100 if retval:
101 # `git clone` is documented to produce an exit status of `128` if
102 # the requested url or branch are not present in the configuration.
103 print('repo: error: git clone call failed with return code: %r, stderr: %r' %
104 (retval, p.stderr), file=sys.stderr)
105 return False
106 return True
107
Raman Tenneti8d43dea2021-02-07 16:30:27 -0800108 def _Fetch(self):
109 """Do a 'git fetch' to to fetch the latest content.
Raman Tenneti9e787532021-02-01 11:47:06 -0800110
111 Returns:
Raman Tenneti8d43dea2021-02-07 16:30:27 -0800112 True if 'git fetch' is successful, or False.
Raman Tenneti9e787532021-02-01 11:47:06 -0800113 """
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800114 if not os.path.exists(self._work_git):
Raman Tenneti8d43dea2021-02-07 16:30:27 -0800115 print('git fetch missing drectory: %s' % self._work_git,
116 file=sys.stderr)
117 return False
118 cmd = ['fetch', 'origin', '+refs/heads/*:refs/heads/*', '--prune']
Raman Tenneti9e787532021-02-01 11:47:06 -0800119 p = GitCommand(None,
120 cmd,
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800121 cwd=self._work_git,
Raman Tenneti9e787532021-02-01 11:47:06 -0800122 capture_stdout=True,
123 capture_stderr=True)
124 retval = p.Wait()
125 if retval:
Raman Tenneti8d43dea2021-02-07 16:30:27 -0800126 print('repo: error: git fetch call failed with return code: %r, stderr: %r' %
Raman Tenneti9e787532021-02-01 11:47:06 -0800127 (retval, p.stderr), file=sys.stderr)
128 return False
129 return True
130
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800131 def _LsTree(self):
132 """Returns the data from 'git ls-tree ...'.
Raman Tenneti6a872c92021-01-14 19:17:50 -0800133
134 Works only in git repositories.
135
136 Returns:
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800137 data: data returned from 'git ls-tree ...' instead of None.
Raman Tenneti6a872c92021-01-14 19:17:50 -0800138 """
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800139 if not os.path.exists(self._work_git):
Raman Tenneti8d43dea2021-02-07 16:30:27 -0800140 print('git ls-tree missing drectory: %s' % self._work_git,
141 file=sys.stderr)
142 return None
Raman Tenneti6a872c92021-01-14 19:17:50 -0800143 data = None
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800144 branch = 'HEAD' if not self._branch else self._branch
Raman Tennetice64e3d2021-02-08 13:27:41 -0800145 cmd = ['ls-tree', '-z', '-r', branch]
146
Raman Tenneti6a872c92021-01-14 19:17:50 -0800147 p = GitCommand(None,
148 cmd,
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800149 cwd=self._work_git,
Raman Tenneti6a872c92021-01-14 19:17:50 -0800150 capture_stdout=True,
151 capture_stderr=True)
152 retval = p.Wait()
153 if retval == 0:
154 data = p.stdout
155 else:
156 # `git clone` is documented to produce an exit status of `128` if
157 # the requested url or branch are not present in the configuration.
158 print('repo: error: git ls-tree call failed with return code: %r, stderr: %r' % (
159 retval, p.stderr), file=sys.stderr)
160 return data
161
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800162 def Sync(self):
163 """Sync superproject either by git clone/fetch.
Raman Tenneti6a872c92021-01-14 19:17:50 -0800164
165 Returns:
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800166 True if sync of superproject is successful, or False.
Raman Tenneti6a872c92021-01-14 19:17:50 -0800167 """
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800168 print('WARNING: --use-superproject is experimental and not '
169 'for general use', file=sys.stderr)
170
171 if not self._manifest.superproject:
172 print('error: superproject tag is not defined in manifest',
173 file=sys.stderr)
174 return False
175
176 url = self._manifest.superproject['remote'].url
Raman Tenneti6a872c92021-01-14 19:17:50 -0800177 if not url:
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800178 print('error: superproject URL is not defined in manifest',
179 file=sys.stderr)
180 return False
Raman Tenneti8d43dea2021-02-07 16:30:27 -0800181
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800182 do_clone = True
Raman Tenneti6a872c92021-01-14 19:17:50 -0800183 if os.path.exists(self._superproject_path):
Raman Tenneti8d43dea2021-02-07 16:30:27 -0800184 if not self._Fetch():
185 # If fetch fails due to a corrupted git directory, then do a git clone.
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800186 platform_utils.rmtree(self._superproject_path)
187 else:
188 do_clone = False
189 if do_clone:
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800190 if not self._Clone(url):
191 print('error: git clone failed for url: %s' % url, file=sys.stderr)
192 return False
193 return True
Raman Tenneti6a872c92021-01-14 19:17:50 -0800194
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800195 def _GetAllProjectsCommitIds(self):
196 """Get commit ids for all projects from superproject and save them in _project_commit_ids.
197
198 Returns:
199 A dictionary with the projects/commit ids on success, otherwise None.
200 """
201 if not self.Sync():
202 return None
203
204 data = self._LsTree()
Raman Tenneti6a872c92021-01-14 19:17:50 -0800205 if not data:
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800206 print('error: git ls-tree failed for superproject', file=sys.stderr)
207 return None
Raman Tenneti6a872c92021-01-14 19:17:50 -0800208
209 # Parse lines like the following to select lines starting with '160000' and
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800210 # build a dictionary with project path (last element) and its commit id (3rd element).
Raman Tenneti6a872c92021-01-14 19:17:50 -0800211 #
212 # 160000 commit 2c2724cb36cd5a9cec6c852c681efc3b7c6b86ea\tart\x00
213 # 120000 blob acc2cbdf438f9d2141f0ae424cec1d8fc4b5d97f\tbootstrap.bash\x00
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800214 commit_ids = {}
Raman Tenneti6a872c92021-01-14 19:17:50 -0800215 for line in data.split('\x00'):
216 ls_data = line.split(None, 3)
217 if not ls_data:
218 break
219 if ls_data[0] == '160000':
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800220 commit_ids[ls_data[3]] = ls_data[2]
Raman Tenneti6a872c92021-01-14 19:17:50 -0800221
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800222 self._project_commit_ids = commit_ids
223 return commit_ids
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800224
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800225 def _WriteManfiestFile(self):
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800226 """Writes manifest to a file.
227
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800228 Returns:
229 manifest_path: Path name of the file into which manifest is written instead of None.
230 """
231 if not os.path.exists(self._superproject_path):
232 print('error: missing superproject directory %s' %
233 self._superproject_path,
234 file=sys.stderr)
235 return None
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800236 manifest_str = self._manifest.ToXml().toxml()
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800237 manifest_path = self._manifest_path
238 try:
239 with open(manifest_path, 'w', encoding='utf-8') as fp:
240 fp.write(manifest_str)
241 except IOError as e:
242 print('error: cannot write manifest to %s:\n%s'
243 % (manifest_path, e),
244 file=sys.stderr)
245 return None
246 return manifest_path
247
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800248 def UpdateProjectsRevisionId(self, projects):
249 """Update revisionId of every project in projects with the commit id.
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800250
251 Args:
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800252 projects: List of projects whose revisionId needs to be updated.
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800253
254 Returns:
255 manifest_path: Path name of the overriding manfiest file instead of None.
256 """
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800257 commit_ids = self._GetAllProjectsCommitIds()
258 if not commit_ids:
259 print('error: Cannot get project commit ids from manifest', file=sys.stderr)
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800260 return None
261
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800262 projects_missing_commit_ids = []
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800263 for project in projects:
264 path = project.relpath
265 if not path:
266 continue
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800267 commit_id = commit_ids.get(path)
268 if commit_id:
269 project.SetRevisionId(commit_id)
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800270 else:
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800271 projects_missing_commit_ids.append(path)
272 if projects_missing_commit_ids:
273 print('error: please file a bug using %s to report missing commit_ids for: %s' %
274 (BUG_REPORT_URL, projects_missing_commit_ids), file=sys.stderr)
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800275 return None
276
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800277 manifest_path = self._WriteManfiestFile()
Raman Tenneti1fd7bc22021-02-04 14:39:38 -0800278 return manifest_path