porcelain.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  1. # porcelain.py -- Porcelain-like layer on top of Dulwich
  2. # Copyright (C) 2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  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. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Simple wrapper that provides porcelain-like functions on top of Dulwich.
  21. Currently implemented:
  22. * archive
  23. * add
  24. * branch{_create,_delete,_list}
  25. * check-ignore
  26. * checkout
  27. * clone
  28. * commit
  29. * commit-tree
  30. * daemon
  31. * describe
  32. * diff-tree
  33. * fetch
  34. * init
  35. * ls-files
  36. * ls-remote
  37. * ls-tree
  38. * pull
  39. * push
  40. * rm
  41. * remote{_add}
  42. * receive-pack
  43. * reset
  44. * rev-list
  45. * tag{_create,_delete,_list}
  46. * upload-pack
  47. * update-server-info
  48. * status
  49. * symbolic-ref
  50. These functions are meant to behave similarly to the git subcommands.
  51. Differences in behaviour are considered bugs.
  52. Functions should generally accept both unicode strings and bytestrings
  53. """
  54. from collections import namedtuple
  55. from contextlib import (
  56. closing,
  57. contextmanager,
  58. )
  59. from io import BytesIO
  60. import datetime
  61. import os
  62. import posixpath
  63. import stat
  64. import sys
  65. import time
  66. from dulwich.archive import (
  67. tar_stream,
  68. )
  69. from dulwich.client import (
  70. get_transport_and_path,
  71. )
  72. from dulwich.config import (
  73. StackedConfig,
  74. )
  75. from dulwich.diff_tree import (
  76. CHANGE_ADD,
  77. CHANGE_DELETE,
  78. CHANGE_MODIFY,
  79. CHANGE_RENAME,
  80. CHANGE_COPY,
  81. RENAME_CHANGE_TYPES,
  82. )
  83. from dulwich.errors import (
  84. SendPackError,
  85. UpdateRefsError,
  86. )
  87. from dulwich.ignore import IgnoreFilterManager
  88. from dulwich.index import (
  89. blob_from_path_and_stat,
  90. get_unstaged_changes,
  91. )
  92. from dulwich.object_store import (
  93. tree_lookup_path,
  94. )
  95. from dulwich.objects import (
  96. Commit,
  97. Tag,
  98. format_timezone,
  99. parse_timezone,
  100. pretty_format_tree_entry,
  101. )
  102. from dulwich.objectspec import (
  103. parse_commit,
  104. parse_object,
  105. parse_ref,
  106. parse_reftuples,
  107. parse_tree,
  108. )
  109. from dulwich.pack import (
  110. write_pack_index,
  111. write_pack_objects,
  112. )
  113. from dulwich.patch import write_tree_diff
  114. from dulwich.protocol import (
  115. Protocol,
  116. ZERO_SHA,
  117. )
  118. from dulwich.refs import (
  119. ANNOTATED_TAG_SUFFIX,
  120. strip_peeled_refs,
  121. )
  122. from dulwich.repo import (BaseRepo, Repo)
  123. from dulwich.server import (
  124. FileSystemBackend,
  125. TCPGitServer,
  126. ReceivePackHandler,
  127. UploadPackHandler,
  128. update_server_info as server_update_server_info,
  129. )
  130. # Module level tuple definition for status output
  131. GitStatus = namedtuple('GitStatus', 'staged unstaged untracked')
  132. default_bytes_out_stream = getattr(sys.stdout, 'buffer', sys.stdout)
  133. default_bytes_err_stream = getattr(sys.stderr, 'buffer', sys.stderr)
  134. DEFAULT_ENCODING = 'utf-8'
  135. class RemoteExists(Exception):
  136. """Raised when the remote already exists."""
  137. def open_repo(path_or_repo):
  138. """Open an argument that can be a repository or a path for a repository."""
  139. if isinstance(path_or_repo, BaseRepo):
  140. return path_or_repo
  141. return Repo(path_or_repo)
  142. @contextmanager
  143. def _noop_context_manager(obj):
  144. """Context manager that has the same api as closing but does nothing."""
  145. yield obj
  146. def open_repo_closing(path_or_repo):
  147. """Open an argument that can be a repository or a path for a repository.
  148. returns a context manager that will close the repo on exit if the argument
  149. is a path, else does nothing if the argument is a repo.
  150. """
  151. if isinstance(path_or_repo, BaseRepo):
  152. return _noop_context_manager(path_or_repo)
  153. return closing(Repo(path_or_repo))
  154. def path_to_tree_path(repopath, path):
  155. """Convert a path to a path usable in an index, e.g. bytes and relative to
  156. the repository root.
  157. :param repopath: Repository path, absolute or relative to the cwd
  158. :param path: A path, absolute or relative to the cwd
  159. :return: A path formatted for use in e.g. an index
  160. """
  161. if not isinstance(path, bytes):
  162. path = path.encode(sys.getfilesystemencoding())
  163. if not isinstance(repopath, bytes):
  164. repopath = repopath.encode(sys.getfilesystemencoding())
  165. treepath = os.path.relpath(path, repopath)
  166. if treepath.startswith(b'..'):
  167. raise ValueError('Path not in repo')
  168. if os.path.sep != '/':
  169. treepath = treepath.replace(os.path.sep.encode('ascii'), b'/')
  170. return treepath
  171. def archive(repo, committish=None, outstream=default_bytes_out_stream,
  172. errstream=default_bytes_err_stream):
  173. """Create an archive.
  174. :param repo: Path of repository for which to generate an archive.
  175. :param committish: Commit SHA1 or ref to use
  176. :param outstream: Output stream (defaults to stdout)
  177. :param errstream: Error stream (defaults to stderr)
  178. """
  179. if committish is None:
  180. committish = "HEAD"
  181. with open_repo_closing(repo) as repo_obj:
  182. c = repo_obj[committish]
  183. for chunk in tar_stream(
  184. repo_obj.object_store, repo_obj.object_store[c.tree],
  185. c.commit_time):
  186. outstream.write(chunk)
  187. def update_server_info(repo="."):
  188. """Update server info files for a repository.
  189. :param repo: path to the repository
  190. """
  191. with open_repo_closing(repo) as r:
  192. server_update_server_info(r)
  193. def symbolic_ref(repo, ref_name, force=False):
  194. """Set git symbolic ref into HEAD.
  195. :param repo: path to the repository
  196. :param ref_name: short name of the new ref
  197. :param force: force settings without checking if it exists in refs/heads
  198. """
  199. with open_repo_closing(repo) as repo_obj:
  200. ref_path = _make_branch_ref(ref_name)
  201. if not force and ref_path not in repo_obj.refs.keys():
  202. raise ValueError('fatal: ref `%s` is not a ref' % ref_name)
  203. repo_obj.refs.set_symbolic_ref(b'HEAD', ref_path)
  204. def commit(repo=".", message=None, author=None, committer=None, encoding=None):
  205. """Create a new commit.
  206. :param repo: Path to repository
  207. :param message: Optional commit message
  208. :param author: Optional author name and email
  209. :param committer: Optional committer name and email
  210. :return: SHA1 of the new commit
  211. """
  212. # FIXME: Support --all argument
  213. # FIXME: Support --signoff argument
  214. if getattr(message, 'encode', None):
  215. message = message.encode(encoding or DEFAULT_ENCODING)
  216. if getattr(author, 'encode', None):
  217. author = author.encode(encoding or DEFAULT_ENCODING)
  218. if getattr(committer, 'encode', None):
  219. committer = committer.encode(encoding or DEFAULT_ENCODING)
  220. with open_repo_closing(repo) as r:
  221. return r.do_commit(
  222. message=message, author=author, committer=committer,
  223. encoding=encoding)
  224. def commit_tree(repo, tree, message=None, author=None, committer=None):
  225. """Create a new commit object.
  226. :param repo: Path to repository
  227. :param tree: An existing tree object
  228. :param author: Optional author name and email
  229. :param committer: Optional committer name and email
  230. """
  231. with open_repo_closing(repo) as r:
  232. return r.do_commit(
  233. message=message, tree=tree, committer=committer, author=author)
  234. def init(path=".", bare=False):
  235. """Create a new git repository.
  236. :param path: Path to repository.
  237. :param bare: Whether to create a bare repository.
  238. :return: A Repo instance
  239. """
  240. if not os.path.exists(path):
  241. os.mkdir(path)
  242. if bare:
  243. return Repo.init_bare(path)
  244. else:
  245. return Repo.init(path)
  246. def clone(source, target=None, bare=False, checkout=None,
  247. errstream=default_bytes_err_stream, outstream=None,
  248. origin=b"origin", **kwargs):
  249. """Clone a local or remote git repository.
  250. :param source: Path or URL for source repository
  251. :param target: Path to target repository (optional)
  252. :param bare: Whether or not to create a bare repository
  253. :param checkout: Whether or not to check-out HEAD after cloning
  254. :param errstream: Optional stream to write progress to
  255. :param outstream: Optional stream to write progress to (deprecated)
  256. :param origin: Name of remote from the repository used to clone
  257. :return: The new repository
  258. """
  259. # TODO(jelmer): This code overlaps quite a bit with Repo.clone
  260. if outstream is not None:
  261. import warnings
  262. warnings.warn(
  263. "outstream= has been deprecated in favour of errstream=.",
  264. DeprecationWarning, stacklevel=3)
  265. errstream = outstream
  266. if checkout is None:
  267. checkout = (not bare)
  268. if checkout and bare:
  269. raise ValueError("checkout and bare are incompatible")
  270. if target is None:
  271. target = source.split("/")[-1]
  272. if not os.path.exists(target):
  273. os.mkdir(target)
  274. if bare:
  275. r = Repo.init_bare(target)
  276. else:
  277. r = Repo.init(target)
  278. reflog_message = b'clone: from ' + source.encode('utf-8')
  279. try:
  280. fetch_result = fetch(
  281. r, source, origin, errstream=errstream, message=reflog_message,
  282. **kwargs)
  283. target_config = r.get_config()
  284. if not isinstance(source, bytes):
  285. source = source.encode(DEFAULT_ENCODING)
  286. target_config.set((b'remote', origin), b'url', source)
  287. target_config.set(
  288. (b'remote', origin), b'fetch',
  289. b'+refs/heads/*:refs/remotes/' + origin + b'/*')
  290. target_config.write_to_path()
  291. # TODO(jelmer): Support symref capability,
  292. # https://github.com/jelmer/dulwich/issues/485
  293. try:
  294. head = r[fetch_result[b'HEAD']]
  295. except KeyError:
  296. head = None
  297. else:
  298. r[b'HEAD'] = head.id
  299. if checkout and not bare and head is not None:
  300. errstream.write(b'Checking out ' + head.id + b'\n')
  301. r.reset_index(head.tree)
  302. except BaseException:
  303. r.close()
  304. raise
  305. return r
  306. def add(repo=".", paths=None):
  307. """Add files to the staging area.
  308. :param repo: Repository for the files
  309. :param paths: Paths to add. No value passed stages all modified files.
  310. :return: Tuple with set of added files and ignored files
  311. """
  312. ignored = set()
  313. with open_repo_closing(repo) as r:
  314. ignore_manager = IgnoreFilterManager.from_repo(r)
  315. if not paths:
  316. paths = list(
  317. get_untracked_paths(os.getcwd(), r.path, r.open_index()))
  318. relpaths = []
  319. if not isinstance(paths, list):
  320. paths = [paths]
  321. for p in paths:
  322. relpath = os.path.relpath(p, r.path)
  323. if relpath.startswith('..' + os.path.sep):
  324. raise ValueError('path %r is not in repo' % relpath)
  325. # FIXME: Support patterns, directories.
  326. if ignore_manager.is_ignored(relpath):
  327. ignored.add(relpath)
  328. continue
  329. relpaths.append(relpath)
  330. r.stage(relpaths)
  331. return (relpaths, ignored)
  332. def remove(repo=".", paths=None, cached=False):
  333. """Remove files from the staging area.
  334. :param repo: Repository for the files
  335. :param paths: Paths to remove
  336. """
  337. with open_repo_closing(repo) as r:
  338. index = r.open_index()
  339. for p in paths:
  340. full_path = os.path.abspath(p).encode(sys.getfilesystemencoding())
  341. tree_path = path_to_tree_path(r.path, p)
  342. try:
  343. index_sha = index[tree_path].sha
  344. except KeyError:
  345. raise Exception('%s did not match any files' % p)
  346. if not cached:
  347. try:
  348. st = os.lstat(full_path)
  349. except OSError:
  350. pass
  351. else:
  352. try:
  353. blob = blob_from_path_and_stat(full_path, st)
  354. except IOError:
  355. pass
  356. else:
  357. try:
  358. committed_sha = tree_lookup_path(
  359. r.__getitem__, r[r.head()].tree, tree_path)[1]
  360. except KeyError:
  361. committed_sha = None
  362. if blob.id != index_sha and index_sha != committed_sha:
  363. raise Exception(
  364. 'file has staged content differing '
  365. 'from both the file and head: %s' % p)
  366. if index_sha != committed_sha:
  367. raise Exception(
  368. 'file has staged changes: %s' % p)
  369. os.remove(full_path)
  370. del index[tree_path]
  371. index.write()
  372. rm = remove
  373. def commit_decode(commit, contents, default_encoding=DEFAULT_ENCODING):
  374. if commit.encoding is not None:
  375. return contents.decode(commit.encoding, "replace")
  376. return contents.decode(default_encoding, "replace")
  377. def print_commit(commit, decode, outstream=sys.stdout):
  378. """Write a human-readable commit log entry.
  379. :param commit: A `Commit` object
  380. :param outstream: A stream file to write to
  381. """
  382. outstream.write("-" * 50 + "\n")
  383. outstream.write("commit: " + commit.id.decode('ascii') + "\n")
  384. if len(commit.parents) > 1:
  385. outstream.write(
  386. "merge: " +
  387. "...".join([c.decode('ascii') for c in commit.parents[1:]]) + "\n")
  388. outstream.write("Author: " + decode(commit.author) + "\n")
  389. if commit.author != commit.committer:
  390. outstream.write("Committer: " + decode(commit.committer) + "\n")
  391. time_tuple = time.gmtime(commit.author_time + commit.author_timezone)
  392. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  393. timezone_str = format_timezone(commit.author_timezone).decode('ascii')
  394. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  395. outstream.write("\n")
  396. outstream.write(decode(commit.message) + "\n")
  397. outstream.write("\n")
  398. def print_tag(tag, decode, outstream=sys.stdout):
  399. """Write a human-readable tag.
  400. :param tag: A `Tag` object
  401. :param decode: Function for decoding bytes to unicode string
  402. :param outstream: A stream to write to
  403. """
  404. outstream.write("Tagger: " + decode(tag.tagger) + "\n")
  405. outstream.write("Date: " + decode(tag.tag_time) + "\n")
  406. outstream.write("\n")
  407. outstream.write(decode(tag.message) + "\n")
  408. outstream.write("\n")
  409. def show_blob(repo, blob, decode, outstream=sys.stdout):
  410. """Write a blob to a stream.
  411. :param repo: A `Repo` object
  412. :param blob: A `Blob` object
  413. :param decode: Function for decoding bytes to unicode string
  414. :param outstream: A stream file to write to
  415. """
  416. outstream.write(decode(blob.data))
  417. def show_commit(repo, commit, decode, outstream=sys.stdout):
  418. """Show a commit to a stream.
  419. :param repo: A `Repo` object
  420. :param commit: A `Commit` object
  421. :param decode: Function for decoding bytes to unicode string
  422. :param outstream: Stream to write to
  423. """
  424. print_commit(commit, decode=decode, outstream=outstream)
  425. if commit.parents:
  426. parent_commit = repo[commit.parents[0]]
  427. base_tree = parent_commit.tree
  428. else:
  429. base_tree = None
  430. diffstream = BytesIO()
  431. write_tree_diff(
  432. diffstream,
  433. repo.object_store, base_tree, commit.tree)
  434. diffstream.seek(0)
  435. outstream.write(
  436. diffstream.getvalue().decode(
  437. commit.encoding or DEFAULT_ENCODING, 'replace'))
  438. def show_tree(repo, tree, decode, outstream=sys.stdout):
  439. """Print a tree to a stream.
  440. :param repo: A `Repo` object
  441. :param tree: A `Tree` object
  442. :param decode: Function for decoding bytes to unicode string
  443. :param outstream: Stream to write to
  444. """
  445. for n in tree:
  446. outstream.write(decode(n) + "\n")
  447. def show_tag(repo, tag, decode, outstream=sys.stdout):
  448. """Print a tag to a stream.
  449. :param repo: A `Repo` object
  450. :param tag: A `Tag` object
  451. :param decode: Function for decoding bytes to unicode string
  452. :param outstream: Stream to write to
  453. """
  454. print_tag(tag, decode, outstream)
  455. show_object(repo, repo[tag.object[1]], outstream)
  456. def show_object(repo, obj, decode, outstream):
  457. return {
  458. b"tree": show_tree,
  459. b"blob": show_blob,
  460. b"commit": show_commit,
  461. b"tag": show_tag,
  462. }[obj.type_name](repo, obj, decode, outstream)
  463. def print_name_status(changes):
  464. """Print a simple status summary, listing changed files.
  465. """
  466. for change in changes:
  467. if not change:
  468. continue
  469. if isinstance(change, list):
  470. change = change[0]
  471. if change.type == CHANGE_ADD:
  472. path1 = change.new.path
  473. path2 = ''
  474. kind = 'A'
  475. elif change.type == CHANGE_DELETE:
  476. path1 = change.old.path
  477. path2 = ''
  478. kind = 'D'
  479. elif change.type == CHANGE_MODIFY:
  480. path1 = change.new.path
  481. path2 = ''
  482. kind = 'M'
  483. elif change.type in RENAME_CHANGE_TYPES:
  484. path1 = change.old.path
  485. path2 = change.new.path
  486. if change.type == CHANGE_RENAME:
  487. kind = 'R'
  488. elif change.type == CHANGE_COPY:
  489. kind = 'C'
  490. yield '%-8s%-20s%-20s' % (kind, path1, path2)
  491. def log(repo=".", paths=None, outstream=sys.stdout, max_entries=None,
  492. reverse=False, name_status=False):
  493. """Write commit logs.
  494. :param repo: Path to repository
  495. :param paths: Optional set of specific paths to print entries for
  496. :param outstream: Stream to write log output to
  497. :param reverse: Reverse order in which entries are printed
  498. :param name_status: Print name status
  499. :param max_entries: Optional maximum number of entries to display
  500. """
  501. with open_repo_closing(repo) as r:
  502. walker = r.get_walker(
  503. max_entries=max_entries, paths=paths, reverse=reverse)
  504. for entry in walker:
  505. def decode(x):
  506. return commit_decode(entry.commit, x)
  507. print_commit(entry.commit, decode, outstream)
  508. if name_status:
  509. outstream.writelines(
  510. [l+'\n' for l in print_name_status(entry.changes())])
  511. # TODO(jelmer): better default for encoding?
  512. def show(repo=".", objects=None, outstream=sys.stdout,
  513. default_encoding=DEFAULT_ENCODING):
  514. """Print the changes in a commit.
  515. :param repo: Path to repository
  516. :param objects: Objects to show (defaults to [HEAD])
  517. :param outstream: Stream to write to
  518. :param default_encoding: Default encoding to use if none is set in the
  519. commit
  520. """
  521. if objects is None:
  522. objects = ["HEAD"]
  523. if not isinstance(objects, list):
  524. objects = [objects]
  525. with open_repo_closing(repo) as r:
  526. for objectish in objects:
  527. o = parse_object(r, objectish)
  528. if isinstance(o, Commit):
  529. def decode(x):
  530. return commit_decode(o, x, default_encoding)
  531. else:
  532. def decode(x):
  533. return x.decode(default_encoding)
  534. show_object(r, o, decode, outstream)
  535. def diff_tree(repo, old_tree, new_tree, outstream=sys.stdout):
  536. """Compares the content and mode of blobs found via two tree objects.
  537. :param repo: Path to repository
  538. :param old_tree: Id of old tree
  539. :param new_tree: Id of new tree
  540. :param outstream: Stream to write to
  541. """
  542. with open_repo_closing(repo) as r:
  543. write_tree_diff(outstream, r.object_store, old_tree, new_tree)
  544. def rev_list(repo, commits, outstream=sys.stdout):
  545. """Lists commit objects in reverse chronological order.
  546. :param repo: Path to repository
  547. :param commits: Commits over which to iterate
  548. :param outstream: Stream to write to
  549. """
  550. with open_repo_closing(repo) as r:
  551. for entry in r.get_walker(include=[r[c].id for c in commits]):
  552. outstream.write(entry.commit.id + b"\n")
  553. def tag(*args, **kwargs):
  554. import warnings
  555. warnings.warn("tag has been deprecated in favour of tag_create.",
  556. DeprecationWarning)
  557. return tag_create(*args, **kwargs)
  558. def tag_create(
  559. repo, tag, author=None, message=None, annotated=False,
  560. objectish="HEAD", tag_time=None, tag_timezone=None):
  561. """Creates a tag in git via dulwich calls:
  562. :param repo: Path to repository
  563. :param tag: tag string
  564. :param author: tag author (optional, if annotated is set)
  565. :param message: tag message (optional)
  566. :param annotated: whether to create an annotated tag
  567. :param objectish: object the tag should point at, defaults to HEAD
  568. :param tag_time: Optional time for annotated tag
  569. :param tag_timezone: Optional timezone for annotated tag
  570. """
  571. with open_repo_closing(repo) as r:
  572. object = parse_object(r, objectish)
  573. if annotated:
  574. # Create the tag object
  575. tag_obj = Tag()
  576. if author is None:
  577. # TODO(jelmer): Don't use repo private method.
  578. author = r._get_user_identity()
  579. tag_obj.tagger = author
  580. tag_obj.message = message
  581. tag_obj.name = tag
  582. tag_obj.object = (type(object), object.id)
  583. if tag_time is None:
  584. tag_time = int(time.time())
  585. tag_obj.tag_time = tag_time
  586. if tag_timezone is None:
  587. # TODO(jelmer) Use current user timezone rather than UTC
  588. tag_timezone = 0
  589. elif isinstance(tag_timezone, str):
  590. tag_timezone = parse_timezone(tag_timezone)
  591. tag_obj.tag_timezone = tag_timezone
  592. r.object_store.add_object(tag_obj)
  593. tag_id = tag_obj.id
  594. else:
  595. tag_id = object.id
  596. r.refs[_make_tag_ref(tag)] = tag_id
  597. def list_tags(*args, **kwargs):
  598. import warnings
  599. warnings.warn("list_tags has been deprecated in favour of tag_list.",
  600. DeprecationWarning)
  601. return tag_list(*args, **kwargs)
  602. def tag_list(repo, outstream=sys.stdout):
  603. """List all tags.
  604. :param repo: Path to repository
  605. :param outstream: Stream to write tags to
  606. """
  607. with open_repo_closing(repo) as r:
  608. tags = sorted(r.refs.as_dict(b"refs/tags"))
  609. return tags
  610. def tag_delete(repo, name):
  611. """Remove a tag.
  612. :param repo: Path to repository
  613. :param name: Name of tag to remove
  614. """
  615. with open_repo_closing(repo) as r:
  616. if isinstance(name, bytes):
  617. names = [name]
  618. elif isinstance(name, list):
  619. names = name
  620. else:
  621. raise TypeError("Unexpected tag name type %r" % name)
  622. for name in names:
  623. del r.refs[_make_tag_ref(name)]
  624. def reset(repo, mode, treeish="HEAD"):
  625. """Reset current HEAD to the specified state.
  626. :param repo: Path to repository
  627. :param mode: Mode ("hard", "soft", "mixed")
  628. :param treeish: Treeish to reset to
  629. """
  630. if mode != "hard":
  631. raise ValueError("hard is the only mode currently supported")
  632. with open_repo_closing(repo) as r:
  633. tree = parse_tree(r, treeish)
  634. r.reset_index(tree.id)
  635. def push(repo, remote_location, refspecs,
  636. outstream=default_bytes_out_stream,
  637. errstream=default_bytes_err_stream, **kwargs):
  638. """Remote push with dulwich via dulwich.client
  639. :param repo: Path to repository
  640. :param remote_location: Location of the remote
  641. :param refspecs: Refs to push to remote
  642. :param outstream: A stream file to write output
  643. :param errstream: A stream file to write errors
  644. """
  645. # Open the repo
  646. with open_repo_closing(repo) as r:
  647. # Get the client and path
  648. client, path = get_transport_and_path(
  649. remote_location, config=r.get_config_stack(), **kwargs)
  650. selected_refs = []
  651. def update_refs(refs):
  652. selected_refs.extend(parse_reftuples(r.refs, refs, refspecs))
  653. new_refs = {}
  654. # TODO: Handle selected_refs == {None: None}
  655. for (lh, rh, force) in selected_refs:
  656. if lh is None:
  657. new_refs[rh] = ZERO_SHA
  658. else:
  659. new_refs[rh] = r.refs[lh]
  660. return new_refs
  661. err_encoding = getattr(errstream, 'encoding', None) or DEFAULT_ENCODING
  662. remote_location_bytes = client.get_url(path).encode(err_encoding)
  663. try:
  664. client.send_pack(
  665. path, update_refs,
  666. generate_pack_data=r.object_store.generate_pack_data,
  667. progress=errstream.write)
  668. errstream.write(
  669. b"Push to " + remote_location_bytes + b" successful.\n")
  670. except (UpdateRefsError, SendPackError) as e:
  671. errstream.write(b"Push to " + remote_location_bytes +
  672. b" failed -> " + e.message.encode(err_encoding) +
  673. b"\n")
  674. def pull(repo, remote_location=None, refspecs=None,
  675. outstream=default_bytes_out_stream,
  676. errstream=default_bytes_err_stream, **kwargs):
  677. """Pull from remote via dulwich.client
  678. :param repo: Path to repository
  679. :param remote_location: Location of the remote
  680. :param refspec: refspecs to fetch
  681. :param outstream: A stream file to write to output
  682. :param errstream: A stream file to write to errors
  683. """
  684. # Open the repo
  685. with open_repo_closing(repo) as r:
  686. if remote_location is None:
  687. # TODO(jelmer): Lookup 'remote' for current branch in config
  688. raise NotImplementedError(
  689. "looking up remote from branch config not supported yet")
  690. if refspecs is None:
  691. refspecs = [b"HEAD"]
  692. selected_refs = []
  693. def determine_wants(remote_refs):
  694. selected_refs.extend(
  695. parse_reftuples(remote_refs, r.refs, refspecs))
  696. return [remote_refs[lh] for (lh, rh, force) in selected_refs]
  697. client, path = get_transport_and_path(
  698. remote_location, config=r.get_config_stack(), **kwargs)
  699. fetch_result = client.fetch(
  700. path, r, progress=errstream.write, determine_wants=determine_wants)
  701. for (lh, rh, force) in selected_refs:
  702. r.refs[rh] = fetch_result.refs[lh]
  703. if selected_refs:
  704. r[b'HEAD'] = fetch_result.refs[selected_refs[0][1]]
  705. # Perform 'git checkout .' - syncs staged changes
  706. tree = r[b"HEAD"].tree
  707. r.reset_index(tree=tree)
  708. def status(repo=".", ignored=False):
  709. """Returns staged, unstaged, and untracked changes relative to the HEAD.
  710. :param repo: Path to repository or repository object
  711. :param ignored: Whether to include ignored files in `untracked`
  712. :return: GitStatus tuple,
  713. staged - list of staged paths (diff index/HEAD)
  714. unstaged - list of unstaged paths (diff index/working-tree)
  715. untracked - list of untracked, un-ignored & non-.git paths
  716. """
  717. with open_repo_closing(repo) as r:
  718. # 1. Get status of staged
  719. tracked_changes = get_tree_changes(r)
  720. # 2. Get status of unstaged
  721. index = r.open_index()
  722. unstaged_changes = list(get_unstaged_changes(index, r.path))
  723. ignore_manager = IgnoreFilterManager.from_repo(r)
  724. untracked_paths = get_untracked_paths(r.path, r.path, index)
  725. if ignored:
  726. untracked_changes = list(untracked_paths)
  727. else:
  728. untracked_changes = [
  729. p for p in untracked_paths
  730. if not ignore_manager.is_ignored(p)]
  731. return GitStatus(tracked_changes, unstaged_changes, untracked_changes)
  732. def get_untracked_paths(frompath, basepath, index):
  733. """Get untracked paths.
  734. ;param frompath: Path to walk
  735. :param basepath: Path to compare to
  736. :param index: Index to check against
  737. """
  738. # If nothing is specified, add all non-ignored files.
  739. for dirpath, dirnames, filenames in os.walk(frompath):
  740. # Skip .git and below.
  741. if '.git' in dirnames:
  742. dirnames.remove('.git')
  743. if dirpath != basepath:
  744. continue
  745. if '.git' in filenames:
  746. filenames.remove('.git')
  747. if dirpath != basepath:
  748. continue
  749. for filename in filenames:
  750. ap = os.path.join(dirpath, filename)
  751. ip = path_to_tree_path(basepath, ap)
  752. if ip not in index:
  753. yield os.path.relpath(ap, frompath)
  754. def get_tree_changes(repo):
  755. """Return add/delete/modify changes to tree by comparing index to HEAD.
  756. :param repo: repo path or object
  757. :return: dict with lists for each type of change
  758. """
  759. with open_repo_closing(repo) as r:
  760. index = r.open_index()
  761. # Compares the Index to the HEAD & determines changes
  762. # Iterate through the changes and report add/delete/modify
  763. # TODO: call out to dulwich.diff_tree somehow.
  764. tracked_changes = {
  765. 'add': [],
  766. 'delete': [],
  767. 'modify': [],
  768. }
  769. try:
  770. tree_id = r[b'HEAD'].tree
  771. except KeyError:
  772. tree_id = None
  773. for change in index.changes_from_tree(r.object_store, tree_id):
  774. if not change[0][0]:
  775. tracked_changes['add'].append(change[0][1])
  776. elif not change[0][1]:
  777. tracked_changes['delete'].append(change[0][0])
  778. elif change[0][0] == change[0][1]:
  779. tracked_changes['modify'].append(change[0][0])
  780. else:
  781. raise AssertionError('git mv ops not yet supported')
  782. return tracked_changes
  783. def daemon(path=".", address=None, port=None):
  784. """Run a daemon serving Git requests over TCP/IP.
  785. :param path: Path to the directory to serve.
  786. :param address: Optional address to listen on (defaults to ::)
  787. :param port: Optional port to listen on (defaults to TCP_GIT_PORT)
  788. """
  789. # TODO(jelmer): Support git-daemon-export-ok and --export-all.
  790. backend = FileSystemBackend(path)
  791. server = TCPGitServer(backend, address, port)
  792. server.serve_forever()
  793. def web_daemon(path=".", address=None, port=None):
  794. """Run a daemon serving Git requests over HTTP.
  795. :param path: Path to the directory to serve
  796. :param address: Optional address to listen on (defaults to ::)
  797. :param port: Optional port to listen on (defaults to 80)
  798. """
  799. from dulwich.web import (
  800. make_wsgi_chain,
  801. make_server,
  802. WSGIRequestHandlerLogger,
  803. WSGIServerLogger)
  804. backend = FileSystemBackend(path)
  805. app = make_wsgi_chain(backend)
  806. server = make_server(address, port, app,
  807. handler_class=WSGIRequestHandlerLogger,
  808. server_class=WSGIServerLogger)
  809. server.serve_forever()
  810. def upload_pack(path=".", inf=None, outf=None):
  811. """Upload a pack file after negotiating its contents using smart protocol.
  812. :param path: Path to the repository
  813. :param inf: Input stream to communicate with client
  814. :param outf: Output stream to communicate with client
  815. """
  816. if outf is None:
  817. outf = getattr(sys.stdout, 'buffer', sys.stdout)
  818. if inf is None:
  819. inf = getattr(sys.stdin, 'buffer', sys.stdin)
  820. path = os.path.expanduser(path)
  821. backend = FileSystemBackend(path)
  822. def send_fn(data):
  823. outf.write(data)
  824. outf.flush()
  825. proto = Protocol(inf.read, send_fn)
  826. handler = UploadPackHandler(backend, [path], proto)
  827. # FIXME: Catch exceptions and write a single-line summary to outf.
  828. handler.handle()
  829. return 0
  830. def receive_pack(path=".", inf=None, outf=None):
  831. """Receive a pack file after negotiating its contents using smart protocol.
  832. :param path: Path to the repository
  833. :param inf: Input stream to communicate with client
  834. :param outf: Output stream to communicate with client
  835. """
  836. if outf is None:
  837. outf = getattr(sys.stdout, 'buffer', sys.stdout)
  838. if inf is None:
  839. inf = getattr(sys.stdin, 'buffer', sys.stdin)
  840. path = os.path.expanduser(path)
  841. backend = FileSystemBackend(path)
  842. def send_fn(data):
  843. outf.write(data)
  844. outf.flush()
  845. proto = Protocol(inf.read, send_fn)
  846. handler = ReceivePackHandler(backend, [path], proto)
  847. # FIXME: Catch exceptions and write a single-line summary to outf.
  848. handler.handle()
  849. return 0
  850. def _make_branch_ref(name):
  851. if getattr(name, 'encode', None):
  852. name = name.encode(DEFAULT_ENCODING)
  853. return b"refs/heads/" + name
  854. def _make_tag_ref(name):
  855. if getattr(name, 'encode', None):
  856. name = name.encode(DEFAULT_ENCODING)
  857. return b"refs/tags/" + name
  858. def branch_delete(repo, name):
  859. """Delete a branch.
  860. :param repo: Path to the repository
  861. :param name: Name of the branch
  862. """
  863. with open_repo_closing(repo) as r:
  864. if isinstance(name, list):
  865. names = name
  866. else:
  867. names = [name]
  868. for name in names:
  869. del r.refs[_make_branch_ref(name)]
  870. def branch_create(repo, name, objectish=None, force=False):
  871. """Create a branch.
  872. :param repo: Path to the repository
  873. :param name: Name of the new branch
  874. :param objectish: Target object to point new branch at (defaults to HEAD)
  875. :param force: Force creation of branch, even if it already exists
  876. """
  877. with open_repo_closing(repo) as r:
  878. if objectish is None:
  879. objectish = "HEAD"
  880. object = parse_object(r, objectish)
  881. refname = _make_branch_ref(name)
  882. ref_message = b"branch: Created from " + objectish.encode('utf-8')
  883. if force:
  884. r.refs.set_if_equals(refname, None, object.id, message=ref_message)
  885. else:
  886. if not r.refs.add_if_new(refname, object.id, message=ref_message):
  887. raise KeyError("Branch with name %s already exists." % name)
  888. def branch_list(repo):
  889. """List all branches.
  890. :param repo: Path to the repository
  891. """
  892. with open_repo_closing(repo) as r:
  893. return r.refs.keys(base=b"refs/heads/")
  894. def fetch(repo, remote_location, remote_name=b'origin', outstream=sys.stdout,
  895. errstream=default_bytes_err_stream, message=None, **kwargs):
  896. """Fetch objects from a remote server.
  897. :param repo: Path to the repository
  898. :param remote_location: String identifying a remote server
  899. :param remote_name: Name for remote server
  900. :param outstream: Output stream (defaults to stdout)
  901. :param errstream: Error stream (defaults to stderr)
  902. :param message: Reflog message (defaults to b"fetch: from <remote_name>")
  903. :return: Dictionary with refs on the remote
  904. """
  905. if message is None:
  906. message = b'fetch: from ' + remote_location.encode("utf-8")
  907. with open_repo_closing(repo) as r:
  908. client, path = get_transport_and_path(
  909. remote_location, config=r.get_config_stack(), **kwargs)
  910. fetch_result = client.fetch(path, r, progress=errstream.write)
  911. stripped_refs = strip_peeled_refs(fetch_result.refs)
  912. branches = {
  913. n[len(b'refs/heads/'):]: v for (n, v) in stripped_refs.items()
  914. if n.startswith(b'refs/heads/')}
  915. r.refs.import_refs(
  916. b'refs/remotes/' + remote_name, branches, message=message)
  917. tags = {
  918. n[len(b'refs/tags/'):]: v for (n, v) in stripped_refs.items()
  919. if n.startswith(b'refs/tags/') and
  920. not n.endswith(ANNOTATED_TAG_SUFFIX)}
  921. r.refs.import_refs(b'refs/tags', tags, message=message)
  922. return fetch_result.refs
  923. def ls_remote(remote, config=None, **kwargs):
  924. """List the refs in a remote.
  925. :param remote: Remote repository location
  926. :param config: Configuration to use
  927. :return: Dictionary with remote refs
  928. """
  929. if config is None:
  930. config = StackedConfig.default()
  931. client, host_path = get_transport_and_path(remote, config=config, **kwargs)
  932. return client.get_refs(host_path)
  933. def repack(repo):
  934. """Repack loose files in a repository.
  935. Currently this only packs loose objects.
  936. :param repo: Path to the repository
  937. """
  938. with open_repo_closing(repo) as r:
  939. r.object_store.pack_loose_objects()
  940. def pack_objects(repo, object_ids, packf, idxf, delta_window_size=None):
  941. """Pack objects into a file.
  942. :param repo: Path to the repository
  943. :param object_ids: List of object ids to write
  944. :param packf: File-like object to write to
  945. :param idxf: File-like object to write to (can be None)
  946. """
  947. with open_repo_closing(repo) as r:
  948. entries, data_sum = write_pack_objects(
  949. packf,
  950. r.object_store.iter_shas((oid, None) for oid in object_ids),
  951. delta_window_size=delta_window_size)
  952. if idxf is not None:
  953. entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
  954. write_pack_index(idxf, entries, data_sum)
  955. def ls_tree(repo, treeish=b"HEAD", outstream=sys.stdout, recursive=False,
  956. name_only=False):
  957. """List contents of a tree.
  958. :param repo: Path to the repository
  959. :param tree_ish: Tree id to list
  960. :param outstream: Output stream (defaults to stdout)
  961. :param recursive: Whether to recursively list files
  962. :param name_only: Only print item name
  963. """
  964. def list_tree(store, treeid, base):
  965. for (name, mode, sha) in store[treeid].iteritems():
  966. if base:
  967. name = posixpath.join(base, name)
  968. if name_only:
  969. outstream.write(name + b"\n")
  970. else:
  971. outstream.write(pretty_format_tree_entry(name, mode, sha))
  972. if stat.S_ISDIR(mode) and recursive:
  973. list_tree(store, sha, name)
  974. with open_repo_closing(repo) as r:
  975. tree = parse_tree(r, treeish)
  976. list_tree(r.object_store, tree.id, "")
  977. def remote_add(repo, name, url):
  978. """Add a remote.
  979. :param repo: Path to the repository
  980. :param name: Remote name
  981. :param url: Remote URL
  982. """
  983. if not isinstance(name, bytes):
  984. name = name.encode(DEFAULT_ENCODING)
  985. if not isinstance(url, bytes):
  986. url = url.encode(DEFAULT_ENCODING)
  987. with open_repo_closing(repo) as r:
  988. c = r.get_config()
  989. section = (b'remote', name)
  990. if c.has_section(section):
  991. raise RemoteExists(section)
  992. c.set(section, b"url", url)
  993. c.write_to_path()
  994. def check_ignore(repo, paths, no_index=False):
  995. """Debug gitignore files.
  996. :param repo: Path to the repository
  997. :param paths: List of paths to check for
  998. :param no_index: Don't check index
  999. :return: List of ignored files
  1000. """
  1001. with open_repo_closing(repo) as r:
  1002. index = r.open_index()
  1003. ignore_manager = IgnoreFilterManager.from_repo(r)
  1004. for path in paths:
  1005. if not no_index and path_to_tree_path(r.path, path) in index:
  1006. continue
  1007. if os.path.isabs(path):
  1008. path = os.path.relpath(path, r.path)
  1009. if ignore_manager.is_ignored(path):
  1010. yield path
  1011. def update_head(repo, target, detached=False, new_branch=None):
  1012. """Update HEAD to point at a new branch/commit.
  1013. Note that this does not actually update the working tree.
  1014. :param repo: Path to the repository
  1015. :param detach: Create a detached head
  1016. :param target: Branch or committish to switch to
  1017. :param new_branch: New branch to create
  1018. """
  1019. with open_repo_closing(repo) as r:
  1020. if new_branch is not None:
  1021. to_set = _make_branch_ref(new_branch)
  1022. else:
  1023. to_set = b"HEAD"
  1024. if detached:
  1025. # TODO(jelmer): Provide some way so that the actual ref gets
  1026. # updated rather than what it points to, so the delete isn't
  1027. # necessary.
  1028. del r.refs[to_set]
  1029. r.refs[to_set] = parse_commit(r, target).id
  1030. else:
  1031. r.refs.set_symbolic_ref(to_set, parse_ref(r, target))
  1032. if new_branch is not None:
  1033. r.refs.set_symbolic_ref(b"HEAD", to_set)
  1034. def check_mailmap(repo, contact):
  1035. """Check canonical name and email of contact.
  1036. :param repo: Path to the repository
  1037. :param contact: Contact name and/or email
  1038. :return: Canonical contact data
  1039. """
  1040. with open_repo_closing(repo) as r:
  1041. from dulwich.mailmap import Mailmap
  1042. import errno
  1043. try:
  1044. mailmap = Mailmap.from_path(os.path.join(r.path, '.mailmap'))
  1045. except IOError as e:
  1046. if e.errno != errno.ENOENT:
  1047. raise
  1048. mailmap = Mailmap()
  1049. return mailmap.lookup(contact)
  1050. def fsck(repo):
  1051. """Check a repository.
  1052. :param repo: A path to the repository
  1053. :return: Iterator over errors/warnings
  1054. """
  1055. with open_repo_closing(repo) as r:
  1056. # TODO(jelmer): check pack files
  1057. # TODO(jelmer): check graph
  1058. # TODO(jelmer): check refs
  1059. for sha in r.object_store:
  1060. o = r.object_store[sha]
  1061. try:
  1062. o.check()
  1063. except Exception as e:
  1064. yield (sha, e)
  1065. def stash_list(repo):
  1066. """List all stashes in a repository."""
  1067. with open_repo_closing(repo) as r:
  1068. from dulwich.stash import Stash
  1069. stash = Stash.from_repo(r)
  1070. return enumerate(list(stash.stashes()))
  1071. def stash_push(repo):
  1072. """Push a new stash onto the stack."""
  1073. with open_repo_closing(repo) as r:
  1074. from dulwich.stash import Stash
  1075. stash = Stash.from_repo(r)
  1076. stash.push()
  1077. def stash_pop(repo):
  1078. """Pop a new stash from the stack."""
  1079. with open_repo_closing(repo) as r:
  1080. from dulwich.stash import Stash
  1081. stash = Stash.from_repo(r)
  1082. stash.pop()
  1083. def ls_files(repo):
  1084. """List all files in an index."""
  1085. with open_repo_closing(repo) as r:
  1086. return sorted(r.open_index())
  1087. def describe(repo):
  1088. """Describe the repository version.
  1089. :param projdir: git repository root
  1090. :returns: a string description of the current git revision
  1091. Examples: "gabcdefh", "v0.1" or "v0.1-5-gabcdefh".
  1092. """
  1093. # Get the repository
  1094. with open_repo_closing(repo) as r:
  1095. # Get a list of all tags
  1096. refs = r.get_refs()
  1097. tags = {}
  1098. for key, value in refs.items():
  1099. key = key.decode()
  1100. obj = r.get_object(value)
  1101. if u'tags' not in key:
  1102. continue
  1103. _, tag = key.rsplit(u'/', 1)
  1104. try:
  1105. commit = obj.object
  1106. except AttributeError:
  1107. continue
  1108. else:
  1109. commit = r.get_object(commit[1])
  1110. tags[tag] = [
  1111. datetime.datetime(*time.gmtime(commit.commit_time)[:6]),
  1112. commit.id.decode('ascii'),
  1113. ]
  1114. sorted_tags = sorted(tags.items(),
  1115. key=lambda tag: tag[1][0],
  1116. reverse=True)
  1117. # If there are no tags, return the current commit
  1118. if len(sorted_tags) == 0:
  1119. return 'g{}'.format(r[r.head()].id.decode('ascii')[:7])
  1120. # We're now 0 commits from the top
  1121. commit_count = 0
  1122. # Get the latest commit
  1123. latest_commit = r[r.head()]
  1124. # Walk through all commits
  1125. walker = r.get_walker()
  1126. for entry in walker:
  1127. # Check if tag
  1128. commit_id = entry.commit.id.decode('ascii')
  1129. for tag in sorted_tags:
  1130. tag_name = tag[0]
  1131. tag_commit = tag[1][1]
  1132. if commit_id == tag_commit:
  1133. if commit_count == 0:
  1134. return tag_name
  1135. else:
  1136. return '{}-{}-g{}'.format(
  1137. tag_name,
  1138. commit_count,
  1139. latest_commit.id.decode('ascii')[:7])
  1140. commit_count += 1
  1141. # Return plain commit if no parent tag can be found
  1142. return 'g{}'.format(latest_commit.id.decode('ascii')[:7])