porcelain.py 54 KB

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