2
0

dulwich 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. #!/usr/bin/python -u
  2. #
  3. # dulwich - Simple command-line interface to Dulwich
  4. # Copyright (C) 2008-2011 Jelmer Vernooij <jelmer@jelmer.uk>
  5. # vim: expandtab
  6. #
  7. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  8. # General Public License as public by the Free Software Foundation; version 2.0
  9. # or (at your option) any later version. You can redistribute it and/or
  10. # modify it under the terms of either of these two licenses.
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. #
  18. # You should have received a copy of the licenses; if not, see
  19. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  20. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  21. # License, Version 2.0.
  22. #
  23. """Simple command-line interface to Dulwich>
  24. This is a very simple command-line wrapper for Dulwich. It is by
  25. no means intended to be a full-blown Git command-line interface but just
  26. a way to test Dulwich.
  27. """
  28. import os
  29. import sys
  30. from getopt import getopt
  31. import optparse
  32. import signal
  33. def signal_int(signal, frame):
  34. sys.exit(1)
  35. def signal_quit(signal, frame):
  36. import pdb
  37. pdb.set_trace()
  38. if 'DULWICH_PDB' in os.environ:
  39. signal.signal(signal.SIGQUIT, signal_quit)
  40. signal.signal(signal.SIGINT, signal_int)
  41. from dulwich import porcelain
  42. from dulwich.client import get_transport_and_path
  43. from dulwich.errors import ApplyDeltaError
  44. from dulwich.index import Index
  45. from dulwich.pack import Pack, sha_to_hex
  46. from dulwich.patch import write_tree_diff
  47. from dulwich.repo import Repo
  48. class Command(object):
  49. """A Dulwich subcommand."""
  50. def run(self, args):
  51. """Run the command."""
  52. raise NotImplementedError(self.run)
  53. class cmd_archive(Command):
  54. def run(self, args):
  55. parser = optparse.OptionParser()
  56. parser.add_option("--remote", type=str,
  57. help="Retrieve archive from specified remote repo")
  58. options, args = parser.parse_args(args)
  59. committish = args.pop(0)
  60. if options.remote:
  61. client, path = get_transport_and_path(options.remote)
  62. client.archive(path, committish, sys.stdout.write,
  63. write_error=sys.stderr.write)
  64. else:
  65. porcelain.archive('.', committish, outstream=sys.stdout,
  66. errstream=sys.stderr)
  67. class cmd_add(Command):
  68. def run(self, args):
  69. opts, args = getopt(args, "", [])
  70. porcelain.add(".", paths=args)
  71. class cmd_rm(Command):
  72. def run(self, args):
  73. opts, args = getopt(args, "", [])
  74. porcelain.rm(".", paths=args)
  75. class cmd_fetch_pack(Command):
  76. def run(self, args):
  77. opts, args = getopt(args, "", ["all"])
  78. opts = dict(opts)
  79. client, path = get_transport_and_path(args.pop(0))
  80. r = Repo(".")
  81. if "--all" in opts:
  82. determine_wants = r.object_store.determine_wants_all
  83. else:
  84. determine_wants = lambda x: [y for y in args if not y in r.object_store]
  85. client.fetch(path, r, determine_wants)
  86. class cmd_fetch(Command):
  87. def run(self, args):
  88. opts, args = getopt(args, "", [])
  89. opts = dict(opts)
  90. client, path = get_transport_and_path(args.pop(0))
  91. r = Repo(".")
  92. if "--all" in opts:
  93. determine_wants = r.object_store.determine_wants_all
  94. refs = client.fetch(path, r, progress=sys.stdout.write)
  95. print("Remote refs:")
  96. for item in refs.items():
  97. print("%s -> %s" % item)
  98. class cmd_fsck(Command):
  99. def run(self, args):
  100. opts, args = getopt(args, "", [])
  101. opts = dict(opts)
  102. for (obj, msg) in porcelain.fsck('.'):
  103. print("%s: %s" % (obj, msg))
  104. class cmd_log(Command):
  105. def run(self, args):
  106. parser = optparse.OptionParser()
  107. parser.add_option("--reverse", dest="reverse", action="store_true",
  108. help="Reverse order in which entries are printed")
  109. parser.add_option("--name-status", dest="name_status", action="store_true",
  110. help="Print name/status for each changed file")
  111. options, args = parser.parse_args(args)
  112. porcelain.log(".", paths=args, reverse=options.reverse,
  113. name_status=options.name_status,
  114. outstream=sys.stdout)
  115. class cmd_diff(Command):
  116. def run(self, args):
  117. opts, args = getopt(args, "", [])
  118. if args == []:
  119. print("Usage: dulwich diff COMMITID")
  120. sys.exit(1)
  121. r = Repo(".")
  122. commit_id = args[0]
  123. commit = r[commit_id]
  124. parent_commit = r[commit.parents[0]]
  125. write_tree_diff(sys.stdout, r.object_store, parent_commit.tree, commit.tree)
  126. class cmd_dump_pack(Command):
  127. def run(self, args):
  128. opts, args = getopt(args, "", [])
  129. if args == []:
  130. print("Usage: dulwich dump-pack FILENAME")
  131. sys.exit(1)
  132. basename, _ = os.path.splitext(args[0])
  133. x = Pack(basename)
  134. print("Object names checksum: %s" % x.name())
  135. print("Checksum: %s" % sha_to_hex(x.get_stored_checksum()))
  136. if not x.check():
  137. print("CHECKSUM DOES NOT MATCH")
  138. print("Length: %d" % len(x))
  139. for name in x:
  140. try:
  141. print("\t%s" % x[name])
  142. except KeyError as k:
  143. print("\t%s: Unable to resolve base %s" % (name, k))
  144. except ApplyDeltaError as e:
  145. print("\t%s: Unable to apply delta: %r" % (name, e))
  146. class cmd_dump_index(Command):
  147. def run(self, args):
  148. opts, args = getopt(args, "", [])
  149. if args == []:
  150. print("Usage: dulwich dump-index FILENAME")
  151. sys.exit(1)
  152. filename = args[0]
  153. idx = Index(filename)
  154. for o in idx:
  155. print(o, idx[o])
  156. class cmd_init(Command):
  157. def run(self, args):
  158. opts, args = getopt(args, "", ["bare"])
  159. opts = dict(opts)
  160. if args == []:
  161. path = os.getcwd()
  162. else:
  163. path = args[0]
  164. porcelain.init(path, bare=("--bare" in opts))
  165. class cmd_clone(Command):
  166. def run(self, args):
  167. parser = optparse.OptionParser()
  168. parser.add_option("--bare", dest="bare",
  169. help="Whether to create a bare repository.",
  170. action="store_true")
  171. parser.add_option("--depth", dest="depth",
  172. type=int, help="Depth at which to fetch")
  173. options, args = parser.parse_args(args)
  174. if args == []:
  175. print("usage: dulwich clone host:path [PATH]")
  176. sys.exit(1)
  177. source = args.pop(0)
  178. if len(args) > 0:
  179. target = args.pop(0)
  180. else:
  181. target = None
  182. porcelain.clone(source, target, bare=options.bare, depth=options.depth)
  183. class cmd_commit(Command):
  184. def run(self, args):
  185. opts, args = getopt(args, "", ["message"])
  186. opts = dict(opts)
  187. porcelain.commit(".", message=opts["--message"])
  188. class cmd_commit_tree(Command):
  189. def run(self, args):
  190. opts, args = getopt(args, "", ["message"])
  191. if args == []:
  192. print("usage: dulwich commit-tree tree")
  193. sys.exit(1)
  194. opts = dict(opts)
  195. porcelain.commit_tree(".", tree=args[0], message=opts["--message"])
  196. class cmd_update_server_info(Command):
  197. def run(self, args):
  198. porcelain.update_server_info(".")
  199. class cmd_symbolic_ref(Command):
  200. def run(self, args):
  201. opts, args = getopt(args, "", ["ref-name", "force"])
  202. if not args:
  203. print("Usage: dulwich symbolic-ref REF_NAME [--force]")
  204. sys.exit(1)
  205. ref_name = args.pop(0)
  206. porcelain.symbolic_ref(".", ref_name=ref_name, force='--force' in args)
  207. class cmd_show(Command):
  208. def run(self, args):
  209. opts, args = getopt(args, "", [])
  210. porcelain.show(".", args)
  211. class cmd_diff_tree(Command):
  212. def run(self, args):
  213. opts, args = getopt(args, "", [])
  214. if len(args) < 2:
  215. print("Usage: dulwich diff-tree OLD-TREE NEW-TREE")
  216. sys.exit(1)
  217. porcelain.diff_tree(".", args[0], args[1])
  218. class cmd_rev_list(Command):
  219. def run(self, args):
  220. opts, args = getopt(args, "", [])
  221. if len(args) < 1:
  222. print('Usage: dulwich rev-list COMMITID...')
  223. sys.exit(1)
  224. porcelain.rev_list('.', args)
  225. class cmd_tag(Command):
  226. def run(self, args):
  227. opts, args = getopt(args, '', [])
  228. if len(args) < 2:
  229. print('Usage: dulwich tag NAME')
  230. sys.exit(1)
  231. porcelain.tag('.', args[0])
  232. class cmd_repack(Command):
  233. def run(self, args):
  234. opts, args = getopt(args, "", [])
  235. opts = dict(opts)
  236. porcelain.repack('.')
  237. class cmd_reset(Command):
  238. def run(self, args):
  239. opts, args = getopt(args, "", ["hard", "soft", "mixed"])
  240. opts = dict(opts)
  241. mode = ""
  242. if "--hard" in opts:
  243. mode = "hard"
  244. elif "--soft" in opts:
  245. mode = "soft"
  246. elif "--mixed" in opts:
  247. mode = "mixed"
  248. porcelain.reset('.', mode=mode, *args)
  249. class cmd_daemon(Command):
  250. def run(self, args):
  251. from dulwich import log_utils
  252. from dulwich.protocol import TCP_GIT_PORT
  253. parser = optparse.OptionParser()
  254. parser.add_option("-l", "--listen_address", dest="listen_address",
  255. default="localhost",
  256. help="Binding IP address.")
  257. parser.add_option("-p", "--port", dest="port", type=int,
  258. default=TCP_GIT_PORT,
  259. help="Binding TCP port.")
  260. options, args = parser.parse_args(args)
  261. log_utils.default_logging_config()
  262. if len(args) >= 1:
  263. gitdir = args[0]
  264. else:
  265. gitdir = '.'
  266. from dulwich import porcelain
  267. porcelain.daemon(gitdir, address=options.listen_address,
  268. port=options.port)
  269. class cmd_web_daemon(Command):
  270. def run(self, args):
  271. from dulwich import log_utils
  272. parser = optparse.OptionParser()
  273. parser.add_option("-l", "--listen_address", dest="listen_address",
  274. default="",
  275. help="Binding IP address.")
  276. parser.add_option("-p", "--port", dest="port", type=int,
  277. default=8000,
  278. help="Binding TCP port.")
  279. options, args = parser.parse_args(args)
  280. log_utils.default_logging_config()
  281. if len(args) >= 1:
  282. gitdir = args[0]
  283. else:
  284. gitdir = '.'
  285. from dulwich import porcelain
  286. porcelain.web_daemon(gitdir, address=options.listen_address,
  287. port=options.port)
  288. class cmd_receive_pack(Command):
  289. def run(self, args):
  290. parser = optparse.OptionParser()
  291. options, args = parser.parse_args(args)
  292. if len(args) >= 1:
  293. gitdir = args[0]
  294. else:
  295. gitdir = '.'
  296. porcelain.receive_pack(gitdir)
  297. class cmd_upload_pack(Command):
  298. def run(self, args):
  299. parser = optparse.OptionParser()
  300. options, args = parser.parse_args(args)
  301. if len(args) >= 1:
  302. gitdir = args[0]
  303. else:
  304. gitdir = '.'
  305. porcelain.upload_pack(gitdir)
  306. class cmd_status(Command):
  307. def run(self, args):
  308. parser = optparse.OptionParser()
  309. options, args = parser.parse_args(args)
  310. if len(args) >= 1:
  311. gitdir = args[0]
  312. else:
  313. gitdir = '.'
  314. status = porcelain.status(gitdir)
  315. if any(names for (kind, names) in status.staged.items()):
  316. sys.stdout.write("Changes to be committed:\n\n")
  317. for kind, names in status.staged.items():
  318. for name in names:
  319. sys.stdout.write("\t%s: %s\n" % (
  320. kind, name.decode(sys.getfilesystemencoding())))
  321. sys.stdout.write("\n")
  322. if status.unstaged:
  323. sys.stdout.write("Changes not staged for commit:\n\n")
  324. for name in status.unstaged:
  325. sys.stdout.write("\t%s\n" %
  326. name.decode(sys.getfilesystemencoding()))
  327. sys.stdout.write("\n")
  328. if status.untracked:
  329. sys.stdout.write("Untracked files:\n\n")
  330. for name in status.untracked:
  331. sys.stdout.write("\t%s\n" % name)
  332. sys.stdout.write("\n")
  333. class cmd_ls_remote(Command):
  334. def run(self, args):
  335. opts, args = getopt(args, '', [])
  336. if len(args) < 1:
  337. print('Usage: dulwich ls-remote URL')
  338. sys.exit(1)
  339. refs = porcelain.ls_remote(args[0])
  340. for ref in sorted(refs):
  341. sys.stdout.write("%s\t%s\n" % (ref, refs[ref]))
  342. class cmd_ls_tree(Command):
  343. def run(self, args):
  344. parser = optparse.OptionParser()
  345. parser.add_option("-r", "--recursive", action="store_true",
  346. help="Recusively list tree contents.")
  347. parser.add_option("--name-only", action="store_true",
  348. help="Only display name.")
  349. options, args = parser.parse_args(args)
  350. try:
  351. treeish = args.pop(0)
  352. except IndexError:
  353. treeish = None
  354. porcelain.ls_tree(
  355. '.', treeish, outstream=sys.stdout, recursive=options.recursive,
  356. name_only=options.name_only)
  357. class cmd_pack_objects(Command):
  358. def run(self, args):
  359. opts, args = getopt(args, '', ['stdout'])
  360. opts = dict(opts)
  361. if len(args) < 1 and not '--stdout' in args:
  362. print('Usage: dulwich pack-objects basename')
  363. sys.exit(1)
  364. object_ids = [l.strip() for l in sys.stdin.readlines()]
  365. basename = args[0]
  366. if '--stdout' in opts:
  367. packf = getattr(sys.stdout, 'buffer', sys.stdout)
  368. idxf = None
  369. close = []
  370. else:
  371. packf = open(basename + '.pack', 'w')
  372. idxf = open(basename + '.idx', 'w')
  373. close = [packf, idxf]
  374. porcelain.pack_objects('.', object_ids, packf, idxf)
  375. for f in close:
  376. f.close()
  377. class cmd_pull(Command):
  378. def run(self, args):
  379. parser = optparse.OptionParser()
  380. options, args = parser.parse_args(args)
  381. try:
  382. from_location = args[0]
  383. except IndexError:
  384. from_location = None
  385. porcelain.pull('.', from_location)
  386. class cmd_push(Command):
  387. def run(self, args):
  388. parser = optparse.OptionParser()
  389. options, args = parser.parse_args(args)
  390. if len(args) < 2:
  391. print("Usage: dulwich push TO-LOCATION REFSPEC..")
  392. sys.exit(1)
  393. to_location = args[0]
  394. refspecs = args[1:]
  395. porcelain.push('.', to_location, refspecs)
  396. class cmd_remote_add(Command):
  397. def run(self, args):
  398. parser = optparse.OptionParser()
  399. options, args = parser.parse_args(args)
  400. porcelain.remote_add('.', args[0], args[1])
  401. class SuperCommand(Command):
  402. subcommands = {}
  403. def run(self, args):
  404. if not args:
  405. print("Supported subcommands: %s" % ', '.join(self.subcommands.keys()))
  406. return False
  407. cmd = args[0]
  408. try:
  409. cmd_kls = self.subcommands[cmd]
  410. except KeyError:
  411. print('No such subcommand: %s' % args[0])
  412. return False
  413. return cmd_kls().run(args[1:])
  414. class cmd_remote(SuperCommand):
  415. subcommands = {
  416. "add": cmd_remote_add,
  417. }
  418. class cmd_check_ignore(Command):
  419. def run(self, args):
  420. parser = optparse.OptionParser()
  421. options, args = parser.parse_args(args)
  422. ret = 1
  423. for path in porcelain.check_ignore('.', args):
  424. print(path)
  425. ret = 0
  426. return ret
  427. class cmd_check_mailmap(Command):
  428. def run(self, args):
  429. parser = optparse.OptionParser()
  430. options, args = parser.parse_args(args)
  431. for arg in args:
  432. canonical_identity = porcelain.check_mailmap('.', arg)
  433. print(canonical_identity)
  434. class cmd_stash_list(Command):
  435. def run(self, args):
  436. parser = optparse.OptionParser()
  437. options, args = parser.parse_args(args)
  438. for i, entry in porcelain.stash_list('.'):
  439. print("stash@{%d}: %s" % (i, entry.message.rstrip('\n')))
  440. class cmd_stash_push(Command):
  441. def run(self, args):
  442. parser = optparse.OptionParser()
  443. options, args = parser.parse_args(args)
  444. porcelain.stash_push('.')
  445. print("Saved working directory and index state")
  446. class cmd_stash_pop(Command):
  447. def run(self, args):
  448. parser = optparse.OptionParser()
  449. options, args = parser.parse_args(args)
  450. porcelain.stash_pop('.')
  451. print("Restrored working directory and index state")
  452. class cmd_stash(SuperCommand):
  453. subcommands = {
  454. "list": cmd_stash_list,
  455. "pop": cmd_stash_pop,
  456. "push": cmd_stash_push,
  457. }
  458. class cmd_ls_files(Command):
  459. def run(self, args):
  460. parser = optparse.OptionParser()
  461. options, args = parser.parse_args(args)
  462. for name in porcelain.ls_files('.'):
  463. print(name)
  464. class cmd_describe(Command):
  465. def run(self, args):
  466. parser = optparse.OptionParser()
  467. options, args = parser.parse_args(args)
  468. print(porcelain.describe('.'))
  469. class cmd_help(Command):
  470. def run(self, args):
  471. parser = optparse.OptionParser()
  472. parser.add_option("-a", "--all", dest="all",
  473. action="store_true",
  474. help="List all commands.")
  475. options, args = parser.parse_args(args)
  476. if options.all:
  477. print('Available commands:')
  478. for cmd in sorted(commands):
  479. print(' %s' % cmd)
  480. else:
  481. print("""\
  482. The dulwich command line tool is currently a very basic frontend for the
  483. Dulwich python module. For full functionality, please see the API reference.
  484. For a list of supported commands, see 'dulwich help -a'.
  485. """)
  486. commands = {
  487. "add": cmd_add,
  488. "archive": cmd_archive,
  489. "check-ignore": cmd_check_ignore,
  490. "check-mailmap": cmd_check_mailmap,
  491. "clone": cmd_clone,
  492. "commit": cmd_commit,
  493. "commit-tree": cmd_commit_tree,
  494. "describe": cmd_describe,
  495. "daemon": cmd_daemon,
  496. "diff": cmd_diff,
  497. "diff-tree": cmd_diff_tree,
  498. "dump-pack": cmd_dump_pack,
  499. "dump-index": cmd_dump_index,
  500. "fetch-pack": cmd_fetch_pack,
  501. "fetch": cmd_fetch,
  502. "fsck": cmd_fsck,
  503. "help": cmd_help,
  504. "init": cmd_init,
  505. "log": cmd_log,
  506. "ls-files": cmd_ls_files,
  507. "ls-remote": cmd_ls_remote,
  508. "ls-tree": cmd_ls_tree,
  509. "pack-objects": cmd_pack_objects,
  510. "pull": cmd_pull,
  511. "push": cmd_push,
  512. "receive-pack": cmd_receive_pack,
  513. "remote": cmd_remote,
  514. "repack": cmd_repack,
  515. "reset": cmd_reset,
  516. "rev-list": cmd_rev_list,
  517. "rm": cmd_rm,
  518. "show": cmd_show,
  519. "stash": cmd_stash,
  520. "status": cmd_status,
  521. "symbolic-ref": cmd_symbolic_ref,
  522. "tag": cmd_tag,
  523. "update-server-info": cmd_update_server_info,
  524. "upload-pack": cmd_upload_pack,
  525. "web-daemon": cmd_web_daemon,
  526. }
  527. if len(sys.argv) < 2:
  528. print("Usage: %s <%s> [OPTIONS...]" % (sys.argv[0], "|".join(commands.keys())))
  529. sys.exit(1)
  530. cmd = sys.argv[1]
  531. try:
  532. cmd_kls = commands[cmd]
  533. except KeyError:
  534. print("No such subcommand: %s" % cmd)
  535. sys.exit(1)
  536. # TODO(jelmer): Return non-0 on errors
  537. cmd_kls().run(sys.argv[2:])