dulwich 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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. opts, args = getopt(args, "", ["bare"])
  168. opts = dict(opts)
  169. if args == []:
  170. print("usage: dulwich clone host:path [PATH]")
  171. sys.exit(1)
  172. source = args.pop(0)
  173. if len(args) > 0:
  174. target = args.pop(0)
  175. else:
  176. target = None
  177. porcelain.clone(source, target, bare=("--bare" in opts))
  178. class cmd_commit(Command):
  179. def run(self, args):
  180. opts, args = getopt(args, "", ["message"])
  181. opts = dict(opts)
  182. porcelain.commit(".", message=opts["--message"])
  183. class cmd_commit_tree(Command):
  184. def run(self, args):
  185. opts, args = getopt(args, "", ["message"])
  186. if args == []:
  187. print("usage: dulwich commit-tree tree")
  188. sys.exit(1)
  189. opts = dict(opts)
  190. porcelain.commit_tree(".", tree=args[0], message=opts["--message"])
  191. class cmd_update_server_info(Command):
  192. def run(self, args):
  193. porcelain.update_server_info(".")
  194. class cmd_symbolic_ref(Command):
  195. def run(self, args):
  196. opts, args = getopt(args, "", ["ref-name", "force"])
  197. if not args:
  198. print("Usage: dulwich symbolic-ref REF_NAME [--force]")
  199. sys.exit(1)
  200. ref_name = args.pop(0)
  201. porcelain.symbolic_ref(".", ref_name=ref_name, force='--force' in args)
  202. class cmd_show(Command):
  203. def run(self, args):
  204. opts, args = getopt(args, "", [])
  205. porcelain.show(".", args)
  206. class cmd_diff_tree(Command):
  207. def run(self, args):
  208. opts, args = getopt(args, "", [])
  209. if len(args) < 2:
  210. print("Usage: dulwich diff-tree OLD-TREE NEW-TREE")
  211. sys.exit(1)
  212. porcelain.diff_tree(".", args[0], args[1])
  213. class cmd_rev_list(Command):
  214. def run(self, args):
  215. opts, args = getopt(args, "", [])
  216. if len(args) < 1:
  217. print('Usage: dulwich rev-list COMMITID...')
  218. sys.exit(1)
  219. porcelain.rev_list('.', args)
  220. class cmd_tag(Command):
  221. def run(self, args):
  222. opts, args = getopt(args, '', [])
  223. if len(args) < 2:
  224. print('Usage: dulwich tag NAME')
  225. sys.exit(1)
  226. porcelain.tag('.', args[0])
  227. class cmd_repack(Command):
  228. def run(self, args):
  229. opts, args = getopt(args, "", [])
  230. opts = dict(opts)
  231. porcelain.repack('.')
  232. class cmd_reset(Command):
  233. def run(self, args):
  234. opts, args = getopt(args, "", ["hard", "soft", "mixed"])
  235. opts = dict(opts)
  236. mode = ""
  237. if "--hard" in opts:
  238. mode = "hard"
  239. elif "--soft" in opts:
  240. mode = "soft"
  241. elif "--mixed" in opts:
  242. mode = "mixed"
  243. porcelain.reset('.', mode=mode, *args)
  244. class cmd_daemon(Command):
  245. def run(self, args):
  246. from dulwich import log_utils
  247. from dulwich.protocol import TCP_GIT_PORT
  248. parser = optparse.OptionParser()
  249. parser.add_option("-l", "--listen_address", dest="listen_address",
  250. default="localhost",
  251. help="Binding IP address.")
  252. parser.add_option("-p", "--port", dest="port", type=int,
  253. default=TCP_GIT_PORT,
  254. help="Binding TCP port.")
  255. options, args = parser.parse_args(args)
  256. log_utils.default_logging_config()
  257. if len(args) >= 1:
  258. gitdir = args[0]
  259. else:
  260. gitdir = '.'
  261. from dulwich import porcelain
  262. porcelain.daemon(gitdir, address=options.listen_address,
  263. port=options.port)
  264. class cmd_web_daemon(Command):
  265. def run(self, args):
  266. from dulwich import log_utils
  267. parser = optparse.OptionParser()
  268. parser.add_option("-l", "--listen_address", dest="listen_address",
  269. default="",
  270. help="Binding IP address.")
  271. parser.add_option("-p", "--port", dest="port", type=int,
  272. default=8000,
  273. help="Binding TCP port.")
  274. options, args = parser.parse_args(args)
  275. log_utils.default_logging_config()
  276. if len(args) >= 1:
  277. gitdir = args[0]
  278. else:
  279. gitdir = '.'
  280. from dulwich import porcelain
  281. porcelain.web_daemon(gitdir, address=options.listen_address,
  282. port=options.port)
  283. class cmd_receive_pack(Command):
  284. def run(self, args):
  285. parser = optparse.OptionParser()
  286. options, args = parser.parse_args(args)
  287. if len(args) >= 1:
  288. gitdir = args[0]
  289. else:
  290. gitdir = '.'
  291. porcelain.receive_pack(gitdir)
  292. class cmd_upload_pack(Command):
  293. def run(self, args):
  294. parser = optparse.OptionParser()
  295. options, args = parser.parse_args(args)
  296. if len(args) >= 1:
  297. gitdir = args[0]
  298. else:
  299. gitdir = '.'
  300. porcelain.upload_pack(gitdir)
  301. class cmd_status(Command):
  302. def run(self, args):
  303. parser = optparse.OptionParser()
  304. options, args = parser.parse_args(args)
  305. if len(args) >= 1:
  306. gitdir = args[0]
  307. else:
  308. gitdir = '.'
  309. status = porcelain.status(gitdir)
  310. if any(names for (kind, names) in status.staged.items()):
  311. sys.stdout.write("Changes to be committed:\n\n")
  312. for kind, names in status.staged.items():
  313. for name in names:
  314. sys.stdout.write("\t%s: %s\n" % (
  315. kind, name.decode(sys.getfilesystemencoding())))
  316. sys.stdout.write("\n")
  317. if status.unstaged:
  318. sys.stdout.write("Changes not staged for commit:\n\n")
  319. for name in status.unstaged:
  320. sys.stdout.write("\t%s\n" %
  321. name.decode(sys.getfilesystemencoding()))
  322. sys.stdout.write("\n")
  323. if status.untracked:
  324. sys.stdout.write("Untracked files:\n\n")
  325. for name in status.untracked:
  326. sys.stdout.write("\t%s\n" % name)
  327. sys.stdout.write("\n")
  328. class cmd_ls_remote(Command):
  329. def run(self, args):
  330. opts, args = getopt(args, '', [])
  331. if len(args) < 1:
  332. print('Usage: dulwich ls-remote URL')
  333. sys.exit(1)
  334. refs = porcelain.ls_remote(args[0])
  335. for ref in sorted(refs):
  336. sys.stdout.write("%s\t%s\n" % (ref, refs[ref]))
  337. class cmd_ls_tree(Command):
  338. def run(self, args):
  339. parser = optparse.OptionParser()
  340. parser.add_option("-r", "--recursive", action="store_true",
  341. help="Recusively list tree contents.")
  342. parser.add_option("--name-only", action="store_true",
  343. help="Only display name.")
  344. options, args = parser.parse_args(args)
  345. try:
  346. treeish = args.pop(0)
  347. except IndexError:
  348. treeish = None
  349. porcelain.ls_tree(
  350. '.', treeish, outstream=sys.stdout, recursive=options.recursive,
  351. name_only=options.name_only)
  352. class cmd_pack_objects(Command):
  353. def run(self, args):
  354. opts, args = getopt(args, '', ['stdout'])
  355. opts = dict(opts)
  356. if len(args) < 1 and not '--stdout' in args:
  357. print('Usage: dulwich pack-objects basename')
  358. sys.exit(1)
  359. object_ids = [l.strip() for l in sys.stdin.readlines()]
  360. basename = args[0]
  361. if '--stdout' in opts:
  362. packf = getattr(sys.stdout, 'buffer', sys.stdout)
  363. idxf = None
  364. close = []
  365. else:
  366. packf = open(basename + '.pack', 'w')
  367. idxf = open(basename + '.idx', 'w')
  368. close = [packf, idxf]
  369. porcelain.pack_objects('.', object_ids, packf, idxf)
  370. for f in close:
  371. f.close()
  372. class cmd_pull(Command):
  373. def run(self, args):
  374. parser = optparse.OptionParser()
  375. options, args = parser.parse_args(args)
  376. try:
  377. from_location = args[0]
  378. except IndexError:
  379. from_location = None
  380. porcelain.pull('.', from_location)
  381. class cmd_push(Command):
  382. def run(self, args):
  383. parser = optparse.OptionParser()
  384. options, args = parser.parse_args(args)
  385. if len(args) < 2:
  386. print("Usage: dulwich push TO-LOCATION REFSPEC..")
  387. sys.exit(1)
  388. to_location = args[0]
  389. refspecs = args[1:]
  390. porcelain.push('.', to_location, refspecs)
  391. class cmd_remote_add(Command):
  392. def run(self, args):
  393. parser = optparse.OptionParser()
  394. options, args = parser.parse_args(args)
  395. porcelain.remote_add('.', args[0], args[1])
  396. class SuperCommand(Command):
  397. subcommands = {}
  398. def run(self, args):
  399. if not args:
  400. print("Supported subcommands: %s" % ', '.join(self.subcommands.keys()))
  401. return False
  402. cmd = args[0]
  403. try:
  404. cmd_kls = self.subcommands[cmd]
  405. except KeyError:
  406. print('No such subcommand: %s' % args[0])
  407. return False
  408. return cmd_kls().run(args[1:])
  409. class cmd_remote(SuperCommand):
  410. subcommands = {
  411. "add": cmd_remote_add,
  412. }
  413. class cmd_check_ignore(Command):
  414. def run(self, args):
  415. parser = optparse.OptionParser()
  416. options, args = parser.parse_args(args)
  417. ret = 1
  418. for path in porcelain.check_ignore('.', args):
  419. print(path)
  420. ret = 0
  421. return ret
  422. class cmd_check_mailmap(Command):
  423. def run(self, args):
  424. parser = optparse.OptionParser()
  425. options, args = parser.parse_args(args)
  426. for arg in args:
  427. canonical_identity = porcelain.check_mailmap('.', arg)
  428. print(canonical_identity)
  429. class cmd_stash_list(Command):
  430. def run(self, args):
  431. parser = optparse.OptionParser()
  432. options, args = parser.parse_args(args)
  433. for i, entry in porcelain.stash_list('.'):
  434. print("stash@{%d}: %s" % (i, entry.message.rstrip('\n')))
  435. class cmd_stash_push(Command):
  436. def run(self, args):
  437. parser = optparse.OptionParser()
  438. options, args = parser.parse_args(args)
  439. porcelain.stash_push('.')
  440. print("Saved working directory and index state")
  441. class cmd_stash_pop(Command):
  442. def run(self, args):
  443. parser = optparse.OptionParser()
  444. options, args = parser.parse_args(args)
  445. porcelain.stash_pop('.')
  446. print("Restrored working directory and index state")
  447. class cmd_stash(SuperCommand):
  448. subcommands = {
  449. "list": cmd_stash_list,
  450. "pop": cmd_stash_pop,
  451. "push": cmd_stash_push,
  452. }
  453. class cmd_ls_files(Command):
  454. def run(self, args):
  455. parser = optparse.OptionParser()
  456. options, args = parser.parse_args(args)
  457. for name in porcelain.ls_files('.'):
  458. print(name)
  459. class cmd_describe(Command):
  460. def run(self, args):
  461. parser = optparse.OptionParser()
  462. options, args = parser.parse_args(args)
  463. print(porcelain.describe('.'))
  464. class cmd_help(Command):
  465. def run(self, args):
  466. parser = optparse.OptionParser()
  467. parser.add_option("-a", "--all", dest="all",
  468. action="store_true",
  469. help="List all commands.")
  470. options, args = parser.parse_args(args)
  471. if options.all:
  472. print('Available commands:')
  473. for cmd in sorted(commands):
  474. print(' %s' % cmd)
  475. else:
  476. print("""\
  477. The dulwich command line tool is currently a very basic frontend for the
  478. Dulwich python module. For full functionality, please see the API reference.
  479. For a list of supported commands, see 'dulwich help -a'.
  480. """)
  481. commands = {
  482. "add": cmd_add,
  483. "archive": cmd_archive,
  484. "check-ignore": cmd_check_ignore,
  485. "check-mailmap": cmd_check_mailmap,
  486. "clone": cmd_clone,
  487. "commit": cmd_commit,
  488. "commit-tree": cmd_commit_tree,
  489. "describe": cmd_describe,
  490. "daemon": cmd_daemon,
  491. "diff": cmd_diff,
  492. "diff-tree": cmd_diff_tree,
  493. "dump-pack": cmd_dump_pack,
  494. "dump-index": cmd_dump_index,
  495. "fetch-pack": cmd_fetch_pack,
  496. "fetch": cmd_fetch,
  497. "fsck": cmd_fsck,
  498. "help": cmd_help,
  499. "init": cmd_init,
  500. "log": cmd_log,
  501. "ls-files": cmd_ls_files,
  502. "ls-remote": cmd_ls_remote,
  503. "ls-tree": cmd_ls_tree,
  504. "pack-objects": cmd_pack_objects,
  505. "pull": cmd_pull,
  506. "push": cmd_push,
  507. "receive-pack": cmd_receive_pack,
  508. "remote": cmd_remote,
  509. "repack": cmd_repack,
  510. "reset": cmd_reset,
  511. "rev-list": cmd_rev_list,
  512. "rm": cmd_rm,
  513. "show": cmd_show,
  514. "stash": cmd_stash,
  515. "status": cmd_status,
  516. "symbolic-ref": cmd_symbolic_ref,
  517. "tag": cmd_tag,
  518. "update-server-info": cmd_update_server_info,
  519. "upload-pack": cmd_upload_pack,
  520. "web-daemon": cmd_web_daemon,
  521. }
  522. if len(sys.argv) < 2:
  523. print("Usage: %s <%s> [OPTIONS...]" % (sys.argv[0], "|".join(commands.keys())))
  524. sys.exit(1)
  525. cmd = sys.argv[1]
  526. try:
  527. cmd_kls = commands[cmd]
  528. except KeyError:
  529. print("No such subcommand: %s" % cmd)
  530. sys.exit(1)
  531. # TODO(jelmer): Return non-0 on errors
  532. cmd_kls().run(sys.argv[2:])