porcelain.py 54 KB

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