blob: 75fe9ec2eab2fc8b4e72022e3984d70341dfd892 [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001#!/bin/sh
2
3## repo default configuration
4##
Shawn O. Pearce44da16e2011-09-05 14:02:38 -07005REPO_URL='https://code.google.com/p/git-repo/'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07006REPO_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
22magic='--calling-python-from-/bin/sh--'
Shawn O. Pearce7542d662008-10-21 07:11:36 -070023"""exec" python -E "$0" "$@" """#$magic"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070024if __name__ == '__main__':
25 import sys
26 if sys.argv[-1] == '#%s' % magic:
27 del sys.argv[-1]
28del magic
29
30# increment this whenever we make important changes to this script
Colin Cross5acde752012-03-28 20:15:45 -070031VERSION = (1, 15)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070032
33# increment this if the MAINTAINER_KEYS block is modified
34KEYRING_VERSION = (1,0)
35MAINTAINER_KEYS = """
36
37 Repo Maintainer <repo@android.kernel.org>
38-----BEGIN PGP PUBLIC KEY BLOCK-----
39Version: GnuPG v1.4.2.2 (GNU/Linux)
40
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
76=CMiZ
77-----END PGP PUBLIC KEY BLOCK-----
78"""
79
80GIT = 'git' # our git command
81MIN_GIT_VERSION = (1, 5, 4) # minimum supported git version
82repodir = '.repo' # name of repo's private directory
83S_repo = 'repo' # special repo reposiory
84S_manifests = 'manifests' # special manifest repository
85REPO_MAIN = S_repo + '/main.py' # main script
86
87
88import optparse
89import os
90import re
91import readline
92import subprocess
93import sys
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070094import urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070095
96home_dot_repo = os.path.expanduser('~/.repoconfig')
97gpg_dir = os.path.join(home_dot_repo, 'gnupg')
98
99extra_args = []
100init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
101
102# Logging
103group = init_optparse.add_option_group('Logging options')
104group.add_option('-q', '--quiet',
105 dest="quiet", action="store_true", default=False,
106 help="be quiet")
107
108# Manifest
109group = init_optparse.add_option_group('Manifest options')
110group.add_option('-u', '--manifest-url',
111 dest='manifest_url',
112 help='manifest repository location', metavar='URL')
113group.add_option('-b', '--manifest-branch',
114 dest='manifest_branch',
115 help='manifest branch or revision', metavar='REVISION')
116group.add_option('-m', '--manifest-name',
117 dest='manifest_name',
118 help='initial manifest file', metavar='NAME.xml')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800119group.add_option('--mirror',
120 dest='mirror', action='store_true',
121 help='mirror the forrest')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200122group.add_option('--reference',
123 dest='reference',
124 help='location of mirror directory', metavar='DIR')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700125group.add_option('--depth', type='int', default=None,
126 dest='depth',
127 help='create a shallow clone with given depth; see git clone')
Colin Cross5acde752012-03-28 20:15:45 -0700128group.add_option('-g', '--groups',
129 dest='groups', default="",
130 help='restrict manifest projects to ones with a specified group',
131 metavar='GROUP')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700132
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700133
134# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700135group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700136group.add_option('--repo-url',
137 dest='repo_url',
138 help='repo repository location', metavar='URL')
139group.add_option('--repo-branch',
140 dest='repo_branch',
141 help='repo branch or revision', metavar='REVISION')
142group.add_option('--no-repo-verify',
143 dest='no_repo_verify', action='store_true',
144 help='do not verify repo source code')
145
Victor Boivie841be342011-04-05 11:31:10 +0200146# Other
147group = init_optparse.add_option_group('Other options')
148group.add_option('--config-name',
149 dest='config_name', action="store_true", default=False,
150 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700151
152class CloneFailure(Exception):
153 """Indicate the remote clone of repo itself failed.
154 """
155
156
157def _Init(args):
158 """Installs repo by cloning it over the network.
159 """
160 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800161 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700162 init_optparse.print_usage()
163 sys.exit(1)
164
165 url = opt.repo_url
166 if not url:
167 url = REPO_URL
168 extra_args.append('--repo-url=%s' % url)
169
170 branch = opt.repo_branch
171 if not branch:
172 branch = REPO_REV
173 extra_args.append('--repo-branch=%s' % branch)
174
175 if branch.startswith('refs/heads/'):
176 branch = branch[len('refs/heads/'):]
177 if branch.startswith('refs/'):
178 print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
179 raise CloneFailure()
180
181 if not os.path.isdir(repodir):
182 try:
183 os.mkdir(repodir)
184 except OSError, e:
185 print >>sys.stderr, \
186 'fatal: cannot make %s directory: %s' % (
187 repodir, e.strerror)
188 # Don't faise CloneFailure; that would delete the
189 # name. Instead exit immediately.
190 #
191 sys.exit(1)
192
193 _CheckGitVersion()
194 try:
195 if _NeedSetupGnuPG():
196 can_verify = _SetupGnuPG(opt.quiet)
197 else:
198 can_verify = True
199
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700200 dst = os.path.abspath(os.path.join(repodir, S_repo))
201 _Clone(url, dst, opt.quiet)
202
203 if can_verify and not opt.no_repo_verify:
204 rev = _Verify(dst, branch, opt.quiet)
205 else:
206 rev = 'refs/remotes/origin/%s^0' % branch
207
208 _Checkout(dst, branch, rev, opt.quiet)
209 except CloneFailure:
210 if opt.quiet:
211 print >>sys.stderr, \
212 'fatal: repo init failed; run without --quiet to see why'
213 raise
214
215
216def _CheckGitVersion():
217 cmd = [GIT, '--version']
218 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
219 ver_str = proc.stdout.read().strip()
220 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700221 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700222
223 if not ver_str.startswith('git version '):
224 print >>sys.stderr, 'error: "%s" unsupported' % ver_str
225 raise CloneFailure()
226
227 ver_str = ver_str[len('git version '):].strip()
228 ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
229 if ver_act < MIN_GIT_VERSION:
230 need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
231 print >>sys.stderr, 'fatal: git %s or later required' % need
232 raise CloneFailure()
233
234
235def _NeedSetupGnuPG():
236 if not os.path.isdir(home_dot_repo):
237 return True
238
239 kv = os.path.join(home_dot_repo, 'keyring-version')
240 if not os.path.exists(kv):
241 return True
242
243 kv = open(kv).read()
244 if not kv:
245 return True
246
247 kv = tuple(map(lambda x: int(x), kv.split('.')))
248 if kv < KEYRING_VERSION:
249 return True
250 return False
251
252
253def _SetupGnuPG(quiet):
254 if not os.path.isdir(home_dot_repo):
255 try:
256 os.mkdir(home_dot_repo)
257 except OSError, e:
258 print >>sys.stderr, \
259 'fatal: cannot make %s directory: %s' % (
260 home_dot_repo, e.strerror)
261 sys.exit(1)
262
263 if not os.path.isdir(gpg_dir):
264 try:
265 os.mkdir(gpg_dir, 0700)
266 except OSError, e:
267 print >>sys.stderr, \
268 'fatal: cannot make %s directory: %s' % (
269 gpg_dir, e.strerror)
270 sys.exit(1)
271
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800272 env = os.environ.copy()
273 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700274
275 cmd = ['gpg', '--import']
276 try:
277 proc = subprocess.Popen(cmd,
278 env = env,
279 stdin = subprocess.PIPE)
280 except OSError, e:
281 if not quiet:
282 print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
283 print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
284 print >>sys.stderr
285 return False
286
287 proc.stdin.write(MAINTAINER_KEYS)
288 proc.stdin.close()
289
290 if proc.wait() != 0:
291 print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
292 sys.exit(1)
293 print
294
295 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
296 fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
297 fd.close()
298 return True
299
300
301def _SetConfig(local, name, value):
302 """Set a git configuration option to the specified value.
303 """
304 cmd = [GIT, 'config', name, value]
305 if subprocess.Popen(cmd, cwd = local).wait() != 0:
306 raise CloneFailure()
307
308
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700309def _InitHttp():
310 handlers = []
311
312 mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
313 try:
314 import netrc
315 n = netrc.netrc()
316 for host in n.hosts:
317 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800318 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
319 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700320 except:
321 pass
322 handlers.append(urllib2.HTTPBasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800323 handlers.append(urllib2.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700324
325 if 'http_proxy' in os.environ:
326 url = os.environ['http_proxy']
327 handlers.append(urllib2.ProxyHandler({'http': url, 'https': url}))
328 if 'REPO_CURL_VERBOSE' in os.environ:
329 handlers.append(urllib2.HTTPHandler(debuglevel=1))
330 handlers.append(urllib2.HTTPSHandler(debuglevel=1))
331 urllib2.install_opener(urllib2.build_opener(*handlers))
332
333def _Fetch(url, local, src, quiet):
334 if not quiet:
335 print >>sys.stderr, 'Get %s' % url
336
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700337 cmd = [GIT, 'fetch']
338 if quiet:
339 cmd.append('--quiet')
340 err = subprocess.PIPE
341 else:
342 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700343 cmd.append(src)
344 cmd.append('+refs/heads/*:refs/remotes/origin/*')
345 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700346
347 proc = subprocess.Popen(cmd, cwd = local, stderr = err)
348 if err:
349 proc.stderr.read()
350 proc.stderr.close()
351 if proc.wait() != 0:
352 raise CloneFailure()
353
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700354def _DownloadBundle(url, local, quiet):
355 if not url.endswith('/'):
356 url += '/'
357 url += 'clone.bundle'
358
359 proc = subprocess.Popen(
360 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
361 cwd = local,
362 stdout = subprocess.PIPE)
363 for line in proc.stdout:
364 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
365 if m:
366 new_url = m.group(1)
367 old_url = m.group(2)
368 if url.startswith(old_url):
369 url = new_url + url[len(old_url):]
370 break
371 proc.stdout.close()
372 proc.wait()
373
374 if not url.startswith('http:') and not url.startswith('https:'):
375 return False
376
377 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
378 try:
379 try:
380 r = urllib2.urlopen(url)
381 except urllib2.HTTPError, e:
382 if e.code == 404:
383 return False
384 print >>sys.stderr, 'fatal: Cannot get %s' % url
385 print >>sys.stderr, 'fatal: HTTP error %s' % e.code
386 raise CloneFailure()
387 except urllib2.URLError, e:
388 print >>sys.stderr, 'fatal: Cannot get %s' % url
389 print >>sys.stderr, 'fatal: error %s' % e.reason
390 raise CloneFailure()
391 try:
392 if not quiet:
393 print >>sys.stderr, 'Get %s' % url
394 while True:
395 buf = r.read(8192)
396 if buf == '':
397 return True
398 dest.write(buf)
399 finally:
400 r.close()
401 finally:
402 dest.close()
403
404def _ImportBundle(local):
405 path = os.path.join(local, '.git', 'clone.bundle')
406 try:
407 _Fetch(local, local, path, True)
408 finally:
409 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700410
411def _Clone(url, local, quiet):
412 """Clones a git repository to a new subdirectory of repodir
413 """
414 try:
415 os.mkdir(local)
416 except OSError, e:
417 print >>sys.stderr, \
418 'fatal: cannot make %s directory: %s' \
419 % (local, e.strerror)
420 raise CloneFailure()
421
422 cmd = [GIT, 'init', '--quiet']
423 try:
424 proc = subprocess.Popen(cmd, cwd = local)
425 except OSError, e:
426 print >>sys.stderr
427 print >>sys.stderr, "fatal: '%s' is not available" % GIT
428 print >>sys.stderr, 'fatal: %s' % e
429 print >>sys.stderr
430 print >>sys.stderr, 'Please make sure %s is installed'\
431 ' and in your path.' % GIT
432 raise CloneFailure()
433 if proc.wait() != 0:
434 print >>sys.stderr, 'fatal: could not create %s' % local
435 raise CloneFailure()
436
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700437 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700438 _SetConfig(local, 'remote.origin.url', url)
439 _SetConfig(local, 'remote.origin.fetch',
440 '+refs/heads/*:refs/remotes/origin/*')
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700441 if _DownloadBundle(url, local, quiet):
442 _ImportBundle(local)
443 else:
444 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700445
446
447def _Verify(cwd, branch, quiet):
448 """Verify the branch has been signed by a tag.
449 """
450 cmd = [GIT, 'describe', 'origin/%s' % branch]
451 proc = subprocess.Popen(cmd,
452 stdout=subprocess.PIPE,
453 stderr=subprocess.PIPE,
454 cwd = cwd)
455 cur = proc.stdout.read().strip()
456 proc.stdout.close()
457
458 proc.stderr.read()
459 proc.stderr.close()
460
461 if proc.wait() != 0 or not cur:
462 print >>sys.stderr
463 print >>sys.stderr,\
464 "fatal: branch '%s' has not been signed" \
465 % branch
466 raise CloneFailure()
467
468 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
469 if m:
470 cur = m.group(1)
471 if not quiet:
472 print >>sys.stderr
473 print >>sys.stderr, \
474 "info: Ignoring branch '%s'; using tagged release '%s'" \
475 % (branch, cur)
476 print >>sys.stderr
477
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800478 env = os.environ.copy()
479 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700480
481 cmd = [GIT, 'tag', '-v', cur]
482 proc = subprocess.Popen(cmd,
483 stdout = subprocess.PIPE,
484 stderr = subprocess.PIPE,
485 cwd = cwd,
486 env = env)
487 out = proc.stdout.read()
488 proc.stdout.close()
489
490 err = proc.stderr.read()
491 proc.stderr.close()
492
493 if proc.wait() != 0:
494 print >>sys.stderr
495 print >>sys.stderr, out
496 print >>sys.stderr, err
497 print >>sys.stderr
498 raise CloneFailure()
499 return '%s^0' % cur
500
501
502def _Checkout(cwd, branch, rev, quiet):
503 """Checkout an upstream branch into the repository and track it.
504 """
505 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
506 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
507 raise CloneFailure()
508
509 _SetConfig(cwd, 'branch.default.remote', 'origin')
510 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
511
512 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
513 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
514 raise CloneFailure()
515
516 cmd = [GIT, 'read-tree', '--reset', '-u']
517 if not quiet:
518 cmd.append('-v')
519 cmd.append('HEAD')
520 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
521 raise CloneFailure()
522
523
524def _FindRepo():
525 """Look for a repo installation, starting at the current directory.
526 """
527 dir = os.getcwd()
528 repo = None
529
Anthony Newnamdf14a702011-01-09 17:31:57 -0800530 olddir = None
531 while dir != '/' \
532 and dir != olddir \
533 and not repo:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700534 repo = os.path.join(dir, repodir, REPO_MAIN)
535 if not os.path.isfile(repo):
536 repo = None
Anthony Newnamdf14a702011-01-09 17:31:57 -0800537 olddir = dir
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700538 dir = os.path.dirname(dir)
539 return (repo, os.path.join(dir, repodir))
540
541
542class _Options:
543 help = False
544
545
546def _ParseArguments(args):
547 cmd = None
548 opt = _Options()
549 arg = []
550
551 for i in xrange(0, len(args)):
552 a = args[i]
553 if a == '-h' or a == '--help':
554 opt.help = True
555
556 elif not a.startswith('-'):
557 cmd = a
558 arg = args[i + 1:]
559 break
560 return cmd, opt, arg
561
562
563def _Usage():
564 print >>sys.stderr,\
565"""usage: repo COMMAND [ARGS]
566
567repo is not yet installed. Use "repo init" to install it here.
568
569The most commonly used repo commands are:
570
571 init Install repo in the current working directory
572 help Display detailed help on a command
573
574For access to the full online help, install repo ("repo init").
575"""
576 sys.exit(1)
577
578
579def _Help(args):
580 if args:
581 if args[0] == 'init':
582 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100583 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700584 else:
585 print >>sys.stderr,\
586 "error: '%s' is not a bootstrap command.\n"\
587 ' For access to online help, install repo ("repo init").'\
588 % args[0]
589 else:
590 _Usage()
591 sys.exit(1)
592
593
594def _NotInstalled():
595 print >>sys.stderr,\
596'error: repo is not installed. Use "repo init" to install it here.'
597 sys.exit(1)
598
599
600def _NoCommands(cmd):
601 print >>sys.stderr,\
602"""error: command '%s' requires repo to be installed first.
603 Use "repo init" to install it here.""" % cmd
604 sys.exit(1)
605
606
607def _RunSelf(wrapper_path):
608 my_dir = os.path.dirname(wrapper_path)
609 my_main = os.path.join(my_dir, 'main.py')
610 my_git = os.path.join(my_dir, '.git')
611
612 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700613 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700614 'project.py',
615 'subcmds']:
616 if not os.path.exists(os.path.join(my_dir, name)):
617 return None, None
618 return my_main, my_git
619 return None, None
620
621
622def _SetDefaultsTo(gitdir):
623 global REPO_URL
624 global REPO_REV
625
626 REPO_URL = gitdir
627 proc = subprocess.Popen([GIT,
628 '--git-dir=%s' % gitdir,
629 'symbolic-ref',
630 'HEAD'],
631 stdout = subprocess.PIPE,
632 stderr = subprocess.PIPE)
633 REPO_REV = proc.stdout.read().strip()
634 proc.stdout.close()
635
636 proc.stderr.read()
637 proc.stderr.close()
638
639 if proc.wait() != 0:
640 print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
641 sys.exit(1)
642
643
644def main(orig_args):
645 main, dir = _FindRepo()
646 cmd, opt, args = _ParseArguments(orig_args)
647
648 wrapper_path = os.path.abspath(__file__)
649 my_main, my_git = _RunSelf(wrapper_path)
650
651 if not main:
652 if opt.help:
653 _Usage()
654 if cmd == 'help':
655 _Help(args)
656 if not cmd:
657 _NotInstalled()
658 if cmd == 'init':
659 if my_git:
660 _SetDefaultsTo(my_git)
661 try:
662 _Init(args)
663 except CloneFailure:
664 for root, dirs, files in os.walk(repodir, topdown=False):
665 for name in files:
666 os.remove(os.path.join(root, name))
667 for name in dirs:
668 os.rmdir(os.path.join(root, name))
669 os.rmdir(repodir)
670 sys.exit(1)
671 main, dir = _FindRepo()
672 else:
673 _NoCommands(cmd)
674
675 if my_main:
676 main = my_main
677
678 ver_str = '.'.join(map(lambda x: str(x), VERSION))
679 me = [main,
680 '--repo-dir=%s' % dir,
681 '--wrapper-version=%s' % ver_str,
682 '--wrapper-path=%s' % wrapper_path,
683 '--']
684 me.extend(orig_args)
685 me.extend(extra_args)
686 try:
687 os.execv(main, me)
688 except OSError, e:
689 print >>sys.stderr, "fatal: unable to start %s" % main
690 print >>sys.stderr, "fatal: %s" % e
691 sys.exit(148)
692
693
694if __name__ == '__main__':
695 main(sys.argv[1:])