Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(26)

Side by Side Diff: repo

Issue 2792012: Add the repo tool which is going to be used for iterative tasks across multiple git repos (Closed)
Patch Set: Created 10 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 #!/bin/sh
2
3 ## repo default configuration
4 ##
5 REPO_URL='git://android.git.kernel.org/tools/repo.git'
6 REPO_REV='stable'
7
8 # Copyright (C) 2008 Google Inc.
9 #
10 # Licensed under the Apache License, Version 2.0 (the "License");
11 # you may not use this file except in compliance with the License.
12 # You may obtain a copy of the License at
13 #
14 # http://www.apache.org/licenses/LICENSE-2.0
15 #
16 # Unless required by applicable law or agreed to in writing, software
17 # distributed under the License is distributed on an "AS IS" BASIS,
18 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 # See the License for the specific language governing permissions and
20 # limitations under the License.
21
22 magic='--calling-python-from-/bin/sh--'
23 """exec" python -E "$0" "$@" """#$magic"
24 if __name__ == '__main__':
25 import sys
26 if sys.argv[-1] == '#%s' % magic:
27 del sys.argv[-1]
28 del magic
29
30 # increment this whenever we make important changes to this script
31 VERSION = (1, 9)
32
33 # increment this if the MAINTAINER_KEYS block is modified
34 KEYRING_VERSION = (1,0)
35 MAINTAINER_KEYS = """
36
37 Repo Maintainer <repo@android.kernel.org>
38 -----BEGIN PGP PUBLIC KEY BLOCK-----
39 Version: GnuPG v1.4.2.2 (GNU/Linux)
40
41 mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
42 WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+I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gkQFlMNXpIPXGWp
75 TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2
76 =CMiZ
77 -----END PGP PUBLIC KEY BLOCK-----
78 """
79
80 GIT = 'git' # our git command
81 MIN_GIT_VERSION = (1, 5, 4) # minimum supported git version
82 repodir = '.repo' # name of repo's private directory
83 S_repo = 'repo' # special repo reposiory
84 S_manifests = 'manifests' # special manifest repository
85 REPO_MAIN = S_repo + '/main.py' # main script
86
87
88 import optparse
89 import os
90 import re
91 import readline
92 import subprocess
93 import sys
94
95 home_dot_repo = os.path.expanduser('~/.repoconfig')
96 gpg_dir = os.path.join(home_dot_repo, 'gnupg')
97
98 extra_args = []
99 init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
100
101 # Logging
102 group = init_optparse.add_option_group('Logging options')
103 group.add_option('-q', '--quiet',
104 dest="quiet", action="store_true", default=False,
105 help="be quiet")
106
107 # Manifest
108 group = init_optparse.add_option_group('Manifest options')
109 group.add_option('-u', '--manifest-url',
110 dest='manifest_url',
111 help='manifest repository location', metavar='URL')
112 group.add_option('-o', '--origin',
113 dest='manifest_origin',
114 help="use REMOTE instead of 'origin' to track upstream",
115 metavar='REMOTE')
116 group.add_option('-b', '--manifest-branch',
117 dest='manifest_branch',
118 help='manifest branch or revision', metavar='REVISION')
119 group.add_option('-m', '--manifest-name',
120 dest='manifest_name',
121 help='initial manifest file (deprecated)',
122 metavar='NAME.xml')
123 group.add_option('--mirror',
124 dest='mirror', action='store_true',
125 help='mirror the forrest')
126
127 # Tool
128 group = init_optparse.add_option_group('repo Version options')
129 group.add_option('--repo-url',
130 dest='repo_url',
131 help='repo repository location', metavar='URL')
132 group.add_option('--repo-branch',
133 dest='repo_branch',
134 help='repo branch or revision', metavar='REVISION')
135 group.add_option('--no-repo-verify',
136 dest='no_repo_verify', action='store_true',
137 help='do not verify repo source code')
138
139
140 class CloneFailure(Exception):
141 """Indicate the remote clone of repo itself failed.
142 """
143
144
145 def _Init(args):
146 """Installs repo by cloning it over the network.
147 """
148 opt, args = init_optparse.parse_args(args)
149 if args or not opt.manifest_url:
150 init_optparse.print_usage()
151 sys.exit(1)
152
153 url = opt.repo_url
154 if not url:
155 url = REPO_URL
156 extra_args.append('--repo-url=%s' % url)
157
158 branch = opt.repo_branch
159 if not branch:
160 branch = REPO_REV
161 extra_args.append('--repo-branch=%s' % branch)
162
163 if branch.startswith('refs/heads/'):
164 branch = branch[len('refs/heads/'):]
165 if branch.startswith('refs/'):
166 print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
167 raise CloneFailure()
168
169 if not os.path.isdir(repodir):
170 try:
171 os.mkdir(repodir)
172 except OSError, e:
173 print >>sys.stderr, \
174 'fatal: cannot make %s directory: %s' % (
175 repodir, e.strerror)
176 # Don't faise CloneFailure; that would delete the
177 # name. Instead exit immediately.
178 #
179 sys.exit(1)
180
181 _CheckGitVersion()
182 try:
183 if _NeedSetupGnuPG():
184 can_verify = _SetupGnuPG(opt.quiet)
185 else:
186 can_verify = True
187
188 if not opt.quiet:
189 print >>sys.stderr, 'Getting repo ...'
190 print >>sys.stderr, ' from %s' % url
191
192 dst = os.path.abspath(os.path.join(repodir, S_repo))
193 _Clone(url, dst, opt.quiet)
194
195 if can_verify and not opt.no_repo_verify:
196 rev = _Verify(dst, branch, opt.quiet)
197 else:
198 rev = 'refs/remotes/origin/%s^0' % branch
199
200 _Checkout(dst, branch, rev, opt.quiet)
201 except CloneFailure:
202 if opt.quiet:
203 print >>sys.stderr, \
204 'fatal: repo init failed; run without --quiet to see why'
205 raise
206
207
208 def _CheckGitVersion():
209 cmd = [GIT, '--version']
210 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
211 ver_str = proc.stdout.read().strip()
212 proc.stdout.close()
213 proc.wait()
214
215 if not ver_str.startswith('git version '):
216 print >>sys.stderr, 'error: "%s" unsupported' % ver_str
217 raise CloneFailure()
218
219 ver_str = ver_str[len('git version '):].strip()
220 ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
221 if ver_act < MIN_GIT_VERSION:
222 need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
223 print >>sys.stderr, 'fatal: git %s or later required' % need
224 raise CloneFailure()
225
226
227 def _NeedSetupGnuPG():
228 if not os.path.isdir(home_dot_repo):
229 return True
230
231 kv = os.path.join(home_dot_repo, 'keyring-version')
232 if not os.path.exists(kv):
233 return True
234
235 kv = open(kv).read()
236 if not kv:
237 return True
238
239 kv = tuple(map(lambda x: int(x), kv.split('.')))
240 if kv < KEYRING_VERSION:
241 return True
242 return False
243
244
245 def _SetupGnuPG(quiet):
246 if not os.path.isdir(home_dot_repo):
247 try:
248 os.mkdir(home_dot_repo)
249 except OSError, e:
250 print >>sys.stderr, \
251 'fatal: cannot make %s directory: %s' % (
252 home_dot_repo, e.strerror)
253 sys.exit(1)
254
255 if not os.path.isdir(gpg_dir):
256 try:
257 os.mkdir(gpg_dir, 0700)
258 except OSError, e:
259 print >>sys.stderr, \
260 'fatal: cannot make %s directory: %s' % (
261 gpg_dir, e.strerror)
262 sys.exit(1)
263
264 env = dict(os.environ)
265 env['GNUPGHOME'] = gpg_dir
266
267 cmd = ['gpg', '--import']
268 try:
269 proc = subprocess.Popen(cmd,
270 env = env,
271 stdin = subprocess.PIPE)
272 except OSError, e:
273 if not quiet:
274 print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
275 print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
276 print >>sys.stderr
277 return False
278
279 proc.stdin.write(MAINTAINER_KEYS)
280 proc.stdin.close()
281
282 if proc.wait() != 0:
283 print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
284 sys.exit(1)
285 print
286
287 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
288 fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
289 fd.close()
290 return True
291
292
293 def _SetConfig(local, name, value):
294 """Set a git configuration option to the specified value.
295 """
296 cmd = [GIT, 'config', name, value]
297 if subprocess.Popen(cmd, cwd = local).wait() != 0:
298 raise CloneFailure()
299
300
301 def _Fetch(local, quiet, *args):
302 cmd = [GIT, 'fetch']
303 if quiet:
304 cmd.append('--quiet')
305 err = subprocess.PIPE
306 else:
307 err = None
308 cmd.extend(args)
309 cmd.append('origin')
310
311 proc = subprocess.Popen(cmd, cwd = local, stderr = err)
312 if err:
313 proc.stderr.read()
314 proc.stderr.close()
315 if proc.wait() != 0:
316 raise CloneFailure()
317
318
319 def _Clone(url, local, quiet):
320 """Clones a git repository to a new subdirectory of repodir
321 """
322 try:
323 os.mkdir(local)
324 except OSError, e:
325 print >>sys.stderr, \
326 'fatal: cannot make %s directory: %s' \
327 % (local, e.strerror)
328 raise CloneFailure()
329
330 cmd = [GIT, 'init', '--quiet']
331 try:
332 proc = subprocess.Popen(cmd, cwd = local)
333 except OSError, e:
334 print >>sys.stderr
335 print >>sys.stderr, "fatal: '%s' is not available" % GIT
336 print >>sys.stderr, 'fatal: %s' % e
337 print >>sys.stderr
338 print >>sys.stderr, 'Please make sure %s is installed'\
339 ' and in your path.' % GIT
340 raise CloneFailure()
341 if proc.wait() != 0:
342 print >>sys.stderr, 'fatal: could not create %s' % local
343 raise CloneFailure()
344
345 _SetConfig(local, 'remote.origin.url', url)
346 _SetConfig(local, 'remote.origin.fetch',
347 '+refs/heads/*:refs/remotes/origin/*')
348 _Fetch(local, quiet)
349 _Fetch(local, quiet, '--tags')
350
351
352 def _Verify(cwd, branch, quiet):
353 """Verify the branch has been signed by a tag.
354 """
355 cmd = [GIT, 'describe', 'origin/%s' % branch]
356 proc = subprocess.Popen(cmd,
357 stdout=subprocess.PIPE,
358 stderr=subprocess.PIPE,
359 cwd = cwd)
360 cur = proc.stdout.read().strip()
361 proc.stdout.close()
362
363 proc.stderr.read()
364 proc.stderr.close()
365
366 if proc.wait() != 0 or not cur:
367 print >>sys.stderr
368 print >>sys.stderr,\
369 "fatal: branch '%s' has not been signed" \
370 % branch
371 raise CloneFailure()
372
373 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
374 if m:
375 cur = m.group(1)
376 if not quiet:
377 print >>sys.stderr
378 print >>sys.stderr, \
379 "info: Ignoring branch '%s'; using tagged release '%s'" \
380 % (branch, cur)
381 print >>sys.stderr
382
383 env = dict(os.environ)
384 env['GNUPGHOME'] = gpg_dir
385
386 cmd = [GIT, 'tag', '-v', cur]
387 proc = subprocess.Popen(cmd,
388 stdout = subprocess.PIPE,
389 stderr = subprocess.PIPE,
390 cwd = cwd,
391 env = env)
392 out = proc.stdout.read()
393 proc.stdout.close()
394
395 err = proc.stderr.read()
396 proc.stderr.close()
397
398 if proc.wait() != 0:
399 print >>sys.stderr
400 print >>sys.stderr, out
401 print >>sys.stderr, err
402 print >>sys.stderr
403 raise CloneFailure()
404 return '%s^0' % cur
405
406
407 def _Checkout(cwd, branch, rev, quiet):
408 """Checkout an upstream branch into the repository and track it.
409 """
410 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
411 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
412 raise CloneFailure()
413
414 _SetConfig(cwd, 'branch.default.remote', 'origin')
415 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
416
417 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
418 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
419 raise CloneFailure()
420
421 cmd = [GIT, 'read-tree', '--reset', '-u']
422 if not quiet:
423 cmd.append('-v')
424 cmd.append('HEAD')
425 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
426 raise CloneFailure()
427
428
429 def _FindRepo():
430 """Look for a repo installation, starting at the current directory.
431 """
432 dir = os.getcwd()
433 repo = None
434
435 while dir != '/' and not repo:
436 repo = os.path.join(dir, repodir, REPO_MAIN)
437 if not os.path.isfile(repo):
438 repo = None
439 dir = os.path.dirname(dir)
440 return (repo, os.path.join(dir, repodir))
441
442
443 class _Options:
444 help = False
445
446
447 def _ParseArguments(args):
448 cmd = None
449 opt = _Options()
450 arg = []
451
452 for i in xrange(0, len(args)):
453 a = args[i]
454 if a == '-h' or a == '--help':
455 opt.help = True
456
457 elif not a.startswith('-'):
458 cmd = a
459 arg = args[i + 1:]
460 break
461 return cmd, opt, arg
462
463
464 def _Usage():
465 print >>sys.stderr,\
466 """usage: repo COMMAND [ARGS]
467
468 repo is not yet installed. Use "repo init" to install it here.
469
470 The most commonly used repo commands are:
471
472 init Install repo in the current working directory
473 help Display detailed help on a command
474
475 For access to the full online help, install repo ("repo init").
476 """
477 sys.exit(1)
478
479
480 def _Help(args):
481 if args:
482 if args[0] == 'init':
483 init_optparse.print_help()
484 else:
485 print >>sys.stderr,\
486 "error: '%s' is not a bootstrap command.\n"\
487 ' For access to online help, install repo ("repo init").'\
488 % args[0]
489 else:
490 _Usage()
491 sys.exit(1)
492
493
494 def _NotInstalled():
495 print >>sys.stderr,\
496 'error: repo is not installed. Use "repo init" to install it here.'
497 sys.exit(1)
498
499
500 def _NoCommands(cmd):
501 print >>sys.stderr,\
502 """error: command '%s' requires repo to be installed first.
503 Use "repo init" to install it here.""" % cmd
504 sys.exit(1)
505
506
507 def _RunSelf(wrapper_path):
508 my_dir = os.path.dirname(wrapper_path)
509 my_main = os.path.join(my_dir, 'main.py')
510 my_git = os.path.join(my_dir, '.git')
511
512 if os.path.isfile(my_main) and os.path.isdir(my_git):
513 for name in ['git_config.py',
514 'project.py',
515 'subcmds']:
516 if not os.path.exists(os.path.join(my_dir, name)):
517 return None, None
518 return my_main, my_git
519 return None, None
520
521
522 def _SetDefaultsTo(gitdir):
523 global REPO_URL
524 global REPO_REV
525
526 REPO_URL = gitdir
527 proc = subprocess.Popen([GIT,
528 '--git-dir=%s' % gitdir,
529 'symbolic-ref',
530 'HEAD'],
531 stdout = subprocess.PIPE,
532 stderr = subprocess.PIPE)
533 REPO_REV = proc.stdout.read().strip()
534 proc.stdout.close()
535
536 proc.stderr.read()
537 proc.stderr.close()
538
539 if proc.wait() != 0:
540 print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
541 sys.exit(1)
542
543
544 def main(orig_args):
545 main, dir = _FindRepo()
546 cmd, opt, args = _ParseArguments(orig_args)
547
548 wrapper_path = os.path.abspath(__file__)
549 my_main, my_git = _RunSelf(wrapper_path)
550
551 if not main:
552 if opt.help:
553 _Usage()
554 if cmd == 'help':
555 _Help(args)
556 if not cmd:
557 _NotInstalled()
558 if cmd == 'init':
559 if my_git:
560 _SetDefaultsTo(my_git)
561 try:
562 _Init(args)
563 except CloneFailure:
564 for root, dirs, files in os.walk(repodir, topdown=False):
565 for name in files:
566 os.remove(os.path.join(root, name))
567 for name in dirs:
568 os.rmdir(os.path.join(root, name))
569 os.rmdir(repodir)
570 sys.exit(1)
571 main, dir = _FindRepo()
572 else:
573 _NoCommands(cmd)
574
575 if my_main:
576 main = my_main
577
578 ver_str = '.'.join(map(lambda x: str(x), VERSION))
579 me = [main,
580 '--repo-dir=%s' % dir,
581 '--wrapper-version=%s' % ver_str,
582 '--wrapper-path=%s' % wrapper_path,
583 '--']
584 me.extend(orig_args)
585 me.extend(extra_args)
586 try:
587 os.execv(main, me)
588 except OSError, e:
589 print >>sys.stderr, "fatal: unable to start %s" % main
590 print >>sys.stderr, "fatal: %s" % e
591 sys.exit(148)
592
593
594 if __name__ == '__main__':
595 main(sys.argv[1:])
596
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698