porcelain.py 24 KB

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