porcelain.py 26 KB

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