porcelain.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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. * diff-tree
  32. * fetch
  33. * init
  34. * ls-files
  35. * ls-remote
  36. * ls-tree
  37. * pull
  38. * push
  39. * rm
  40. * remote{_add}
  41. * receive-pack
  42. * reset
  43. * rev-list
  44. * tag{_create,_delete,_list}
  45. * upload-pack
  46. * update-server-info
  47. * status
  48. * symbolic-ref
  49. These functions are meant to behave similarly to the git subcommands.
  50. Differences in behaviour are considered bugs.
  51. Functions should generally accept both unicode strings and bytestrings
  52. """
  53. from collections import namedtuple
  54. from contextlib import (
  55. closing,
  56. contextmanager,
  57. )
  58. from io import BytesIO
  59. import os
  60. import posixpath
  61. import stat
  62. import sys
  63. import time
  64. from dulwich.archive import (
  65. tar_stream,
  66. )
  67. from dulwich.client import (
  68. get_transport_and_path,
  69. )
  70. from dulwich.config import (
  71. StackedConfig,
  72. )
  73. from dulwich.diff_tree import (
  74. CHANGE_ADD,
  75. CHANGE_DELETE,
  76. CHANGE_MODIFY,
  77. CHANGE_RENAME,
  78. CHANGE_COPY,
  79. RENAME_CHANGE_TYPES,
  80. )
  81. from dulwich.errors import (
  82. SendPackError,
  83. UpdateRefsError,
  84. )
  85. from dulwich.ignore import IgnoreFilterManager
  86. from dulwich.index import (
  87. blob_from_path_and_stat,
  88. get_unstaged_changes,
  89. )
  90. from dulwich.object_store import (
  91. tree_lookup_path,
  92. )
  93. from dulwich.objects import (
  94. Commit,
  95. Tag,
  96. format_timezone,
  97. parse_timezone,
  98. pretty_format_tree_entry,
  99. )
  100. from dulwich.objectspec import (
  101. parse_commit,
  102. parse_object,
  103. parse_ref,
  104. parse_reftuples,
  105. parse_tree,
  106. )
  107. from dulwich.pack import (
  108. write_pack_index,
  109. write_pack_objects,
  110. )
  111. from dulwich.patch import write_tree_diff
  112. from dulwich.protocol import (
  113. Protocol,
  114. ZERO_SHA,
  115. )
  116. from dulwich.refs import (
  117. ANNOTATED_TAG_SUFFIX,
  118. strip_peeled_refs,
  119. )
  120. from dulwich.repo import (BaseRepo, Repo)
  121. from dulwich.server import (
  122. FileSystemBackend,
  123. TCPGitServer,
  124. ReceivePackHandler,
  125. UploadPackHandler,
  126. update_server_info as server_update_server_info,
  127. )
  128. # Module level tuple definition for status output
  129. GitStatus = namedtuple('GitStatus', 'staged unstaged untracked')
  130. default_bytes_out_stream = getattr(sys.stdout, 'buffer', sys.stdout)
  131. default_bytes_err_stream = getattr(sys.stderr, 'buffer', sys.stderr)
  132. DEFAULT_ENCODING = 'utf-8'
  133. class RemoteExists(Exception):
  134. """Raised when the remote already exists."""
  135. def open_repo(path_or_repo):
  136. """Open an argument that can be a repository or a path for a repository."""
  137. if isinstance(path_or_repo, BaseRepo):
  138. return path_or_repo
  139. return Repo(path_or_repo)
  140. @contextmanager
  141. def _noop_context_manager(obj):
  142. """Context manager that has the same api as closing but does nothing."""
  143. yield obj
  144. def open_repo_closing(path_or_repo):
  145. """Open an argument that can be a repository or a path for a repository.
  146. returns a context manager that will close the repo on exit if the argument
  147. is a path, else does nothing if the argument is a repo.
  148. """
  149. if isinstance(path_or_repo, BaseRepo):
  150. return _noop_context_manager(path_or_repo)
  151. return closing(Repo(path_or_repo))
  152. def path_to_tree_path(repopath, path):
  153. """Convert a path to a path usable in e.g. an index.
  154. :param repo: Repository
  155. :param path: A path
  156. :return: A path formatted for use in e.g. an index
  157. """
  158. os.path.relpath(path, repopath)
  159. if os.path.sep != '/':
  160. path = path.replace(os.path.sep, '/')
  161. return path.encode(sys.getfilesystemencoding())
  162. def archive(repo, committish=None, outstream=default_bytes_out_stream,
  163. errstream=default_bytes_err_stream):
  164. """Create an archive.
  165. :param repo: Path of repository for which to generate an archive.
  166. :param committish: Commit SHA1 or ref to use
  167. :param outstream: Output stream (defaults to stdout)
  168. :param errstream: Error stream (defaults to stderr)
  169. """
  170. if committish is None:
  171. committish = "HEAD"
  172. with open_repo_closing(repo) as repo_obj:
  173. c = repo_obj[committish]
  174. for chunk in tar_stream(
  175. repo_obj.object_store, repo_obj.object_store[c.tree],
  176. c.commit_time):
  177. outstream.write(chunk)
  178. def update_server_info(repo="."):
  179. """Update server info files for a repository.
  180. :param repo: path to the repository
  181. """
  182. with open_repo_closing(repo) as r:
  183. server_update_server_info(r)
  184. def symbolic_ref(repo, ref_name, force=False):
  185. """Set git symbolic ref into HEAD.
  186. :param repo: path to the repository
  187. :param ref_name: short name of the new ref
  188. :param force: force settings without checking if it exists in refs/heads
  189. """
  190. with open_repo_closing(repo) as repo_obj:
  191. ref_path = _make_branch_ref(ref_name)
  192. if not force and ref_path not in repo_obj.refs.keys():
  193. raise ValueError('fatal: ref `%s` is not a ref' % ref_name)
  194. repo_obj.refs.set_symbolic_ref(b'HEAD', ref_path)
  195. def commit(repo=".", message=None, author=None, committer=None, encoding=None):
  196. """Create a new commit.
  197. :param repo: Path to repository
  198. :param message: Optional commit message
  199. :param author: Optional author name and email
  200. :param committer: Optional committer name and email
  201. :return: SHA1 of the new commit
  202. """
  203. # FIXME: Support --all argument
  204. # FIXME: Support --signoff argument
  205. if getattr(message, 'encode', None):
  206. message = message.encode(encoding or DEFAULT_ENCODING)
  207. if getattr(author, 'encode', None):
  208. author = author.encode(encoding or DEFAULT_ENCODING)
  209. if getattr(committer, 'encode', None):
  210. committer = committer.encode(encoding or DEFAULT_ENCODING)
  211. with open_repo_closing(repo) as r:
  212. return r.do_commit(
  213. message=message, author=author, committer=committer,
  214. encoding=encoding)
  215. def commit_tree(repo, tree, message=None, author=None, committer=None):
  216. """Create a new commit object.
  217. :param repo: Path to repository
  218. :param tree: An existing tree object
  219. :param author: Optional author name and email
  220. :param committer: Optional committer name and email
  221. """
  222. with open_repo_closing(repo) as r:
  223. return r.do_commit(
  224. message=message, tree=tree, committer=committer, author=author)
  225. def init(path=".", bare=False):
  226. """Create a new git repository.
  227. :param path: Path to repository.
  228. :param bare: Whether to create a bare repository.
  229. :return: A Repo instance
  230. """
  231. if not os.path.exists(path):
  232. os.mkdir(path)
  233. if bare:
  234. return Repo.init_bare(path)
  235. else:
  236. return Repo.init(path)
  237. def clone(source, target=None, bare=False, checkout=None,
  238. errstream=default_bytes_err_stream, outstream=None,
  239. origin=b"origin", **kwargs):
  240. """Clone a local or remote git repository.
  241. :param source: Path or URL for source repository
  242. :param target: Path to target repository (optional)
  243. :param bare: Whether or not to create a bare repository
  244. :param checkout: Whether or not to check-out HEAD after cloning
  245. :param errstream: Optional stream to write progress to
  246. :param outstream: Optional stream to write progress to (deprecated)
  247. :param origin: Name of remote from the repository used to clone
  248. :return: The new repository
  249. """
  250. # TODO(jelmer): This code overlaps quite a bit with Repo.clone
  251. if outstream is not None:
  252. import warnings
  253. warnings.warn(
  254. "outstream= has been deprecated in favour of errstream=.",
  255. DeprecationWarning, stacklevel=3)
  256. errstream = outstream
  257. if checkout is None:
  258. checkout = (not bare)
  259. if checkout and bare:
  260. raise ValueError("checkout and bare are incompatible")
  261. if target is None:
  262. target = source.split("/")[-1]
  263. if not os.path.exists(target):
  264. os.mkdir(target)
  265. if bare:
  266. r = Repo.init_bare(target)
  267. else:
  268. r = Repo.init(target)
  269. reflog_message = b'clone: from ' + source.encode('utf-8')
  270. try:
  271. fetch_result = fetch(r, source, origin, message=reflog_message)
  272. target_config = r.get_config()
  273. if not isinstance(source, bytes):
  274. source = source.encode(DEFAULT_ENCODING)
  275. target_config.set((b'remote', origin), b'url', source)
  276. target_config.set(
  277. (b'remote', origin), b'fetch',
  278. b'+refs/heads/*:refs/remotes/' + origin + b'/*')
  279. target_config.write_to_path()
  280. # TODO(jelmer): Support symref capability,
  281. # https://github.com/jelmer/dulwich/issues/485
  282. try:
  283. head = r[fetch_result[b'HEAD']]
  284. except KeyError:
  285. head = None
  286. else:
  287. r[b'HEAD'] = head.id
  288. if checkout and not bare and head is not None:
  289. errstream.write(b'Checking out ' + head.id + b'\n')
  290. r.reset_index(head.tree)
  291. except BaseException:
  292. r.close()
  293. raise
  294. return r
  295. def add(repo=".", paths=None):
  296. """Add files to the staging area.
  297. :param repo: Repository for the files
  298. :param paths: Paths to add. No value passed stages all modified files.
  299. :return: Tuple with set of added files and ignored files
  300. """
  301. ignored = set()
  302. with open_repo_closing(repo) as r:
  303. ignore_manager = IgnoreFilterManager.from_repo(r)
  304. if not paths:
  305. paths = list(
  306. get_untracked_paths(os.getcwd(), r.path, r.open_index()))
  307. relpaths = []
  308. if not isinstance(paths, list):
  309. paths = [paths]
  310. for p in paths:
  311. relpath = os.path.relpath(p, r.path)
  312. if relpath.startswith('..' + os.path.sep):
  313. raise ValueError('path %r is not in repo' % relpath)
  314. # FIXME: Support patterns, directories.
  315. if ignore_manager.is_ignored(relpath):
  316. ignored.add(relpath)
  317. continue
  318. relpaths.append(relpath)
  319. r.stage(relpaths)
  320. return (relpaths, ignored)
  321. def remove(repo=".", paths=None, cached=False):
  322. """Remove files from the staging area.
  323. :param repo: Repository for the files
  324. :param paths: Paths to remove
  325. """
  326. with open_repo_closing(repo) as r:
  327. index = r.open_index()
  328. for p in paths:
  329. full_path = os.path.abspath(p).encode(sys.getfilesystemencoding())
  330. tree_path = path_to_tree_path(r.path, p)
  331. try:
  332. index_sha = index[tree_path].sha
  333. except KeyError:
  334. raise Exception('%s did not match any files' % p)
  335. if not cached:
  336. try:
  337. st = os.lstat(full_path)
  338. except OSError:
  339. pass
  340. else:
  341. try:
  342. blob = blob_from_path_and_stat(full_path, st)
  343. except IOError:
  344. pass
  345. else:
  346. try:
  347. committed_sha = tree_lookup_path(
  348. r.__getitem__, r[r.head()].tree, tree_path)[1]
  349. except KeyError:
  350. committed_sha = None
  351. if blob.id != index_sha and index_sha != committed_sha:
  352. raise Exception(
  353. 'file has staged content differing '
  354. 'from both the file and head: %s' % p)
  355. if index_sha != committed_sha:
  356. raise Exception(
  357. 'file has staged changes: %s' % p)
  358. os.remove(full_path)
  359. del index[tree_path]
  360. index.write()
  361. rm = remove
  362. def commit_decode(commit, contents, default_encoding=DEFAULT_ENCODING):
  363. if commit.encoding is not None:
  364. return contents.decode(commit.encoding, "replace")
  365. return contents.decode(default_encoding, "replace")
  366. def print_commit(commit, decode, outstream=sys.stdout):
  367. """Write a human-readable commit log entry.
  368. :param commit: A `Commit` object
  369. :param outstream: A stream file to write to
  370. """
  371. outstream.write("-" * 50 + "\n")
  372. outstream.write("commit: " + commit.id.decode('ascii') + "\n")
  373. if len(commit.parents) > 1:
  374. outstream.write(
  375. "merge: " +
  376. "...".join([c.decode('ascii') for c in commit.parents[1:]]) + "\n")
  377. outstream.write("Author: " + decode(commit.author) + "\n")
  378. if commit.author != commit.committer:
  379. outstream.write("Committer: " + decode(commit.committer) + "\n")
  380. time_tuple = time.gmtime(commit.author_time + commit.author_timezone)
  381. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  382. timezone_str = format_timezone(commit.author_timezone).decode('ascii')
  383. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  384. outstream.write("\n")
  385. outstream.write(decode(commit.message) + "\n")
  386. outstream.write("\n")
  387. def print_tag(tag, decode, outstream=sys.stdout):
  388. """Write a human-readable tag.
  389. :param tag: A `Tag` object
  390. :param decode: Function for decoding bytes to unicode string
  391. :param outstream: A stream to write to
  392. """
  393. outstream.write("Tagger: " + decode(tag.tagger) + "\n")
  394. outstream.write("Date: " + decode(tag.tag_time) + "\n")
  395. outstream.write("\n")
  396. outstream.write(decode(tag.message) + "\n")
  397. outstream.write("\n")
  398. def show_blob(repo, blob, decode, outstream=sys.stdout):
  399. """Write a blob to a stream.
  400. :param repo: A `Repo` object
  401. :param blob: A `Blob` object
  402. :param decode: Function for decoding bytes to unicode string
  403. :param outstream: A stream file to write to
  404. """
  405. outstream.write(decode(blob.data))
  406. def show_commit(repo, commit, decode, outstream=sys.stdout):
  407. """Show a commit to a stream.
  408. :param repo: A `Repo` object
  409. :param commit: A `Commit` object
  410. :param decode: Function for decoding bytes to unicode string
  411. :param outstream: Stream to write to
  412. """
  413. print_commit(commit, decode=decode, outstream=outstream)
  414. if commit.parents:
  415. parent_commit = repo[commit.parents[0]]
  416. base_tree = parent_commit.tree
  417. else:
  418. base_tree = None
  419. diffstream = BytesIO()
  420. write_tree_diff(
  421. diffstream,
  422. repo.object_store, base_tree, commit.tree)
  423. diffstream.seek(0)
  424. outstream.write(
  425. diffstream.getvalue().decode(
  426. commit.encoding or DEFAULT_ENCODING, 'replace'))
  427. def show_tree(repo, tree, decode, outstream=sys.stdout):
  428. """Print a tree to a stream.
  429. :param repo: A `Repo` object
  430. :param tree: A `Tree` object
  431. :param decode: Function for decoding bytes to unicode string
  432. :param outstream: Stream to write to
  433. """
  434. for n in tree:
  435. outstream.write(decode(n) + "\n")
  436. def show_tag(repo, tag, decode, outstream=sys.stdout):
  437. """Print a tag to a stream.
  438. :param repo: A `Repo` object
  439. :param tag: A `Tag` object
  440. :param decode: Function for decoding bytes to unicode string
  441. :param outstream: Stream to write to
  442. """
  443. print_tag(tag, decode, outstream)
  444. show_object(repo, repo[tag.object[1]], outstream)
  445. def show_object(repo, obj, decode, outstream):
  446. return {
  447. b"tree": show_tree,
  448. b"blob": show_blob,
  449. b"commit": show_commit,
  450. b"tag": show_tag,
  451. }[obj.type_name](repo, obj, decode, outstream)
  452. def print_name_status(changes):
  453. """Print a simple status summary, listing changed files.
  454. """
  455. for change in changes:
  456. if not change:
  457. continue
  458. if isinstance(change, list):
  459. change = change[0]
  460. if change.type == CHANGE_ADD:
  461. path1 = change.new.path
  462. path2 = ''
  463. kind = 'A'
  464. elif change.type == CHANGE_DELETE:
  465. path1 = change.old.path
  466. path2 = ''
  467. kind = 'D'
  468. elif change.type == CHANGE_MODIFY:
  469. path1 = change.new.path
  470. path2 = ''
  471. kind = 'M'
  472. elif change.type in RENAME_CHANGE_TYPES:
  473. path1 = change.old.path
  474. path2 = change.new.path
  475. if change.type == CHANGE_RENAME:
  476. kind = 'R'
  477. elif change.type == CHANGE_COPY:
  478. kind = 'C'
  479. yield '%-8s%-20s%-20s' % (kind, path1, path2)
  480. def log(repo=".", paths=None, outstream=sys.stdout, max_entries=None,
  481. reverse=False, name_status=False):
  482. """Write commit logs.
  483. :param repo: Path to repository
  484. :param paths: Optional set of specific paths to print entries for
  485. :param outstream: Stream to write log output to
  486. :param reverse: Reverse order in which entries are printed
  487. :param name_status: Print name status
  488. :param max_entries: Optional maximum number of entries to display
  489. """
  490. with open_repo_closing(repo) as r:
  491. walker = r.get_walker(
  492. max_entries=max_entries, paths=paths, reverse=reverse)
  493. for entry in walker:
  494. def decode(x):
  495. return commit_decode(entry.commit, x)
  496. print_commit(entry.commit, decode, outstream)
  497. if name_status:
  498. outstream.writelines(
  499. [l+'\n' for l in print_name_status(entry.changes())])
  500. # TODO(jelmer): better default for encoding?
  501. def show(repo=".", objects=None, outstream=sys.stdout,
  502. default_encoding=DEFAULT_ENCODING):
  503. """Print the changes in a commit.
  504. :param repo: Path to repository
  505. :param objects: Objects to show (defaults to [HEAD])
  506. :param outstream: Stream to write to
  507. :param default_encoding: Default encoding to use if none is set in the
  508. commit
  509. """
  510. if objects is None:
  511. objects = ["HEAD"]
  512. if not isinstance(objects, list):
  513. objects = [objects]
  514. with open_repo_closing(repo) as r:
  515. for objectish in objects:
  516. o = parse_object(r, objectish)
  517. if isinstance(o, Commit):
  518. def decode(x):
  519. return commit_decode(o, x, default_encoding)
  520. else:
  521. def decode(x):
  522. return x.decode(default_encoding)
  523. show_object(r, o, decode, outstream)
  524. def diff_tree(repo, old_tree, new_tree, outstream=sys.stdout):
  525. """Compares the content and mode of blobs found via two tree objects.
  526. :param repo: Path to repository
  527. :param old_tree: Id of old tree
  528. :param new_tree: Id of new tree
  529. :param outstream: Stream to write to
  530. """
  531. with open_repo_closing(repo) as r:
  532. write_tree_diff(outstream, r.object_store, old_tree, new_tree)
  533. def rev_list(repo, commits, outstream=sys.stdout):
  534. """Lists commit objects in reverse chronological order.
  535. :param repo: Path to repository
  536. :param commits: Commits over which to iterate
  537. :param outstream: Stream to write to
  538. """
  539. with open_repo_closing(repo) as r:
  540. for entry in r.get_walker(include=[r[c].id for c in commits]):
  541. outstream.write(entry.commit.id + b"\n")
  542. def tag(*args, **kwargs):
  543. import warnings
  544. warnings.warn("tag has been deprecated in favour of tag_create.",
  545. DeprecationWarning)
  546. return tag_create(*args, **kwargs)
  547. def tag_create(
  548. repo, tag, author=None, message=None, annotated=False,
  549. objectish="HEAD", tag_time=None, tag_timezone=None):
  550. """Creates a tag in git via dulwich calls:
  551. :param repo: Path to repository
  552. :param tag: tag string
  553. :param author: tag author (optional, if annotated is set)
  554. :param message: tag message (optional)
  555. :param annotated: whether to create an annotated tag
  556. :param objectish: object the tag should point at, defaults to HEAD
  557. :param tag_time: Optional time for annotated tag
  558. :param tag_timezone: Optional timezone for annotated tag
  559. """
  560. with open_repo_closing(repo) as r:
  561. object = parse_object(r, objectish)
  562. if annotated:
  563. # Create the tag object
  564. tag_obj = Tag()
  565. if author is None:
  566. # TODO(jelmer): Don't use repo private method.
  567. author = r._get_user_identity()
  568. tag_obj.tagger = author
  569. tag_obj.message = message
  570. tag_obj.name = tag
  571. tag_obj.object = (type(object), object.id)
  572. if tag_time is None:
  573. tag_time = int(time.time())
  574. tag_obj.tag_time = tag_time
  575. if tag_timezone is None:
  576. # TODO(jelmer) Use current user timezone rather than UTC
  577. tag_timezone = 0
  578. elif isinstance(tag_timezone, str):
  579. tag_timezone = parse_timezone(tag_timezone)
  580. tag_obj.tag_timezone = tag_timezone
  581. r.object_store.add_object(tag_obj)
  582. tag_id = tag_obj.id
  583. else:
  584. tag_id = object.id
  585. r.refs[_make_tag_ref(tag)] = tag_id
  586. def list_tags(*args, **kwargs):
  587. import warnings
  588. warnings.warn("list_tags has been deprecated in favour of tag_list.",
  589. DeprecationWarning)
  590. return tag_list(*args, **kwargs)
  591. def tag_list(repo, outstream=sys.stdout):
  592. """List all tags.
  593. :param repo: Path to repository
  594. :param outstream: Stream to write tags to
  595. """
  596. with open_repo_closing(repo) as r:
  597. tags = sorted(r.refs.as_dict(b"refs/tags"))
  598. return tags
  599. def tag_delete(repo, name):
  600. """Remove a tag.
  601. :param repo: Path to repository
  602. :param name: Name of tag to remove
  603. """
  604. with open_repo_closing(repo) as r:
  605. if isinstance(name, bytes):
  606. names = [name]
  607. elif isinstance(name, list):
  608. names = name
  609. else:
  610. raise TypeError("Unexpected tag name type %r" % name)
  611. for name in names:
  612. del r.refs[_make_tag_ref(name)]
  613. def reset(repo, mode, treeish="HEAD"):
  614. """Reset current HEAD to the specified state.
  615. :param repo: Path to repository
  616. :param mode: Mode ("hard", "soft", "mixed")
  617. :param treeish: Treeish to reset to
  618. """
  619. if mode != "hard":
  620. raise ValueError("hard is the only mode currently supported")
  621. with open_repo_closing(repo) as r:
  622. tree = parse_tree(r, treeish)
  623. r.reset_index(tree.id)
  624. def push(repo, remote_location, refspecs,
  625. outstream=default_bytes_out_stream,
  626. errstream=default_bytes_err_stream, **kwargs):
  627. """Remote push with dulwich via dulwich.client
  628. :param repo: Path to repository
  629. :param remote_location: Location of the remote
  630. :param refspecs: Refs to push to remote
  631. :param outstream: A stream file to write output
  632. :param errstream: A stream file to write errors
  633. """
  634. # Open the repo
  635. with open_repo_closing(repo) as r:
  636. # Get the client and path
  637. client, path = get_transport_and_path(
  638. remote_location, config=r.get_config_stack(), **kwargs)
  639. selected_refs = []
  640. def update_refs(refs):
  641. selected_refs.extend(parse_reftuples(r.refs, refs, refspecs))
  642. new_refs = {}
  643. # TODO: Handle selected_refs == {None: None}
  644. for (lh, rh, force) in selected_refs:
  645. if lh is None:
  646. new_refs[rh] = ZERO_SHA
  647. else:
  648. new_refs[rh] = r.refs[lh]
  649. return new_refs
  650. err_encoding = getattr(errstream, 'encoding', None) or DEFAULT_ENCODING
  651. remote_location_bytes = client.get_url(path).encode(err_encoding)
  652. try:
  653. client.send_pack(
  654. path, update_refs,
  655. generate_pack_data=r.object_store.generate_pack_data,
  656. progress=errstream.write)
  657. errstream.write(
  658. b"Push to " + remote_location_bytes + b" successful.\n")
  659. except (UpdateRefsError, SendPackError) as e:
  660. errstream.write(b"Push to " + remote_location_bytes +
  661. b" failed -> " + e.message.encode(err_encoding) +
  662. b"\n")
  663. def pull(repo, remote_location=None, refspecs=None,
  664. outstream=default_bytes_out_stream,
  665. errstream=default_bytes_err_stream, **kwargs):
  666. """Pull from remote via dulwich.client
  667. :param repo: Path to repository
  668. :param remote_location: Location of the remote
  669. :param refspec: refspecs to fetch
  670. :param outstream: A stream file to write to output
  671. :param errstream: A stream file to write to errors
  672. """
  673. # Open the repo
  674. with open_repo_closing(repo) as r:
  675. if remote_location is None:
  676. # TODO(jelmer): Lookup 'remote' for current branch in config
  677. raise NotImplementedError(
  678. "looking up remote from branch config not supported yet")
  679. if refspecs is None:
  680. refspecs = [b"HEAD"]
  681. selected_refs = []
  682. def determine_wants(remote_refs):
  683. selected_refs.extend(
  684. parse_reftuples(remote_refs, r.refs, refspecs))
  685. return [remote_refs[lh] for (lh, rh, force) in selected_refs]
  686. client, path = get_transport_and_path(
  687. remote_location, config=r.get_config_stack(), **kwargs)
  688. fetch_result = client.fetch(
  689. path, r, progress=errstream.write, determine_wants=determine_wants)
  690. for (lh, rh, force) in selected_refs:
  691. r.refs[rh] = fetch_result.refs[lh]
  692. if selected_refs:
  693. r[b'HEAD'] = fetch_result.refs[selected_refs[0][1]]
  694. # Perform 'git checkout .' - syncs staged changes
  695. tree = r[b"HEAD"].tree
  696. r.reset_index(tree=tree)
  697. def status(repo=".", ignored=False):
  698. """Returns staged, unstaged, and untracked changes relative to the HEAD.
  699. :param repo: Path to repository or repository object
  700. :param ignored: Whether to include ignored files in `untracked`
  701. :return: GitStatus tuple,
  702. staged - list of staged paths (diff index/HEAD)
  703. unstaged - list of unstaged paths (diff index/working-tree)
  704. untracked - list of untracked, un-ignored & non-.git paths
  705. """
  706. with open_repo_closing(repo) as r:
  707. # 1. Get status of staged
  708. tracked_changes = get_tree_changes(r)
  709. # 2. Get status of unstaged
  710. index = r.open_index()
  711. unstaged_changes = list(get_unstaged_changes(index, r.path))
  712. ignore_manager = IgnoreFilterManager.from_repo(r)
  713. untracked_paths = get_untracked_paths(r.path, r.path, index)
  714. if ignored:
  715. untracked_changes = list(untracked_paths)
  716. else:
  717. untracked_changes = [
  718. p for p in untracked_paths
  719. if not ignore_manager.is_ignored(p)]
  720. return GitStatus(tracked_changes, unstaged_changes, untracked_changes)
  721. def get_untracked_paths(frompath, basepath, index):
  722. """Get untracked paths.
  723. ;param frompath: Path to walk
  724. :param basepath: Path to compare to
  725. :param index: Index to check against
  726. """
  727. # If nothing is specified, add all non-ignored files.
  728. for dirpath, dirnames, filenames in os.walk(frompath):
  729. # Skip .git and below.
  730. if '.git' in dirnames:
  731. dirnames.remove('.git')
  732. if dirpath != basepath:
  733. continue
  734. if '.git' in filenames:
  735. filenames.remove('.git')
  736. if dirpath != basepath:
  737. continue
  738. for filename in filenames:
  739. ap = os.path.join(dirpath, filename)
  740. ip = path_to_tree_path(basepath, ap)
  741. if ip not in index:
  742. yield os.path.relpath(ap, frompath)
  743. def get_tree_changes(repo):
  744. """Return add/delete/modify changes to tree by comparing index to HEAD.
  745. :param repo: repo path or object
  746. :return: dict with lists for each type of change
  747. """
  748. with open_repo_closing(repo) as r:
  749. index = r.open_index()
  750. # Compares the Index to the HEAD & determines changes
  751. # Iterate through the changes and report add/delete/modify
  752. # TODO: call out to dulwich.diff_tree somehow.
  753. tracked_changes = {
  754. 'add': [],
  755. 'delete': [],
  756. 'modify': [],
  757. }
  758. try:
  759. tree_id = r[b'HEAD'].tree
  760. except KeyError:
  761. tree_id = None
  762. for change in index.changes_from_tree(r.object_store, tree_id):
  763. if not change[0][0]:
  764. tracked_changes['add'].append(change[0][1])
  765. elif not change[0][1]:
  766. tracked_changes['delete'].append(change[0][0])
  767. elif change[0][0] == change[0][1]:
  768. tracked_changes['modify'].append(change[0][0])
  769. else:
  770. raise AssertionError('git mv ops not yet supported')
  771. return tracked_changes
  772. def daemon(path=".", address=None, port=None):
  773. """Run a daemon serving Git requests over TCP/IP.
  774. :param path: Path to the directory to serve.
  775. :param address: Optional address to listen on (defaults to ::)
  776. :param port: Optional port to listen on (defaults to TCP_GIT_PORT)
  777. """
  778. # TODO(jelmer): Support git-daemon-export-ok and --export-all.
  779. backend = FileSystemBackend(path)
  780. server = TCPGitServer(backend, address, port)
  781. server.serve_forever()
  782. def web_daemon(path=".", address=None, port=None):
  783. """Run a daemon serving Git requests over HTTP.
  784. :param path: Path to the directory to serve
  785. :param address: Optional address to listen on (defaults to ::)
  786. :param port: Optional port to listen on (defaults to 80)
  787. """
  788. from dulwich.web import (
  789. make_wsgi_chain,
  790. make_server,
  791. WSGIRequestHandlerLogger,
  792. WSGIServerLogger)
  793. backend = FileSystemBackend(path)
  794. app = make_wsgi_chain(backend)
  795. server = make_server(address, port, app,
  796. handler_class=WSGIRequestHandlerLogger,
  797. server_class=WSGIServerLogger)
  798. server.serve_forever()
  799. def upload_pack(path=".", inf=None, outf=None):
  800. """Upload a pack file after negotiating its contents using smart protocol.
  801. :param path: Path to the repository
  802. :param inf: Input stream to communicate with client
  803. :param outf: Output stream to communicate with client
  804. """
  805. if outf is None:
  806. outf = getattr(sys.stdout, 'buffer', sys.stdout)
  807. if inf is None:
  808. inf = getattr(sys.stdin, 'buffer', sys.stdin)
  809. path = os.path.expanduser(path)
  810. backend = FileSystemBackend(path)
  811. def send_fn(data):
  812. outf.write(data)
  813. outf.flush()
  814. proto = Protocol(inf.read, send_fn)
  815. handler = UploadPackHandler(backend, [path], proto)
  816. # FIXME: Catch exceptions and write a single-line summary to outf.
  817. handler.handle()
  818. return 0
  819. def receive_pack(path=".", inf=None, outf=None):
  820. """Receive a pack file after negotiating its contents using smart protocol.
  821. :param path: Path to the repository
  822. :param inf: Input stream to communicate with client
  823. :param outf: Output stream to communicate with client
  824. """
  825. if outf is None:
  826. outf = getattr(sys.stdout, 'buffer', sys.stdout)
  827. if inf is None:
  828. inf = getattr(sys.stdin, 'buffer', sys.stdin)
  829. path = os.path.expanduser(path)
  830. backend = FileSystemBackend(path)
  831. def send_fn(data):
  832. outf.write(data)
  833. outf.flush()
  834. proto = Protocol(inf.read, send_fn)
  835. handler = ReceivePackHandler(backend, [path], proto)
  836. # FIXME: Catch exceptions and write a single-line summary to outf.
  837. handler.handle()
  838. return 0
  839. def _make_branch_ref(name):
  840. if getattr(name, 'encode', None):
  841. name = name.encode(DEFAULT_ENCODING)
  842. return b"refs/heads/" + name
  843. def _make_tag_ref(name):
  844. if getattr(name, 'encode', None):
  845. name = name.encode(DEFAULT_ENCODING)
  846. return b"refs/tags/" + name
  847. def branch_delete(repo, name):
  848. """Delete a branch.
  849. :param repo: Path to the repository
  850. :param name: Name of the branch
  851. """
  852. with open_repo_closing(repo) as r:
  853. if isinstance(name, list):
  854. names = name
  855. else:
  856. names = [name]
  857. for name in names:
  858. del r.refs[_make_branch_ref(name)]
  859. def branch_create(repo, name, objectish=None, force=False):
  860. """Create a branch.
  861. :param repo: Path to the repository
  862. :param name: Name of the new branch
  863. :param objectish: Target object to point new branch at (defaults to HEAD)
  864. :param force: Force creation of branch, even if it already exists
  865. """
  866. with open_repo_closing(repo) as r:
  867. if objectish is None:
  868. objectish = "HEAD"
  869. object = parse_object(r, objectish)
  870. refname = _make_branch_ref(name)
  871. ref_message = b"branch: Created from " + objectish.encode('utf-8')
  872. if force:
  873. r.refs.set_if_equals(refname, None, object.id, message=ref_message)
  874. else:
  875. if not r.refs.add_if_new(refname, object.id, message=ref_message):
  876. raise KeyError("Branch with name %s already exists." % name)
  877. def branch_list(repo):
  878. """List all branches.
  879. :param repo: Path to the repository
  880. """
  881. with open_repo_closing(repo) as r:
  882. return r.refs.keys(base=b"refs/heads/")
  883. def fetch(repo, remote_location, remote_name=b'origin', outstream=sys.stdout,
  884. errstream=default_bytes_err_stream, message=None, **kwargs):
  885. """Fetch objects from a remote server.
  886. :param repo: Path to the repository
  887. :param remote_location: String identifying a remote server
  888. :param remote_name: Name for remote server
  889. :param outstream: Output stream (defaults to stdout)
  890. :param errstream: Error stream (defaults to stderr)
  891. :param message: Reflog message (defaults to b"fetch: from <remote_name>")
  892. :return: Dictionary with refs on the remote
  893. """
  894. if message is None:
  895. message = b'fetch: from ' + remote_location.encode("utf-8")
  896. with open_repo_closing(repo) as r:
  897. client, path = get_transport_and_path(
  898. remote_location, config=r.get_config_stack(), **kwargs)
  899. fetch_result = client.fetch(path, r, progress=errstream.write)
  900. stripped_refs = strip_peeled_refs(fetch_result.refs)
  901. branches = {
  902. n[len(b'refs/heads/'):]: v for (n, v) in stripped_refs.items()
  903. if n.startswith(b'refs/heads/')}
  904. r.refs.import_refs(
  905. b'refs/remotes/' + remote_name, branches, message=message)
  906. tags = {
  907. n[len(b'refs/tags/'):]: v for (n, v) in stripped_refs.items()
  908. if n.startswith(b'refs/tags/') and
  909. not n.endswith(ANNOTATED_TAG_SUFFIX)}
  910. r.refs.import_refs(b'refs/tags', tags, message=message)
  911. return fetch_result.refs
  912. def ls_remote(remote, config=None, **kwargs):
  913. """List the refs in a remote.
  914. :param remote: Remote repository location
  915. :param config: Configuration to use
  916. :return: Dictionary with remote refs
  917. """
  918. if config is None:
  919. config = StackedConfig.default()
  920. client, host_path = get_transport_and_path(remote, config=config, **kwargs)
  921. return client.get_refs(host_path)
  922. def repack(repo):
  923. """Repack loose files in a repository.
  924. Currently this only packs loose objects.
  925. :param repo: Path to the repository
  926. """
  927. with open_repo_closing(repo) as r:
  928. r.object_store.pack_loose_objects()
  929. def pack_objects(repo, object_ids, packf, idxf, delta_window_size=None):
  930. """Pack objects into a file.
  931. :param repo: Path to the repository
  932. :param object_ids: List of object ids to write
  933. :param packf: File-like object to write to
  934. :param idxf: File-like object to write to (can be None)
  935. """
  936. with open_repo_closing(repo) as r:
  937. entries, data_sum = write_pack_objects(
  938. packf,
  939. r.object_store.iter_shas((oid, None) for oid in object_ids),
  940. delta_window_size=delta_window_size)
  941. if idxf is not None:
  942. entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
  943. write_pack_index(idxf, entries, data_sum)
  944. def ls_tree(repo, treeish=b"HEAD", outstream=sys.stdout, recursive=False,
  945. name_only=False):
  946. """List contents of a tree.
  947. :param repo: Path to the repository
  948. :param tree_ish: Tree id to list
  949. :param outstream: Output stream (defaults to stdout)
  950. :param recursive: Whether to recursively list files
  951. :param name_only: Only print item name
  952. """
  953. def list_tree(store, treeid, base):
  954. for (name, mode, sha) in store[treeid].iteritems():
  955. if base:
  956. name = posixpath.join(base, name)
  957. if name_only:
  958. outstream.write(name + b"\n")
  959. else:
  960. outstream.write(pretty_format_tree_entry(name, mode, sha))
  961. if stat.S_ISDIR(mode) and recursive:
  962. list_tree(store, sha, name)
  963. with open_repo_closing(repo) as r:
  964. tree = parse_tree(r, treeish)
  965. list_tree(r.object_store, tree.id, "")
  966. def remote_add(repo, name, url):
  967. """Add a remote.
  968. :param repo: Path to the repository
  969. :param name: Remote name
  970. :param url: Remote URL
  971. """
  972. if not isinstance(name, bytes):
  973. name = name.encode(DEFAULT_ENCODING)
  974. if not isinstance(url, bytes):
  975. url = url.encode(DEFAULT_ENCODING)
  976. with open_repo_closing(repo) as r:
  977. c = r.get_config()
  978. section = (b'remote', name)
  979. if c.has_section(section):
  980. raise RemoteExists(section)
  981. c.set(section, b"url", url)
  982. c.write_to_path()
  983. def check_ignore(repo, paths, no_index=False):
  984. """Debug gitignore files.
  985. :param repo: Path to the repository
  986. :param paths: List of paths to check for
  987. :param no_index: Don't check index
  988. :return: List of ignored files
  989. """
  990. with open_repo_closing(repo) as r:
  991. index = r.open_index()
  992. ignore_manager = IgnoreFilterManager.from_repo(r)
  993. for path in paths:
  994. if os.path.isabs(path):
  995. path = os.path.relpath(path, r.path)
  996. if not no_index and path_to_tree_path(r.path, path) in index:
  997. continue
  998. if ignore_manager.is_ignored(path):
  999. yield path
  1000. def update_head(repo, target, detached=False, new_branch=None):
  1001. """Update HEAD to point at a new branch/commit.
  1002. Note that this does not actually update the working tree.
  1003. :param repo: Path to the repository
  1004. :param detach: Create a detached head
  1005. :param target: Branch or committish to switch to
  1006. :param new_branch: New branch to create
  1007. """
  1008. with open_repo_closing(repo) as r:
  1009. if new_branch is not None:
  1010. to_set = _make_branch_ref(new_branch)
  1011. else:
  1012. to_set = b"HEAD"
  1013. if detached:
  1014. # TODO(jelmer): Provide some way so that the actual ref gets
  1015. # updated rather than what it points to, so the delete isn't
  1016. # necessary.
  1017. del r.refs[to_set]
  1018. r.refs[to_set] = parse_commit(r, target).id
  1019. else:
  1020. r.refs.set_symbolic_ref(to_set, parse_ref(r, target))
  1021. if new_branch is not None:
  1022. r.refs.set_symbolic_ref(b"HEAD", to_set)
  1023. def check_mailmap(repo, contact):
  1024. """Check canonical name and email of contact.
  1025. :param repo: Path to the repository
  1026. :param contact: Contact name and/or email
  1027. :return: Canonical contact data
  1028. """
  1029. with open_repo_closing(repo) as r:
  1030. from dulwich.mailmap import Mailmap
  1031. import errno
  1032. try:
  1033. mailmap = Mailmap.from_path(os.path.join(r.path, '.mailmap'))
  1034. except IOError as e:
  1035. if e.errno != errno.ENOENT:
  1036. raise
  1037. mailmap = Mailmap()
  1038. return mailmap.lookup(contact)
  1039. def fsck(repo):
  1040. """Check a repository.
  1041. :param repo: A path to the repository
  1042. :return: Iterator over errors/warnings
  1043. """
  1044. with open_repo_closing(repo) as r:
  1045. # TODO(jelmer): check pack files
  1046. # TODO(jelmer): check graph
  1047. # TODO(jelmer): check refs
  1048. for sha in r.object_store:
  1049. o = r.object_store[sha]
  1050. try:
  1051. o.check()
  1052. except Exception as e:
  1053. yield (sha, e)
  1054. def stash_list(repo):
  1055. """List all stashes in a repository."""
  1056. with open_repo_closing(repo) as r:
  1057. from dulwich.stash import Stash
  1058. stash = Stash.from_repo(r)
  1059. return enumerate(list(stash.stashes()))
  1060. def stash_push(repo):
  1061. """Push a new stash onto the stack."""
  1062. with open_repo_closing(repo) as r:
  1063. from dulwich.stash import Stash
  1064. stash = Stash.from_repo(r)
  1065. stash.push()
  1066. def stash_pop(repo):
  1067. """Pop a new stash from the stack."""
  1068. with open_repo_closing(repo) as r:
  1069. from dulwich.stash import Stash
  1070. stash = Stash.from_repo(r)
  1071. stash.pop()
  1072. def ls_files(repo):
  1073. """List all files in an index."""
  1074. with open_repo_closing(repo) as r:
  1075. return sorted(r.open_index())