dulwich 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. #!/usr/bin/python -u
  2. #
  3. # dulwich - Simple command-line interface to Dulwich
  4. # Copyright (C) 2008-2011 Jelmer Vernooij <jelmer@samba.org>
  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. opts, args = getopt(args, "", [])
  56. client, path = get_transport_and_path(args.pop(0))
  57. location = args.pop(0)
  58. committish = args.pop(0)
  59. porcelain.archive(location, committish, outstream=sys.stdout,
  60. errstream=sys.stderr)
  61. class cmd_add(Command):
  62. def run(self, args):
  63. opts, args = getopt(args, "", [])
  64. porcelain.add(".", paths=args)
  65. class cmd_rm(Command):
  66. def run(self, args):
  67. opts, args = getopt(args, "", [])
  68. porcelain.rm(".", paths=args)
  69. class cmd_fetch_pack(Command):
  70. def run(self, args):
  71. opts, args = getopt(args, "", ["all"])
  72. opts = dict(opts)
  73. client, path = get_transport_and_path(args.pop(0))
  74. r = Repo(".")
  75. if "--all" in opts:
  76. determine_wants = r.object_store.determine_wants_all
  77. else:
  78. determine_wants = lambda x: [y for y in args if not y in r.object_store]
  79. client.fetch(path, r, determine_wants)
  80. class cmd_fetch(Command):
  81. def run(self, args):
  82. opts, args = getopt(args, "", [])
  83. opts = dict(opts)
  84. client, path = get_transport_and_path(args.pop(0))
  85. r = Repo(".")
  86. if "--all" in opts:
  87. determine_wants = r.object_store.determine_wants_all
  88. refs = client.fetch(path, r, progress=sys.stdout.write)
  89. print("Remote refs:")
  90. for item in refs.items():
  91. print("%s -> %s" % item)
  92. class cmd_fsck(Command):
  93. def run(self, args):
  94. opts, args = getopt(args, "", [])
  95. opts = dict(opts)
  96. for (obj, msg) in porcelain.fsck('.'):
  97. print("%s: %s" % (obj, msg))
  98. class cmd_log(Command):
  99. def run(self, args):
  100. parser = optparse.OptionParser()
  101. parser.add_option("--reverse", dest="reverse", action="store_true",
  102. help="Reverse order in which entries are printed")
  103. parser.add_option("--name-status", dest="name_status", action="store_true",
  104. help="Print name/status for each changed file")
  105. options, args = parser.parse_args(args)
  106. porcelain.log(".", paths=args, reverse=options.reverse,
  107. name_status=options.name_status,
  108. outstream=sys.stdout)
  109. class cmd_diff(Command):
  110. def run(self, args):
  111. opts, args = getopt(args, "", [])
  112. if args == []:
  113. print("Usage: dulwich diff COMMITID")
  114. sys.exit(1)
  115. r = Repo(".")
  116. commit_id = args[0]
  117. commit = r[commit_id]
  118. parent_commit = r[commit.parents[0]]
  119. write_tree_diff(sys.stdout, r.object_store, parent_commit.tree, commit.tree)
  120. class cmd_dump_pack(Command):
  121. def run(self, args):
  122. opts, args = getopt(args, "", [])
  123. if args == []:
  124. print("Usage: dulwich dump-pack FILENAME")
  125. sys.exit(1)
  126. basename, _ = os.path.splitext(args[0])
  127. x = Pack(basename)
  128. print("Object names checksum: %s" % x.name())
  129. print("Checksum: %s" % sha_to_hex(x.get_stored_checksum()))
  130. if not x.check():
  131. print("CHECKSUM DOES NOT MATCH")
  132. print("Length: %d" % len(x))
  133. for name in x:
  134. try:
  135. print("\t%s" % x[name])
  136. except KeyError as k:
  137. print("\t%s: Unable to resolve base %s" % (name, k))
  138. except ApplyDeltaError as e:
  139. print("\t%s: Unable to apply delta: %r" % (name, e))
  140. class cmd_dump_index(Command):
  141. def run(self, args):
  142. opts, args = getopt(args, "", [])
  143. if args == []:
  144. print("Usage: dulwich dump-index FILENAME")
  145. sys.exit(1)
  146. filename = args[0]
  147. idx = Index(filename)
  148. for o in idx:
  149. print(o, idx[o])
  150. class cmd_init(Command):
  151. def run(self, args):
  152. opts, args = getopt(args, "", ["bare"])
  153. opts = dict(opts)
  154. if args == []:
  155. path = os.getcwd()
  156. else:
  157. path = args[0]
  158. porcelain.init(path, bare=("--bare" in opts))
  159. class cmd_clone(Command):
  160. def run(self, args):
  161. opts, args = getopt(args, "", ["bare"])
  162. opts = dict(opts)
  163. if args == []:
  164. print("usage: dulwich clone host:path [PATH]")
  165. sys.exit(1)
  166. source = args.pop(0)
  167. if len(args) > 0:
  168. target = args.pop(0)
  169. else:
  170. target = None
  171. porcelain.clone(source, target, bare=("--bare" in opts))
  172. class cmd_commit(Command):
  173. def run(self, args):
  174. opts, args = getopt(args, "", ["message"])
  175. opts = dict(opts)
  176. porcelain.commit(".", message=opts["--message"])
  177. class cmd_commit_tree(Command):
  178. def run(self, args):
  179. opts, args = getopt(args, "", ["message"])
  180. if args == []:
  181. print("usage: dulwich commit-tree tree")
  182. sys.exit(1)
  183. opts = dict(opts)
  184. porcelain.commit_tree(".", tree=args[0], message=opts["--message"])
  185. class cmd_update_server_info(Command):
  186. def run(self, args):
  187. porcelain.update_server_info(".")
  188. class cmd_symbolic_ref(Command):
  189. def run(self, args):
  190. opts, args = getopt(args, "", ["ref-name", "force"])
  191. if not args:
  192. print("Usage: dulwich symbolic-ref REF_NAME [--force]")
  193. sys.exit(1)
  194. ref_name = args.pop(0)
  195. porcelain.symbolic_ref(".", ref_name=ref_name, force='--force' in args)
  196. class cmd_show(Command):
  197. def run(self, args):
  198. opts, args = getopt(args, "", [])
  199. porcelain.show(".", args)
  200. class cmd_diff_tree(Command):
  201. def run(self, args):
  202. opts, args = getopt(args, "", [])
  203. if len(args) < 2:
  204. print("Usage: dulwich diff-tree OLD-TREE NEW-TREE")
  205. sys.exit(1)
  206. porcelain.diff_tree(".", args[0], args[1])
  207. class cmd_rev_list(Command):
  208. def run(self, args):
  209. opts, args = getopt(args, "", [])
  210. if len(args) < 1:
  211. print('Usage: dulwich rev-list COMMITID...')
  212. sys.exit(1)
  213. porcelain.rev_list('.', args)
  214. class cmd_tag(Command):
  215. def run(self, args):
  216. opts, args = getopt(args, '', [])
  217. if len(args) < 2:
  218. print('Usage: dulwich tag NAME')
  219. sys.exit(1)
  220. porcelain.tag('.', args[0])
  221. class cmd_repack(Command):
  222. def run(self, args):
  223. opts, args = getopt(args, "", [])
  224. opts = dict(opts)
  225. porcelain.repack('.')
  226. class cmd_reset(Command):
  227. def run(self, args):
  228. opts, args = getopt(args, "", ["hard", "soft", "mixed"])
  229. opts = dict(opts)
  230. mode = ""
  231. if "--hard" in opts:
  232. mode = "hard"
  233. elif "--soft" in opts:
  234. mode = "soft"
  235. elif "--mixed" in opts:
  236. mode = "mixed"
  237. porcelain.reset('.', mode=mode, *args)
  238. class cmd_daemon(Command):
  239. def run(self, args):
  240. from dulwich import log_utils
  241. from dulwich.protocol import TCP_GIT_PORT
  242. parser = optparse.OptionParser()
  243. parser.add_option("-l", "--listen_address", dest="listen_address",
  244. default="localhost",
  245. help="Binding IP address.")
  246. parser.add_option("-p", "--port", dest="port", type=int,
  247. default=TCP_GIT_PORT,
  248. help="Binding TCP port.")
  249. options, args = parser.parse_args(args)
  250. log_utils.default_logging_config()
  251. if len(args) >= 1:
  252. gitdir = args[0]
  253. else:
  254. gitdir = '.'
  255. from dulwich import porcelain
  256. porcelain.daemon(gitdir, address=options.listen_address,
  257. port=options.port)
  258. class cmd_web_daemon(Command):
  259. def run(self, args):
  260. from dulwich import log_utils
  261. parser = optparse.OptionParser()
  262. parser.add_option("-l", "--listen_address", dest="listen_address",
  263. default="",
  264. help="Binding IP address.")
  265. parser.add_option("-p", "--port", dest="port", type=int,
  266. default=8000,
  267. help="Binding TCP port.")
  268. options, args = parser.parse_args(args)
  269. log_utils.default_logging_config()
  270. if len(args) >= 1:
  271. gitdir = args[0]
  272. else:
  273. gitdir = '.'
  274. from dulwich import porcelain
  275. porcelain.web_daemon(gitdir, address=options.listen_address,
  276. port=options.port)
  277. class cmd_receive_pack(Command):
  278. def run(self, args):
  279. parser = optparse.OptionParser()
  280. options, args = parser.parse_args(args)
  281. if len(args) >= 1:
  282. gitdir = args[0]
  283. else:
  284. gitdir = '.'
  285. porcelain.receive_pack(gitdir)
  286. class cmd_upload_pack(Command):
  287. def run(self, args):
  288. parser = optparse.OptionParser()
  289. options, args = parser.parse_args(args)
  290. if len(args) >= 1:
  291. gitdir = args[0]
  292. else:
  293. gitdir = '.'
  294. porcelain.upload_pack(gitdir)
  295. class cmd_status(Command):
  296. def run(self, args):
  297. parser = optparse.OptionParser()
  298. options, args = parser.parse_args(args)
  299. if len(args) >= 1:
  300. gitdir = args[0]
  301. else:
  302. gitdir = '.'
  303. status = porcelain.status(gitdir)
  304. if any(names for (kind, names) in status.staged.items()):
  305. sys.stdout.write("Changes to be committed:\n\n")
  306. for kind, names in status.staged.items():
  307. for name in names:
  308. sys.stdout.write("\t%s: %s\n" % (
  309. kind, name.decode(sys.getfilesystemencoding())))
  310. sys.stdout.write("\n")
  311. if status.unstaged:
  312. sys.stdout.write("Changes not staged for commit:\n\n")
  313. for name in status.unstaged:
  314. sys.stdout.write("\t%s\n" %
  315. name.decode(sys.getfilesystemencoding()))
  316. sys.stdout.write("\n")
  317. if status.untracked:
  318. sys.stdout.write("Untracked files:\n\n")
  319. for name in status.untracked:
  320. sys.stdout.write("\t%s\n" % name)
  321. sys.stdout.write("\n")
  322. class cmd_ls_remote(Command):
  323. def run(self, args):
  324. opts, args = getopt(args, '', [])
  325. if len(args) < 1:
  326. print('Usage: dulwich ls-remote URL')
  327. sys.exit(1)
  328. refs = porcelain.ls_remote(args[0])
  329. for ref in sorted(refs):
  330. sys.stdout.write("%s\t%s\n" % (ref, refs[ref]))
  331. class cmd_ls_tree(Command):
  332. def run(self, args):
  333. parser = optparse.OptionParser()
  334. parser.add_option("-r", "--recursive", action="store_true",
  335. help="Recusively list tree contents.")
  336. parser.add_option("--name-only", action="store_true",
  337. help="Only display name.")
  338. options, args = parser.parse_args(args)
  339. try:
  340. treeish = args.pop(0)
  341. except IndexError:
  342. treeish = None
  343. porcelain.ls_tree(
  344. '.', treeish, outstream=sys.stdout, recursive=options.recursive,
  345. name_only=options.name_only)
  346. class cmd_pack_objects(Command):
  347. def run(self, args):
  348. opts, args = getopt(args, '', ['stdout'])
  349. opts = dict(opts)
  350. if len(args) < 1 and not '--stdout' in args:
  351. print('Usage: dulwich pack-objects basename')
  352. sys.exit(1)
  353. object_ids = [l.strip() for l in sys.stdin.readlines()]
  354. basename = args[0]
  355. if '--stdout' in opts:
  356. packf = getattr(sys.stdout, 'buffer', sys.stdout)
  357. idxf = None
  358. close = []
  359. else:
  360. packf = open(basename + '.pack', 'w')
  361. idxf = open(basename + '.idx', 'w')
  362. close = [packf, idxf]
  363. porcelain.pack_objects('.', object_ids, packf, idxf)
  364. for f in close:
  365. f.close()
  366. class cmd_pull(Command):
  367. def run(self, args):
  368. parser = optparse.OptionParser()
  369. options, args = parser.parse_args(args)
  370. try:
  371. from_location = args[0]
  372. except IndexError:
  373. from_location = None
  374. porcelain.pull('.', from_location)
  375. class cmd_push(Command):
  376. def run(self, args):
  377. parser = optparse.OptionParser()
  378. options, args = parser.parse_args(args)
  379. if len(args) < 2:
  380. print("Usage: dulwich push TO-LOCATION REFSPEC..")
  381. sys.exit(1)
  382. to_location = args[0]
  383. refspecs = args[1:]
  384. porcelain.push('.', to_location, refspecs)
  385. class cmd_remote_add(Command):
  386. def run(self, args):
  387. parser = optparse.OptionParser()
  388. options, args = parser.parse_args(args)
  389. porcelain.remote_add('.', args[0], args[1])
  390. class SuperCommand(Command):
  391. subcommands = {}
  392. def run(self, args):
  393. if not args:
  394. print("Supported subcommands: %s" % ', '.join(self.subcommands.keys()))
  395. return False
  396. cmd = args[0]
  397. try:
  398. cmd_kls = self.subcommands[cmd]
  399. except KeyError:
  400. print('No such subcommand: %s' % args[0])
  401. return False
  402. return cmd_kls().run(args[1:])
  403. class cmd_remote(SuperCommand):
  404. subcommands = {
  405. "add": cmd_remote_add,
  406. }
  407. class cmd_check_ignore(Command):
  408. def run(self, args):
  409. parser = optparse.OptionParser()
  410. options, args = parser.parse_args(args)
  411. ret = 1
  412. for path in porcelain.check_ignore('.', args):
  413. print(path)
  414. ret = 0
  415. return ret
  416. class cmd_check_mailmap(Command):
  417. def run(self, args):
  418. parser = optparse.OptionParser()
  419. options, args = parser.parse_args(args)
  420. for arg in args:
  421. canonical_identity = porcelain.check_mailmap('.', arg)
  422. print(canonical_identity)
  423. class cmd_help(Command):
  424. def run(self, args):
  425. parser = optparse.OptionParser()
  426. parser.add_option("-a", "--all", dest="all",
  427. action="store_true",
  428. help="List all commands.")
  429. options, args = parser.parse_args(args)
  430. if options.all:
  431. print('Available commands:')
  432. for cmd in sorted(commands):
  433. print(' %s' % cmd)
  434. else:
  435. print("""\
  436. The dulwich command line tool is currently a very basic frontend for the
  437. Dulwich python module. For full functionality, please see the API reference.
  438. For a list of supported commands, see 'dulwich help -a'.
  439. """)
  440. commands = {
  441. "add": cmd_add,
  442. "archive": cmd_archive,
  443. "check-ignore": cmd_check_ignore,
  444. "check-mailmap": cmd_check_mailmap,
  445. "clone": cmd_clone,
  446. "commit": cmd_commit,
  447. "commit-tree": cmd_commit_tree,
  448. "daemon": cmd_daemon,
  449. "diff": cmd_diff,
  450. "diff-tree": cmd_diff_tree,
  451. "dump-pack": cmd_dump_pack,
  452. "dump-index": cmd_dump_index,
  453. "fetch-pack": cmd_fetch_pack,
  454. "fetch": cmd_fetch,
  455. "fsck": cmd_fsck,
  456. "help": cmd_help,
  457. "init": cmd_init,
  458. "log": cmd_log,
  459. "ls-remote": cmd_ls_remote,
  460. "ls-tree": cmd_ls_tree,
  461. "pack-objects": cmd_pack_objects,
  462. "pull": cmd_pull,
  463. "push": cmd_push,
  464. "receive-pack": cmd_receive_pack,
  465. "remote": cmd_remote,
  466. "repack": cmd_repack,
  467. "reset": cmd_reset,
  468. "rev-list": cmd_rev_list,
  469. "rm": cmd_rm,
  470. "show": cmd_show,
  471. "status": cmd_status,
  472. "symbolic-ref": cmd_symbolic_ref,
  473. "tag": cmd_tag,
  474. "update-server-info": cmd_update_server_info,
  475. "upload-pack": cmd_upload_pack,
  476. "web-daemon": cmd_web_daemon,
  477. }
  478. if len(sys.argv) < 2:
  479. print("Usage: %s <%s> [OPTIONS...]" % (sys.argv[0], "|".join(commands.keys())))
  480. sys.exit(1)
  481. cmd = sys.argv[1]
  482. try:
  483. cmd_kls = commands[cmd]
  484. except KeyError:
  485. print("No such subcommand: %s" % cmd)
  486. sys.exit(1)
  487. # TODO(jelmer): Return non-0 on errors
  488. cmd_kls().run(sys.argv[2:])