porcelain.py 36 KB

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