porcelain.py 51 KB

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