porcelain.py 38 KB

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