porcelain.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. * clone
  23. * commit
  24. * commit-tree
  25. * daemon
  26. * diff-tree
  27. * init
  28. * list-tags
  29. * pull
  30. * push
  31. * rm
  32. * receive-pack
  33. * reset
  34. * rev-list
  35. * tag
  36. * upload-pack
  37. * update-server-info
  38. * status
  39. * symbolic-ref
  40. These functions are meant to behave similarly to the git subcommands.
  41. Differences in behaviour are considered bugs.
  42. """
  43. __docformat__ = 'restructuredText'
  44. from collections import namedtuple
  45. import os
  46. import sys
  47. import time
  48. from dulwich import index
  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 = 'refs/heads/%s' % 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('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, outstream=sys.stdout):
  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 outstream: Optional stream to write progress to
  150. :return: The new repository
  151. """
  152. if checkout is None:
  153. checkout = (not bare)
  154. if checkout and bare:
  155. raise ValueError("checkout and bare are incompatible")
  156. client, host_path = get_transport_and_path(source)
  157. if target is None:
  158. target = host_path.split("/")[-1]
  159. if not os.path.exists(target):
  160. os.mkdir(target)
  161. if bare:
  162. r = Repo.init_bare(target)
  163. else:
  164. r = Repo.init(target)
  165. remote_refs = client.fetch(host_path, r,
  166. determine_wants=r.object_store.determine_wants_all,
  167. progress=outstream.write)
  168. r["HEAD"] = remote_refs["HEAD"]
  169. if checkout:
  170. outstream.write('Checking out HEAD')
  171. index.build_index_from_tree(r.path, r.index_path(),
  172. r.object_store, r["HEAD"].tree)
  173. return r
  174. def add(repo=".", paths=None):
  175. """Add files to the staging area.
  176. :param repo: Repository for the files
  177. :param paths: Paths to add. No value passed stages all modified files.
  178. """
  179. # FIXME: Support patterns, directories.
  180. r = open_repo(repo)
  181. if not paths:
  182. # If nothing is specified, add all non-ignored files.
  183. paths = []
  184. for dirpath, dirnames, filenames in os.walk(r.path):
  185. # Skip .git and below.
  186. if '.git' in dirnames:
  187. dirnames.remove('.git')
  188. for filename in filenames:
  189. paths.append(os.path.join(dirpath[len(r.path)+1:], filename))
  190. r.stage(paths)
  191. def rm(repo=".", paths=None):
  192. """Remove files from the staging area.
  193. :param repo: Repository for the files
  194. :param paths: Paths to remove
  195. """
  196. r = open_repo(repo)
  197. index = r.open_index()
  198. for p in paths:
  199. del index[p]
  200. index.write()
  201. def print_commit(commit, outstream=sys.stdout):
  202. """Write a human-readable commit log entry.
  203. :param commit: A `Commit` object
  204. :param outstream: A stream file to write to
  205. """
  206. outstream.write("-" * 50 + "\n")
  207. outstream.write("commit: %s\n" % commit.id)
  208. if len(commit.parents) > 1:
  209. outstream.write("merge: %s\n" % "...".join(commit.parents[1:]))
  210. outstream.write("author: %s\n" % commit.author)
  211. outstream.write("committer: %s\n" % commit.committer)
  212. outstream.write("\n")
  213. outstream.write(commit.message + "\n")
  214. outstream.write("\n")
  215. def print_tag(tag, outstream=sys.stdout):
  216. """Write a human-readable tag.
  217. :param tag: A `Tag` object
  218. :param outstream: A stream to write to
  219. """
  220. outstream.write("Tagger: %s\n" % tag.tagger)
  221. outstream.write("Date: %s\n" % tag.tag_time)
  222. outstream.write("\n")
  223. outstream.write("%s\n" % tag.message)
  224. outstream.write("\n")
  225. def show_blob(repo, blob, outstream=sys.stdout):
  226. """Write a blob to a stream.
  227. :param repo: A `Repo` object
  228. :param blob: A `Blob` object
  229. :param outstream: A stream file to write to
  230. """
  231. outstream.write(blob.data)
  232. def show_commit(repo, commit, outstream=sys.stdout):
  233. """Show a commit to a stream.
  234. :param repo: A `Repo` object
  235. :param commit: A `Commit` object
  236. :param outstream: Stream to write to
  237. """
  238. print_commit(commit, outstream)
  239. parent_commit = repo[commit.parents[0]]
  240. write_tree_diff(outstream, repo.object_store, parent_commit.tree, commit.tree)
  241. def show_tree(repo, tree, outstream=sys.stdout):
  242. """Print a tree to a stream.
  243. :param repo: A `Repo` object
  244. :param tree: A `Tree` object
  245. :param outstream: Stream to write to
  246. """
  247. for n in tree:
  248. outstream.write("%s\n" % n)
  249. def show_tag(repo, tag, outstream=sys.stdout):
  250. """Print a tag to a stream.
  251. :param repo: A `Repo` object
  252. :param tag: A `Tag` object
  253. :param outstream: Stream to write to
  254. """
  255. print_tag(tag, outstream)
  256. show_object(repo, repo[tag.object[1]], outstream)
  257. def show_object(repo, obj, outstream):
  258. return {
  259. "tree": show_tree,
  260. "blob": show_blob,
  261. "commit": show_commit,
  262. "tag": show_tag,
  263. }[obj.type_name](repo, obj, outstream)
  264. def log(repo=".", outstream=sys.stdout, max_entries=None):
  265. """Write commit logs.
  266. :param repo: Path to repository
  267. :param outstream: Stream to write log output to
  268. :param max_entries: Optional maximum number of entries to display
  269. """
  270. r = open_repo(repo)
  271. walker = r.get_walker(max_entries=max_entries)
  272. for entry in walker:
  273. print_commit(entry.commit, outstream)
  274. def show(repo=".", objects=None, outstream=sys.stdout):
  275. """Print the changes in a commit.
  276. :param repo: Path to repository
  277. :param objects: Objects to show (defaults to [HEAD])
  278. :param outstream: Stream to write to
  279. """
  280. if objects is None:
  281. objects = ["HEAD"]
  282. if not isinstance(objects, list):
  283. objects = [objects]
  284. r = open_repo(repo)
  285. for objectish in objects:
  286. show_object(r, parse_object(r, objectish), outstream)
  287. def diff_tree(repo, old_tree, new_tree, outstream=sys.stdout):
  288. """Compares the content and mode of blobs found via two tree objects.
  289. :param repo: Path to repository
  290. :param old_tree: Id of old tree
  291. :param new_tree: Id of new tree
  292. :param outstream: Stream to write to
  293. """
  294. r = open_repo(repo)
  295. write_tree_diff(outstream, r.object_store, old_tree, new_tree)
  296. def rev_list(repo, commits, outstream=sys.stdout):
  297. """Lists commit objects in reverse chronological order.
  298. :param repo: Path to repository
  299. :param commits: Commits over which to iterate
  300. :param outstream: Stream to write to
  301. """
  302. r = open_repo(repo)
  303. for entry in r.get_walker(include=[r[c].id for c in commits]):
  304. outstream.write("%s\n" % entry.commit.id)
  305. def tag(repo, tag, author=None, message=None, annotated=False,
  306. objectish="HEAD", tag_time=None, tag_timezone=None):
  307. """Creates a tag in git via dulwich calls:
  308. :param repo: Path to repository
  309. :param tag: tag string
  310. :param author: tag author (optional, if annotated is set)
  311. :param message: tag message (optional)
  312. :param annotated: whether to create an annotated tag
  313. :param objectish: object the tag should point at, defaults to HEAD
  314. :param tag_time: Optional time for annotated tag
  315. :param tag_timezone: Optional timezone for annotated tag
  316. """
  317. r = open_repo(repo)
  318. object = parse_object(r, objectish)
  319. if annotated:
  320. # Create the tag object
  321. tag_obj = Tag()
  322. if author is None:
  323. # TODO(jelmer): Don't use repo private method.
  324. author = r._get_user_identity()
  325. tag_obj.tagger = author
  326. tag_obj.message = message
  327. tag_obj.name = tag
  328. tag_obj.object = (type(object), object.id)
  329. tag_obj.tag_time = tag_time
  330. if tag_time is None:
  331. tag_time = int(time.time())
  332. if tag_timezone is None:
  333. # TODO(jelmer) Use current user timezone rather than UTC
  334. tag_timezone = 0
  335. elif isinstance(tag_timezone, str):
  336. tag_timezone = parse_timezone(tag_timezone)
  337. tag_obj.tag_timezone = tag_timezone
  338. r.object_store.add_object(tag_obj)
  339. tag_id = tag_obj.id
  340. else:
  341. tag_id = object.id
  342. r.refs['refs/tags/' + tag] = tag_id
  343. def list_tags(repo, outstream=sys.stdout):
  344. """List all tags.
  345. :param repo: Path to repository
  346. :param outstream: Stream to write tags to
  347. """
  348. r = open_repo(repo)
  349. tags = list(r.refs.as_dict("refs/tags"))
  350. tags.sort()
  351. return tags
  352. def reset(repo, mode, committish="HEAD"):
  353. """Reset current HEAD to the specified state.
  354. :param repo: Path to repository
  355. :param mode: Mode ("hard", "soft", "mixed")
  356. """
  357. if mode != "hard":
  358. raise ValueError("hard is the only mode currently supported")
  359. r = open_repo(repo)
  360. indexfile = r.index_path()
  361. tree = r[committish].tree
  362. index.build_index_from_tree(r.path, indexfile, r.object_store, tree)
  363. def push(repo, remote_location, refs_path,
  364. outstream=sys.stdout, errstream=sys.stderr):
  365. """Remote push with dulwich via dulwich.client
  366. :param repo: Path to repository
  367. :param remote_location: Location of the remote
  368. :param refs_path: relative path to the refs to push to remote
  369. :param outstream: A stream file to write output
  370. :param errstream: A stream file to write errors
  371. """
  372. # Open the repo
  373. r = open_repo(repo)
  374. # Get the client and path
  375. client, path = get_transport_and_path(remote_location)
  376. def update_refs(refs):
  377. new_refs = r.get_refs()
  378. refs[refs_path] = new_refs['HEAD']
  379. del new_refs['HEAD']
  380. return refs
  381. try:
  382. client.send_pack(path, update_refs,
  383. r.object_store.generate_pack_contents, progress=errstream.write)
  384. outstream.write("Push to %s successful.\n" % remote_location)
  385. except (UpdateRefsError, SendPackError) as e:
  386. outstream.write("Push to %s failed.\n" % remote_location)
  387. errstream.write("Push to %s failed -> '%s'\n" % e.message)
  388. def pull(repo, remote_location, refs_path,
  389. outstream=sys.stdout, errstream=sys.stderr):
  390. """Pull from remote via dulwich.client
  391. :param repo: Path to repository
  392. :param remote_location: Location of the remote
  393. :param refs_path: relative path to the fetched refs
  394. :param outstream: A stream file to write to output
  395. :param errstream: A stream file to write to errors
  396. """
  397. # Open the repo
  398. r = open_repo(repo)
  399. client, path = get_transport_and_path(remote_location)
  400. remote_refs = client.fetch(path, r, progress=errstream.write)
  401. r['HEAD'] = remote_refs[refs_path]
  402. # Perform 'git checkout .' - syncs staged changes
  403. indexfile = r.index_path()
  404. tree = r["HEAD"].tree
  405. index.build_index_from_tree(r.path, indexfile, r.object_store, tree)
  406. def status(repo="."):
  407. """Returns staged, unstaged, and untracked changes relative to the HEAD.
  408. :param repo: Path to repository or repository object
  409. :return: GitStatus tuple,
  410. staged - list of staged paths (diff index/HEAD)
  411. unstaged - list of unstaged paths (diff index/working-tree)
  412. untracked - list of untracked, un-ignored & non-.git paths
  413. """
  414. r = open_repo(repo)
  415. # 1. Get status of staged
  416. tracked_changes = get_tree_changes(r)
  417. # 2. Get status of unstaged
  418. unstaged_changes = list(get_unstaged_changes(r.open_index(), r.path))
  419. # TODO - Status of untracked - add untracked changes, need gitignore.
  420. untracked_changes = []
  421. return GitStatus(tracked_changes, unstaged_changes, untracked_changes)
  422. def get_tree_changes(repo):
  423. """Return add/delete/modify changes to tree by comparing index to HEAD.
  424. :param repo: repo path or object
  425. :return: dict with lists for each type of change
  426. """
  427. r = open_repo(repo)
  428. index = r.open_index()
  429. # Compares the Index to the HEAD & determines changes
  430. # Iterate through the changes and report add/delete/modify
  431. # TODO: call out to dulwich.diff_tree somehow.
  432. tracked_changes = {
  433. 'add': [],
  434. 'delete': [],
  435. 'modify': [],
  436. }
  437. for change in index.changes_from_tree(r.object_store, r['HEAD'].tree):
  438. if not change[0][0]:
  439. tracked_changes['add'].append(change[0][1])
  440. elif not change[0][1]:
  441. tracked_changes['delete'].append(change[0][0])
  442. elif change[0][0] == change[0][1]:
  443. tracked_changes['modify'].append(change[0][0])
  444. else:
  445. raise AssertionError('git mv ops not yet supported')
  446. return tracked_changes
  447. def daemon(path=".", address=None, port=None):
  448. """Run a daemon serving Git requests over TCP/IP.
  449. :param path: Path to the directory to serve.
  450. """
  451. # TODO(jelmer): Support git-daemon-export-ok and --export-all.
  452. backend = FileSystemBackend(path)
  453. server = TCPGitServer(backend, address, port)
  454. server.serve_forever()
  455. def upload_pack(path=".", inf=sys.stdin, outf=sys.stdout):
  456. """Upload a pack file after negotiating its contents using smart protocol.
  457. :param path: Path to the repository
  458. :param inf: Input stream to communicate with client
  459. :param outf: Output stream to communicate with client
  460. """
  461. backend = FileSystemBackend()
  462. def send_fn(data):
  463. outf.write(data)
  464. outf.flush()
  465. proto = Protocol(inf.read, send_fn)
  466. handler = UploadPackHandler(backend, [path], proto)
  467. # FIXME: Catch exceptions and write a single-line summary to outf.
  468. handler.handle()
  469. return 0
  470. def receive_pack(path=".", inf=sys.stdin, outf=sys.stdout):
  471. """Receive a pack file after negotiating its contents using smart protocol.
  472. :param path: Path to the repository
  473. :param inf: Input stream to communicate with client
  474. :param outf: Output stream to communicate with client
  475. """
  476. backend = FileSystemBackend()
  477. def send_fn(data):
  478. outf.write(data)
  479. outf.flush()
  480. proto = Protocol(inf.read, send_fn)
  481. handler = ReceivePackHandler(backend, [path], proto)
  482. # FIXME: Catch exceptions and write a single-line summary to outf.
  483. handler.handle()
  484. return 0