porcelain.py 29 KB

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