porcelain.py 49 KB

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