porcelain.py 22 KB

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