git_archive_all.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. #! /usr/bin/env python
  2. # coding=utf-8
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) 2010 Ilya Kulakov
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy
  8. # of this software and associated documentation files (the "Software"), to deal
  9. # in the Software without restriction, including without limitation the rights
  10. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. # copies of the Software, and to permit persons to whom the Software is
  12. # furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in
  15. # all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. # THE SOFTWARE.
  24. from __future__ import print_function
  25. from __future__ import unicode_literals
  26. import logging
  27. from os import environ, extsep, path, readlink
  28. from subprocess import CalledProcessError, Popen, PIPE
  29. import sys
  30. import re
  31. __version__ = "1.23.1"
  32. try:
  33. # Python 3.2+
  34. from os import fsdecode
  35. except ImportError:
  36. def fsdecode(filename):
  37. if not isinstance(filename, unicode):
  38. return filename.decode(sys.getfilesystemencoding(), 'strict')
  39. else:
  40. return filename
  41. try:
  42. # Python 3.2+
  43. from os import fsencode
  44. except ImportError:
  45. def fsencode(filename):
  46. if not isinstance(filename, bytes):
  47. return filename.encode(sys.getfilesystemencoding(), 'strict')
  48. else:
  49. return filename
  50. def git_fsdecode(filename):
  51. """
  52. Decode filename from git output into str.
  53. """
  54. if sys.platform.startswith('win32'):
  55. return filename.decode('utf-8')
  56. else:
  57. return fsdecode(filename)
  58. def git_fsencode(filename):
  59. """
  60. Encode filename from str into git input.
  61. """
  62. if sys.platform.startswith('win32'):
  63. return filename.encode('utf-8')
  64. else:
  65. return fsencode(filename)
  66. try:
  67. # Python 3.6+
  68. from os import fspath as _fspath
  69. def fspath(filename, decoder=fsdecode, encoder=fsencode):
  70. """
  71. Convert filename into bytes or str, depending on what's the best type
  72. to represent paths for current Python and platform.
  73. """
  74. # Python 3.6+: str can represent any path (PEP 383)
  75. # str is not required on Windows (PEP 529)
  76. # Decoding is still applied for consistency and to follow PEP 519 recommendation.
  77. return decoder(_fspath(filename))
  78. except ImportError:
  79. def fspath(filename, decoder=fsdecode, encoder=fsencode):
  80. # Python 3.4 and 3.5: str can represent any path (PEP 383),
  81. # but str is required on Windows (no PEP 529)
  82. #
  83. # Python 2.6 and 2.7: str cannot represent any path (no PEP 383),
  84. # str is required on Windows (no PEP 529)
  85. # bytes is required on POSIX (no PEP 383)
  86. if sys.version_info > (3,):
  87. import pathlib
  88. if isinstance(filename, pathlib.PurePath):
  89. return str(filename)
  90. else:
  91. return decoder(filename)
  92. elif sys.platform.startswith('win32'):
  93. return decoder(filename)
  94. else:
  95. return encoder(filename)
  96. def git_fspath(filename):
  97. """
  98. fspath representation of git output.
  99. """
  100. return fspath(filename, git_fsdecode, git_fsencode)
  101. class GitArchiver(object):
  102. """
  103. GitArchiver
  104. Scan a git repository and export all tracked files, and submodules.
  105. Checks for .gitattributes files in each directory and uses 'export-ignore'
  106. pattern entries for ignore files in the archive.
  107. >>> archiver = GitArchiver(main_repo_abspath='my/repo/path')
  108. >>> archiver.create('output.zip')
  109. """
  110. TARFILE_FORMATS = {
  111. 'tar': 'w',
  112. 'tbz2': 'w:bz2',
  113. 'tgz': 'w:gz',
  114. 'txz': 'w:xz',
  115. 'bz2': 'w:bz2',
  116. 'gz': 'w:gz',
  117. 'xz': 'w:xz'
  118. }
  119. ZIPFILE_FORMATS = ('zip',)
  120. LOG = logging.getLogger('GitArchiver')
  121. def __init__(self, prefix='', exclude=True, force_sub=False, extra=None, main_repo_abspath=None, git_version=None):
  122. """
  123. @param prefix: Prefix used to prepend all paths in the resulting archive.
  124. Extra file paths are only prefixed if they are not relative.
  125. E.g. if prefix is 'foo' and extra is ['bar', '/baz'] the resulting archive will look like this:
  126. /
  127. baz
  128. foo/
  129. bar
  130. @param exclude: Determines whether archiver should follow rules specified in .gitattributes files.
  131. @param force_sub: Determines whether submodules are initialized and updated before archiving.
  132. @param extra: List of extra paths to include in the resulting archive.
  133. @param main_repo_abspath: Absolute path to the main repository (or one of subdirectories).
  134. If given path is path to a subdirectory (but not a submodule directory!) it will be replaced
  135. with abspath to top-level directory of the repository.
  136. If None, current cwd is used.
  137. @param git_version: Version of Git that determines whether various workarounds are on.
  138. If None, tries to resolve via Git's CLI.
  139. """
  140. self._check_attr_gens = {}
  141. self._ignored_paths_cache = {}
  142. if git_version is None:
  143. git_version = self.get_git_version()
  144. if git_version is not None and git_version < (1, 6, 1):
  145. raise ValueError("git of version 1.6.1 and higher is required")
  146. self.git_version = git_version
  147. if main_repo_abspath is None:
  148. main_repo_abspath = path.abspath('')
  149. elif not path.isabs(main_repo_abspath):
  150. raise ValueError("main_repo_abspath must be an absolute path")
  151. self.main_repo_abspath = self.resolve_git_main_repo_abspath(main_repo_abspath)
  152. self.prefix = fspath(prefix)
  153. self.exclude = exclude
  154. self.extra = [fspath(e) for e in extra] if extra is not None else []
  155. self.force_sub = force_sub
  156. def create(self, output_path, dry_run=False, output_format=None, compresslevel=None):
  157. """
  158. Create the archive at output_file_path.
  159. Type of the archive is determined either by extension of output_file_path or by output_format.
  160. Supported formats are: gz, zip, bz2, xz, tar, tgz, txz
  161. @param output_path: Output file path.
  162. @param dry_run: Determines whether create should do nothing but print what it would archive.
  163. @param output_format: Determines format of the output archive. If None, format is determined from extension
  164. of output_file_path.
  165. @param compresslevel: Optional compression level. Interpretation depends on the output format.
  166. """
  167. output_path = fspath(output_path)
  168. if output_format is None:
  169. file_name, file_ext = path.splitext(output_path)
  170. output_format = file_ext[len(extsep):].lower()
  171. self.LOG.debug("Output format is not explicitly set, determined format is {0}.".format(output_format))
  172. if not dry_run:
  173. if output_format in self.ZIPFILE_FORMATS:
  174. from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED
  175. if compresslevel is not None:
  176. if sys.version_info > (3, 7):
  177. archive = ZipFile(path.abspath(output_path), 'w', compresslevel=compresslevel)
  178. else:
  179. raise ValueError("Compression level for zip archives requires Python 3.7+")
  180. else:
  181. archive = ZipFile(path.abspath(output_path), 'w')
  182. def add_file(file_path, arcname):
  183. if not path.islink(file_path):
  184. archive.write(file_path, arcname, ZIP_DEFLATED)
  185. else:
  186. i = ZipInfo(arcname)
  187. i.create_system = 3
  188. i.external_attr = 0xA1ED0000
  189. archive.writestr(i, readlink(file_path))
  190. elif output_format in self.TARFILE_FORMATS:
  191. import tarfile
  192. mode = self.TARFILE_FORMATS[output_format]
  193. if compresslevel is not None:
  194. try:
  195. archive = tarfile.open(path.abspath(output_path), mode, compresslevel=compresslevel)
  196. except TypeError:
  197. raise ValueError("{0} cannot be compressed".format(output_format))
  198. else:
  199. archive = tarfile.open(path.abspath(output_path), mode)
  200. def add_file(file_path, arcname):
  201. archive.add(file_path, arcname)
  202. else:
  203. raise ValueError("unknown format: {0}".format(output_format))
  204. def archiver(file_path, arcname):
  205. self.LOG.debug(fspath("{0} => {1}").format(file_path, arcname))
  206. add_file(file_path, arcname)
  207. else:
  208. archive = None
  209. def archiver(file_path, arcname):
  210. self.LOG.info(fspath("{0} => {1}").format(file_path, arcname))
  211. self.archive_all_files(archiver)
  212. if archive is not None:
  213. archive.close()
  214. def is_file_excluded(self, repo_abspath, repo_file_path):
  215. """
  216. Checks whether file at a given path is excluded.
  217. @param repo_abspath: Absolute path to the git repository.
  218. @param repo_file_path: Path to a file relative to repo_abspath.
  219. @return: True if file should be excluded. Otherwise False.
  220. """
  221. if not self.exclude:
  222. return False
  223. cache = self._ignored_paths_cache.setdefault(repo_abspath, {})
  224. if repo_file_path not in cache:
  225. next(self._check_attr_gens[repo_abspath])
  226. attrs = self._check_attr_gens[repo_abspath].send(repo_file_path)
  227. export_ignore_attr = attrs['export-ignore']
  228. if export_ignore_attr == b'set':
  229. cache[repo_file_path] = True
  230. elif export_ignore_attr == b'unset':
  231. cache[repo_file_path] = False
  232. else:
  233. repo_file_dir_path = path.dirname(repo_file_path)
  234. if repo_file_dir_path:
  235. cache[repo_file_path] = self.is_file_excluded(repo_abspath, repo_file_dir_path)
  236. else:
  237. cache[repo_file_path] = False
  238. return cache[repo_file_path]
  239. def archive_all_files(self, archiver):
  240. """
  241. Archive all files using archiver.
  242. @param archiver: Callable that accepts 2 arguments:
  243. abspath to file on the system and relative path within archive.
  244. """
  245. for file_path in self.extra:
  246. archiver(path.abspath(file_path), path.join(self.prefix, file_path))
  247. for file_path in self.walk_git_files():
  248. archiver(path.join(self.main_repo_abspath, file_path), path.join(self.prefix, file_path))
  249. def walk_git_files(self, repo_path=fspath('')):
  250. """
  251. An iterator method that yields a file path relative to main_repo_abspath
  252. for each file that should be included in the archive.
  253. Skips those that match the exclusion patterns found in
  254. any discovered .gitattributes files along the way.
  255. Recurs into submodules as well.
  256. @param repo_path: Path to the git submodule repository relative to main_repo_abspath.
  257. @return: Generator to traverse files under git control relative to main_repo_abspath.
  258. """
  259. repo_abspath = path.join(self.main_repo_abspath, fspath(repo_path))
  260. assert repo_abspath not in self._check_attr_gens
  261. self._check_attr_gens[repo_abspath] = self.check_git_attr(repo_abspath, ['export-ignore'])
  262. try:
  263. repo_file_paths = self.list_repo_files(repo_abspath)
  264. for repo_file_path in repo_file_paths:
  265. repo_file_abspath = path.join(repo_abspath, repo_file_path) # absolute file path
  266. main_repo_file_path = path.join(repo_path, repo_file_path) # relative to main_repo_abspath
  267. if not path.islink(repo_file_abspath) and path.isdir(repo_file_abspath):
  268. continue
  269. if self.is_file_excluded(repo_abspath, repo_file_path):
  270. continue
  271. yield main_repo_file_path
  272. if self.force_sub:
  273. self.run_git_shell('git submodule init', repo_abspath)
  274. self.run_git_shell('git submodule update', repo_abspath)
  275. for repo_submodule_path in self.list_repo_submodules(repo_abspath): # relative to repo_path
  276. if self.is_file_excluded(repo_abspath, repo_submodule_path):
  277. continue
  278. main_repo_submodule_path = path.join(repo_path, repo_submodule_path) # relative to main_repo_abspath
  279. for main_repo_submodule_file_path in self.walk_git_files(main_repo_submodule_path):
  280. repo_submodule_file_path = path.relpath(main_repo_submodule_file_path, repo_path) # relative to repo_path
  281. if self.is_file_excluded(repo_abspath, repo_submodule_file_path):
  282. continue
  283. yield main_repo_submodule_file_path
  284. finally:
  285. self._check_attr_gens[repo_abspath].close()
  286. del self._check_attr_gens[repo_abspath]
  287. def check_git_attr(self, repo_abspath, attrs):
  288. """
  289. Generator that returns git attributes for received paths relative to repo_abspath.
  290. >>> archiver = GitArchiver(...)
  291. >>> g = archiver.check_git_attr('repo_path', ['export-ignore'])
  292. >>> next(g)
  293. >>> attrs = g.send('relative_path')
  294. >>> print(attrs['export-ignore'])
  295. @param repo_abspath: Absolute path to a git repository.
  296. @param attrs: Attributes to check
  297. """
  298. def make_process():
  299. env = dict(environ, GIT_FLUSH='1')
  300. cmd = 'git check-attr --stdin -z {0}'.format(' '.join(attrs))
  301. return Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, cwd=repo_abspath, env=env)
  302. def read_attrs(process, repo_file_path):
  303. process.stdin.write(repo_file_path + b'\0')
  304. process.stdin.flush()
  305. # For every attribute check-attr will output: <path> NUL <attribute> NUL <info> NUL
  306. path, attr, info = b'', b'', b''
  307. nuls_count = 0
  308. nuls_expected = 3 * len(attrs)
  309. while nuls_count != nuls_expected:
  310. b = process.stdout.read(1)
  311. if b == b'' and process.poll() is not None:
  312. raise RuntimeError("check-attr exited prematurely")
  313. elif b == b'\0':
  314. nuls_count += 1
  315. if nuls_count % 3 == 0:
  316. yield path, attr, info
  317. path, attr, info = b'', b'', b''
  318. elif nuls_count % 3 == 0:
  319. path += b
  320. elif nuls_count % 3 == 1:
  321. attr += b
  322. elif nuls_count % 3 == 2:
  323. info += b
  324. def read_attrs_old(process, repo_file_path):
  325. """
  326. Compatibility with versions 1.8.5 and below that do not recognize -z for output.
  327. """
  328. process.stdin.write(repo_file_path + b'\0')
  329. process.stdin.flush()
  330. # For every attribute check-attr will output: <path>: <attribute>: <info>\n
  331. # where <path> is c-quoted
  332. path, attr, info = b'', b'', b''
  333. lines_count = 0
  334. lines_expected = len(attrs)
  335. while lines_count != lines_expected:
  336. line = process.stdout.readline()
  337. info_start = line.rfind(b': ')
  338. if info_start == -1:
  339. raise RuntimeError("unexpected output of check-attr: {0}".format(line))
  340. attr_start = line.rfind(b': ', 0, info_start)
  341. if attr_start == -1:
  342. raise RuntimeError("unexpected output of check-attr: {0}".format(line))
  343. path = line[:attr_start]
  344. attr = line[attr_start + 2:info_start] # trim leading ": "
  345. info = line[info_start + 2:len(line) - 1] # trim leading ": " and trailing \n
  346. yield path, attr, info
  347. lines_count += 1
  348. if not attrs:
  349. return
  350. process = make_process()
  351. if self.git_version is None or self.git_version > (1, 8, 5):
  352. reader = read_attrs
  353. else:
  354. reader = read_attrs_old
  355. try:
  356. while True:
  357. repo_file_path = yield
  358. repo_file_path = git_fsencode(fspath(repo_file_path))
  359. repo_file_attrs = {}
  360. for path, attr, value in reader(process, repo_file_path):
  361. attr = attr.decode('utf-8')
  362. repo_file_attrs[attr] = value
  363. yield repo_file_attrs
  364. finally:
  365. process.stdin.close()
  366. process.wait()
  367. def resolve_git_main_repo_abspath(self, abspath):
  368. """
  369. Return absolute path to the repo for a given path.
  370. """
  371. try:
  372. main_repo_abspath = self.run_git_shell('git rev-parse --show-toplevel', cwd=abspath).rstrip()
  373. return path.abspath(git_fspath(main_repo_abspath))
  374. except CalledProcessError as e:
  375. raise ValueError("{0} is not part of a git repository ({1})".format(abspath, e.returncode))
  376. @classmethod
  377. def run_git_shell(cls, cmd, cwd=None):
  378. """
  379. Run git shell command, read output and decode it into a unicode string.
  380. @param cmd: Command to be executed.
  381. @param cwd: Working directory.
  382. @return: Output of the command.
  383. @raise CalledProcessError: Raises exception if return code of the command is non-zero.
  384. """
  385. p = Popen(cmd, shell=True, stdout=PIPE, cwd=cwd)
  386. output, _ = p.communicate()
  387. if p.returncode:
  388. if sys.version_info > (2, 6):
  389. raise CalledProcessError(returncode=p.returncode, cmd=cmd, output=output)
  390. else:
  391. raise CalledProcessError(returncode=p.returncode, cmd=cmd)
  392. return output
  393. @classmethod
  394. def get_git_version(cls):
  395. """
  396. Return version of git current shell points to.
  397. If version cannot be parsed None is returned.
  398. """
  399. try:
  400. output = cls.run_git_shell('git version')
  401. except CalledProcessError:
  402. cls.LOG.warning("Unable to get Git version.")
  403. return None
  404. try:
  405. version = output.split()[2]
  406. except IndexError:
  407. cls.LOG.warning("Unable to parse Git version \"%s\".", output)
  408. return None
  409. try:
  410. return tuple(int(v) if v.isdigit() else 0 for v in version.split(b'.'))
  411. except ValueError:
  412. cls.LOG.warning("Unable to parse Git version \"%s\".", version)
  413. return None
  414. @classmethod
  415. def list_repo_files(cls, repo_abspath):
  416. """
  417. Return a list of all files as seen by git in a given repo.
  418. """
  419. repo_file_paths = cls.run_git_shell(
  420. 'git ls-files -z --cached --full-name --no-empty-directory',
  421. cwd=repo_abspath
  422. )
  423. repo_file_paths = repo_file_paths.split(b'\0')[:-1]
  424. if sys.platform.startswith('win32'):
  425. repo_file_paths = (git_fspath(p.replace(b'/', b'\\')) for p in repo_file_paths)
  426. else:
  427. repo_file_paths = map(git_fspath, repo_file_paths)
  428. return repo_file_paths
  429. @classmethod
  430. def list_repo_submodules(cls, repo_abspath):
  431. """
  432. Return a list of all direct submodules as seen by git in a given repo.
  433. """
  434. if sys.platform.startswith('win32'):
  435. shell_command = 'git submodule foreach --quiet "\\"{0}\\" -c \\"from __future__ import print_function; print(\'"$sm_path"\', end=chr(0))\\""'
  436. else:
  437. shell_command = 'git submodule foreach --quiet \'"{0}" -c "from __future__ import print_function; print(\\"$sm_path\\", end=chr(0))"\''
  438. python_exe = sys.executable or 'python'
  439. shell_command = shell_command.format(python_exe)
  440. repo_submodule_paths = cls.run_git_shell(shell_command, cwd=repo_abspath)
  441. repo_submodule_paths = repo_submodule_paths.split(b'\0')[:-1]
  442. if sys.platform.startswith('win32'):
  443. repo_submodule_paths = (git_fspath(p.replace(b'/', b'\\')) for p in repo_submodule_paths)
  444. else:
  445. repo_submodule_paths = map(git_fspath, repo_submodule_paths)
  446. return repo_submodule_paths
  447. def main(argv=None):
  448. if argv is None:
  449. argv = sys.argv
  450. from optparse import OptionParser, SUPPRESS_HELP
  451. parser = OptionParser(
  452. usage="usage: %prog [-v] [-C BASE_REPO] [--prefix PREFIX] [--no-export-ignore]"
  453. " [--force-submodules] [--include EXTRA1 ...] [--dry-run] [-0 | ... | -9] OUTPUT_FILE",
  454. version="%prog {0}".format(__version__)
  455. )
  456. parser.add_option('--prefix',
  457. type='string',
  458. dest='prefix',
  459. default=None,
  460. help="""prepend PREFIX to each filename in the archive;
  461. defaults to OUTPUT_FILE name""")
  462. parser.add_option('-C',
  463. type='string',
  464. dest='base_repo',
  465. default=None,
  466. help="""use BASE_REPO as the main git repository to archive;
  467. defaults to the current directory when empty""")
  468. parser.add_option('-v', '--verbose',
  469. action='store_true',
  470. dest='verbose',
  471. help='enable verbose mode')
  472. parser.add_option('--no-export-ignore', '--no-exclude',
  473. action='store_false',
  474. dest='exclude',
  475. default=True,
  476. help="ignore the [-]export-ignore attribute in .gitattributes")
  477. parser.add_option('--force-submodules',
  478. action='store_true',
  479. dest='force_sub',
  480. help='force `git submodule init && git submodule update` at each level before iterating submodules')
  481. parser.add_option('--include', '--extra',
  482. action='append',
  483. dest='extra',
  484. default=[],
  485. help="additional files to include in the archive")
  486. parser.add_option('--dry-run',
  487. action='store_true',
  488. dest='dry_run',
  489. help="show files to be archived without actually creating the archive")
  490. for i in range(10):
  491. parser.add_option('-{0}'.format(i),
  492. action='store_const',
  493. const=i,
  494. dest='compresslevel',
  495. help=SUPPRESS_HELP)
  496. options, args = parser.parse_args(argv[1:])
  497. if len(args) != 1:
  498. parser.error("You must specify exactly one output file")
  499. output_file_path = args[0]
  500. if path.isdir(output_file_path):
  501. parser.error("You cannot use directory as output")
  502. # avoid tarbomb
  503. if options.prefix is not None:
  504. options.prefix = path.join(options.prefix, '')
  505. else:
  506. output_name = path.basename(output_file_path)
  507. output_name = re.sub(
  508. '(\\.zip|\\.tar|\\.tbz2|\\.tgz|\\.txz|\\.bz2|\\.gz|\\.xz|\\.tar\\.bz2|\\.tar\\.gz|\\.tar\\.xz)$',
  509. '',
  510. output_name
  511. ) or "Archive"
  512. options.prefix = path.join(output_name, '')
  513. try:
  514. handler = logging.StreamHandler(sys.stdout)
  515. handler.setFormatter(logging.Formatter('%(message)s'))
  516. GitArchiver.LOG.addHandler(handler)
  517. GitArchiver.LOG.setLevel(logging.DEBUG if options.verbose else logging.INFO)
  518. archiver = GitArchiver(options.prefix,
  519. options.exclude,
  520. options.force_sub,
  521. options.extra,
  522. path.abspath(options.base_repo) if options.base_repo is not None else None
  523. )
  524. archiver.create(output_file_path, options.dry_run, compresslevel=options.compresslevel)
  525. except Exception as e:
  526. parser.exit(2, "{0}\n".format(e))
  527. return 0
  528. if __name__ == '__main__':
  529. sys.exit(main())