porcelain.py 32 KB

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