porcelain.py 39 KB

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