porcelain.py 58 KB

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