cli.py 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525
  1. #
  2. # dulwich - Simple command-line interface to Dulwich
  3. # Copyright (C) 2008-2011 Jelmer Vernooij <jelmer@jelmer.uk>
  4. # vim: expandtab
  5. #
  6. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  7. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  8. # General Public License as published 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 argparse
  29. import os
  30. import signal
  31. import sys
  32. from pathlib import Path
  33. from typing import ClassVar, Optional
  34. from dulwich import porcelain
  35. from .bundle import create_bundle_from_repo, read_bundle, write_bundle
  36. from .client import GitProtocolError, get_transport_and_path
  37. from .errors import ApplyDeltaError
  38. from .index import Index
  39. from .objects import valid_hexsha
  40. from .objectspec import parse_committish_range
  41. from .pack import Pack, sha_to_hex
  42. from .repo import Repo
  43. def signal_int(signal, frame) -> None:
  44. sys.exit(1)
  45. def signal_quit(signal, frame) -> None:
  46. import pdb
  47. pdb.set_trace()
  48. def parse_relative_time(time_str):
  49. """Parse a relative time string like '2 weeks ago' into seconds.
  50. Args:
  51. time_str: String like '2 weeks ago' or 'now'
  52. Returns:
  53. Number of seconds
  54. Raises:
  55. ValueError: If the time string cannot be parsed
  56. """
  57. if time_str == "now":
  58. return 0
  59. if not time_str.endswith(" ago"):
  60. raise ValueError(f"Invalid relative time format: {time_str}")
  61. parts = time_str[:-4].split()
  62. if len(parts) != 2:
  63. raise ValueError(f"Invalid relative time format: {time_str}")
  64. try:
  65. num = int(parts[0])
  66. unit = parts[1]
  67. multipliers = {
  68. "second": 1,
  69. "seconds": 1,
  70. "minute": 60,
  71. "minutes": 60,
  72. "hour": 3600,
  73. "hours": 3600,
  74. "day": 86400,
  75. "days": 86400,
  76. "week": 604800,
  77. "weeks": 604800,
  78. }
  79. if unit in multipliers:
  80. return num * multipliers[unit]
  81. else:
  82. raise ValueError(f"Unknown time unit: {unit}")
  83. except ValueError as e:
  84. if "invalid literal" in str(e):
  85. raise ValueError(f"Invalid number in relative time: {parts[0]}")
  86. raise
  87. def format_bytes(bytes):
  88. """Format bytes as human-readable string.
  89. Args:
  90. bytes: Number of bytes
  91. Returns:
  92. Human-readable string like "1.5 MB"
  93. """
  94. for unit in ["B", "KB", "MB", "GB"]:
  95. if bytes < 1024.0:
  96. return f"{bytes:.1f} {unit}"
  97. bytes /= 1024.0
  98. return f"{bytes:.1f} TB"
  99. class Command:
  100. """A Dulwich subcommand."""
  101. def run(self, args) -> Optional[int]:
  102. """Run the command."""
  103. raise NotImplementedError(self.run)
  104. class cmd_archive(Command):
  105. def run(self, args) -> None:
  106. parser = argparse.ArgumentParser()
  107. parser.add_argument(
  108. "--remote",
  109. type=str,
  110. help="Retrieve archive from specified remote repo",
  111. )
  112. parser.add_argument("committish", type=str, nargs="?")
  113. args = parser.parse_args(args)
  114. if args.remote:
  115. client, path = get_transport_and_path(args.remote)
  116. client.archive(
  117. path,
  118. args.committish,
  119. sys.stdout.write,
  120. write_error=sys.stderr.write,
  121. )
  122. else:
  123. # Use buffer if available (for binary output), otherwise use stdout
  124. outstream = getattr(sys.stdout, "buffer", sys.stdout)
  125. porcelain.archive(
  126. ".", args.committish, outstream=outstream, errstream=sys.stderr
  127. )
  128. class cmd_add(Command):
  129. def run(self, argv) -> None:
  130. parser = argparse.ArgumentParser()
  131. parser.add_argument("path", nargs="+")
  132. args = parser.parse_args(argv)
  133. # Convert '.' to None to add all files
  134. paths = args.path
  135. if len(paths) == 1 and paths[0] == ".":
  136. paths = None
  137. porcelain.add(".", paths=paths)
  138. class cmd_annotate(Command):
  139. def run(self, argv) -> None:
  140. parser = argparse.ArgumentParser()
  141. parser.add_argument("path", help="Path to file to annotate")
  142. parser.add_argument("committish", nargs="?", help="Commit to start from")
  143. args = parser.parse_args(argv)
  144. results = porcelain.annotate(".", args.path, args.committish)
  145. for (commit, entry), line in results:
  146. # Show shortened commit hash and line content
  147. commit_hash = commit.id[:8]
  148. print(f"{commit_hash.decode()} {line.decode()}")
  149. class cmd_blame(Command):
  150. def run(self, argv) -> None:
  151. # blame is an alias for annotate
  152. cmd_annotate().run(argv)
  153. class cmd_rm(Command):
  154. def run(self, argv) -> None:
  155. parser = argparse.ArgumentParser()
  156. parser.add_argument(
  157. "--cached", action="store_true", help="Remove from index only"
  158. )
  159. parser.add_argument("path", type=Path, nargs="+")
  160. args = parser.parse_args(argv)
  161. porcelain.remove(".", paths=args.path, cached=args.cached)
  162. class cmd_mv(Command):
  163. def run(self, argv) -> None:
  164. parser = argparse.ArgumentParser()
  165. parser.add_argument(
  166. "-f",
  167. "--force",
  168. action="store_true",
  169. help="Force move even if destination exists",
  170. )
  171. parser.add_argument("source", type=Path)
  172. parser.add_argument("destination", type=Path)
  173. args = parser.parse_args(argv)
  174. porcelain.mv(".", args.source, args.destination, force=args.force)
  175. class cmd_fetch_pack(Command):
  176. def run(self, argv) -> None:
  177. parser = argparse.ArgumentParser()
  178. parser.add_argument("--all", action="store_true")
  179. parser.add_argument("location", nargs="?", type=str)
  180. parser.add_argument("refs", nargs="*", type=str)
  181. args = parser.parse_args(argv)
  182. client, path = get_transport_and_path(args.location)
  183. r = Repo(".")
  184. if args.all:
  185. determine_wants = r.object_store.determine_wants_all
  186. else:
  187. def determine_wants(refs, depth: Optional[int] = None):
  188. return [y.encode("utf-8") for y in args.refs if y not in r.object_store]
  189. client.fetch(path, r, determine_wants)
  190. class cmd_fetch(Command):
  191. def run(self, args) -> None:
  192. parser = argparse.ArgumentParser()
  193. parser.add_argument("location", help="Remote location to fetch from")
  194. args = parser.parse_args(args)
  195. client, path = get_transport_and_path(args.location)
  196. r = Repo(".")
  197. def progress(msg: bytes) -> None:
  198. sys.stdout.buffer.write(msg)
  199. refs = client.fetch(path, r, progress=progress)
  200. print("Remote refs:")
  201. for item in refs.items():
  202. print("{} -> {}".format(*item))
  203. class cmd_for_each_ref(Command):
  204. def run(self, args) -> None:
  205. parser = argparse.ArgumentParser()
  206. parser.add_argument("pattern", type=str, nargs="?")
  207. args = parser.parse_args(args)
  208. for sha, object_type, ref in porcelain.for_each_ref(".", args.pattern):
  209. print(f"{sha.decode()} {object_type.decode()}\t{ref.decode()}")
  210. class cmd_fsck(Command):
  211. def run(self, args) -> None:
  212. parser = argparse.ArgumentParser()
  213. parser.parse_args(args)
  214. for obj, msg in porcelain.fsck("."):
  215. print(f"{obj}: {msg}")
  216. class cmd_log(Command):
  217. def run(self, args) -> None:
  218. parser = argparse.ArgumentParser()
  219. parser.add_argument(
  220. "--reverse",
  221. action="store_true",
  222. help="Reverse order in which entries are printed",
  223. )
  224. parser.add_argument(
  225. "--name-status",
  226. action="store_true",
  227. help="Print name/status for each changed file",
  228. )
  229. parser.add_argument("paths", nargs="*", help="Paths to show log for")
  230. args = parser.parse_args(args)
  231. porcelain.log(
  232. ".",
  233. paths=args.paths,
  234. reverse=args.reverse,
  235. name_status=args.name_status,
  236. outstream=sys.stdout,
  237. )
  238. class cmd_diff(Command):
  239. def run(self, args) -> None:
  240. parser = argparse.ArgumentParser()
  241. parser.add_argument(
  242. "committish", nargs="*", default=[], help="Commits or refs to compare"
  243. )
  244. parser.add_argument("--staged", action="store_true", help="Show staged changes")
  245. parser.add_argument(
  246. "--cached",
  247. action="store_true",
  248. help="Show staged changes (same as --staged)",
  249. )
  250. parser.add_argument(
  251. "--", dest="separator", action="store_true", help=argparse.SUPPRESS
  252. )
  253. parser.add_argument("paths", nargs="*", default=[], help="Paths to limit diff")
  254. # Handle the -- separator for paths
  255. if "--" in args:
  256. sep_index = args.index("--")
  257. parsed_args = parser.parse_args(args[:sep_index])
  258. parsed_args.paths = args[sep_index + 1 :]
  259. else:
  260. parsed_args = parser.parse_args(args)
  261. args = parsed_args
  262. if len(args.committish) == 0:
  263. # Show diff for working tree or staged changes
  264. porcelain.diff(
  265. ".",
  266. staged=(args.staged or args.cached),
  267. paths=args.paths or None,
  268. outstream=sys.stdout.buffer,
  269. )
  270. elif len(args.committish) == 1:
  271. # Show diff between working tree and specified commit
  272. if args.staged or args.cached:
  273. parser.error("--staged/--cached cannot be used with commits")
  274. porcelain.diff(
  275. ".",
  276. commit=args.committish[0],
  277. staged=False,
  278. paths=args.paths or None,
  279. outstream=sys.stdout.buffer,
  280. )
  281. elif len(args.committish) == 2:
  282. # Show diff between two commits
  283. porcelain.diff(
  284. ".",
  285. commit=args.committish[0],
  286. commit2=args.committish[1],
  287. paths=args.paths or None,
  288. outstream=sys.stdout.buffer,
  289. )
  290. else:
  291. parser.error("Too many arguments - specify at most two commits")
  292. class cmd_dump_pack(Command):
  293. def run(self, args) -> None:
  294. parser = argparse.ArgumentParser()
  295. parser.add_argument("filename", help="Pack file to dump")
  296. args = parser.parse_args(args)
  297. basename, _ = os.path.splitext(args.filename)
  298. x = Pack(basename)
  299. print(f"Object names checksum: {x.name()}")
  300. print(f"Checksum: {sha_to_hex(x.get_stored_checksum())!r}")
  301. x.check()
  302. print(f"Length: {len(x)}")
  303. for name in x:
  304. try:
  305. print(f"\t{x[name]}")
  306. except KeyError as k:
  307. print(f"\t{name}: Unable to resolve base {k}")
  308. except ApplyDeltaError as e:
  309. print(f"\t{name}: Unable to apply delta: {e!r}")
  310. class cmd_dump_index(Command):
  311. def run(self, args) -> None:
  312. parser = argparse.ArgumentParser()
  313. parser.add_argument("filename", help="Index file to dump")
  314. args = parser.parse_args(args)
  315. idx = Index(args.filename)
  316. for o in idx:
  317. print(o, idx[o])
  318. class cmd_init(Command):
  319. def run(self, args) -> None:
  320. parser = argparse.ArgumentParser()
  321. parser.add_argument(
  322. "--bare", action="store_true", help="Create a bare repository"
  323. )
  324. parser.add_argument(
  325. "path", nargs="?", default=os.getcwd(), help="Repository path"
  326. )
  327. args = parser.parse_args(args)
  328. porcelain.init(args.path, bare=args.bare)
  329. class cmd_clone(Command):
  330. def run(self, args) -> None:
  331. parser = argparse.ArgumentParser()
  332. parser.add_argument(
  333. "--bare",
  334. help="Whether to create a bare repository.",
  335. action="store_true",
  336. )
  337. parser.add_argument("--depth", type=int, help="Depth at which to fetch")
  338. parser.add_argument(
  339. "-b",
  340. "--branch",
  341. type=str,
  342. help="Check out branch instead of branch pointed to by remote HEAD",
  343. )
  344. parser.add_argument(
  345. "--refspec",
  346. type=str,
  347. help="References to fetch",
  348. action="append",
  349. )
  350. parser.add_argument(
  351. "--filter",
  352. dest="filter_spec",
  353. type=str,
  354. help="git-rev-list-style object filter",
  355. )
  356. parser.add_argument(
  357. "--protocol",
  358. type=int,
  359. help="Git protocol version to use",
  360. )
  361. parser.add_argument(
  362. "--recurse-submodules",
  363. action="store_true",
  364. help="Initialize and clone submodules",
  365. )
  366. parser.add_argument("source", help="Repository to clone from")
  367. parser.add_argument("target", nargs="?", help="Directory to clone into")
  368. args = parser.parse_args(args)
  369. try:
  370. porcelain.clone(
  371. args.source,
  372. args.target,
  373. bare=args.bare,
  374. depth=args.depth,
  375. branch=args.branch,
  376. refspec=args.refspec,
  377. filter_spec=args.filter_spec,
  378. protocol_version=args.protocol,
  379. recurse_submodules=args.recurse_submodules,
  380. )
  381. except GitProtocolError as e:
  382. print(f"{e}")
  383. class cmd_commit(Command):
  384. def run(self, args) -> None:
  385. parser = argparse.ArgumentParser()
  386. parser.add_argument("--message", "-m", required=True, help="Commit message")
  387. parser.add_argument(
  388. "-a",
  389. "--all",
  390. action="store_true",
  391. help="Automatically stage all tracked files that have been modified",
  392. )
  393. args = parser.parse_args(args)
  394. porcelain.commit(".", message=args.message, all=args.all)
  395. class cmd_commit_tree(Command):
  396. def run(self, args) -> None:
  397. parser = argparse.ArgumentParser()
  398. parser.add_argument("--message", "-m", required=True, help="Commit message")
  399. parser.add_argument("tree", help="Tree SHA to commit")
  400. args = parser.parse_args(args)
  401. porcelain.commit_tree(".", tree=args.tree, message=args.message)
  402. class cmd_update_server_info(Command):
  403. def run(self, args) -> None:
  404. porcelain.update_server_info(".")
  405. class cmd_symbolic_ref(Command):
  406. def run(self, args) -> None:
  407. parser = argparse.ArgumentParser()
  408. parser.add_argument("name", help="Symbolic reference name")
  409. parser.add_argument("ref", nargs="?", help="Target reference")
  410. parser.add_argument("--force", action="store_true", help="Force update")
  411. args = parser.parse_args(args)
  412. # If ref is provided, we're setting; otherwise we're reading
  413. if args.ref:
  414. # Set symbolic reference
  415. from .repo import Repo
  416. with Repo(".") as repo:
  417. repo.refs.set_symbolic_ref(args.name.encode(), args.ref.encode())
  418. else:
  419. # Read symbolic reference
  420. from .repo import Repo
  421. with Repo(".") as repo:
  422. try:
  423. target = repo.refs.read_ref(args.name.encode())
  424. if target.startswith(b"ref: "):
  425. print(target[5:].decode())
  426. else:
  427. print(target.decode())
  428. except KeyError:
  429. print(f"fatal: ref '{args.name}' is not a symbolic ref")
  430. class cmd_pack_refs(Command):
  431. def run(self, argv) -> None:
  432. parser = argparse.ArgumentParser()
  433. parser.add_argument("--all", action="store_true")
  434. # ignored, we never prune
  435. parser.add_argument("--no-prune", action="store_true")
  436. args = parser.parse_args(argv)
  437. porcelain.pack_refs(".", all=args.all)
  438. class cmd_show(Command):
  439. def run(self, argv) -> None:
  440. parser = argparse.ArgumentParser()
  441. parser.add_argument("objectish", type=str, nargs="*")
  442. args = parser.parse_args(argv)
  443. porcelain.show(".", args.objectish or None, outstream=sys.stdout)
  444. class cmd_diff_tree(Command):
  445. def run(self, args) -> None:
  446. parser = argparse.ArgumentParser()
  447. parser.add_argument("old_tree", help="Old tree SHA")
  448. parser.add_argument("new_tree", help="New tree SHA")
  449. args = parser.parse_args(args)
  450. porcelain.diff_tree(".", args.old_tree, args.new_tree)
  451. class cmd_rev_list(Command):
  452. def run(self, args) -> None:
  453. parser = argparse.ArgumentParser()
  454. parser.add_argument("commits", nargs="+", help="Commit IDs to list")
  455. args = parser.parse_args(args)
  456. porcelain.rev_list(".", args.commits)
  457. class cmd_tag(Command):
  458. def run(self, args) -> None:
  459. parser = argparse.ArgumentParser()
  460. parser.add_argument(
  461. "-a",
  462. "--annotated",
  463. help="Create an annotated tag.",
  464. action="store_true",
  465. )
  466. parser.add_argument(
  467. "-s", "--sign", help="Sign the annotated tag.", action="store_true"
  468. )
  469. parser.add_argument("tag_name", help="Name of the tag to create")
  470. args = parser.parse_args(args)
  471. porcelain.tag_create(
  472. ".", args.tag_name, annotated=args.annotated, sign=args.sign
  473. )
  474. class cmd_repack(Command):
  475. def run(self, args) -> None:
  476. parser = argparse.ArgumentParser()
  477. parser.parse_args(args)
  478. porcelain.repack(".")
  479. class cmd_reflog(Command):
  480. def run(self, args) -> None:
  481. parser = argparse.ArgumentParser()
  482. parser.add_argument(
  483. "ref", nargs="?", default="HEAD", help="Reference to show reflog for"
  484. )
  485. parser.add_argument(
  486. "--all", action="store_true", help="Show reflogs for all refs"
  487. )
  488. args = parser.parse_args(args)
  489. if args.all:
  490. # Show reflogs for all refs
  491. for ref_bytes, entry in porcelain.reflog(".", all=True):
  492. ref_str = ref_bytes.decode("utf-8", "replace")
  493. short_new = entry.new_sha[:8].decode("ascii")
  494. print(
  495. f"{short_new} {ref_str}: {entry.message.decode('utf-8', 'replace')}"
  496. )
  497. else:
  498. ref = args.ref.encode("utf-8") if isinstance(args.ref, str) else args.ref
  499. for i, entry in enumerate(porcelain.reflog(".", ref)):
  500. # Format similar to git reflog
  501. short_new = entry.new_sha[:8].decode("ascii")
  502. print(
  503. f"{short_new} {ref.decode('utf-8', 'replace')}@{{{i}}}: {entry.message.decode('utf-8', 'replace')}"
  504. )
  505. class cmd_reset(Command):
  506. def run(self, args) -> None:
  507. parser = argparse.ArgumentParser()
  508. mode_group = parser.add_mutually_exclusive_group()
  509. mode_group.add_argument(
  510. "--hard", action="store_true", help="Reset working tree and index"
  511. )
  512. mode_group.add_argument("--soft", action="store_true", help="Reset only HEAD")
  513. mode_group.add_argument(
  514. "--mixed", action="store_true", help="Reset HEAD and index"
  515. )
  516. parser.add_argument("treeish", nargs="?", help="Commit/tree to reset to")
  517. args = parser.parse_args(args)
  518. if args.hard:
  519. mode = "hard"
  520. elif args.soft:
  521. mode = "soft"
  522. elif args.mixed:
  523. mode = "mixed"
  524. else:
  525. # Default to mixed behavior
  526. mode = "mixed"
  527. # Use the porcelain.reset function for all modes
  528. porcelain.reset(".", mode=mode, treeish=args.treeish)
  529. class cmd_revert(Command):
  530. def run(self, args) -> None:
  531. parser = argparse.ArgumentParser()
  532. parser.add_argument(
  533. "--no-commit",
  534. "-n",
  535. action="store_true",
  536. help="Apply changes but don't create a commit",
  537. )
  538. parser.add_argument("-m", "--message", help="Custom commit message")
  539. parser.add_argument("commits", nargs="+", help="Commits to revert")
  540. args = parser.parse_args(args)
  541. result = porcelain.revert(
  542. ".", commits=args.commits, no_commit=args.no_commit, message=args.message
  543. )
  544. if result and not args.no_commit:
  545. print(f"[{result.decode('ascii')[:7]}] Revert completed")
  546. class cmd_daemon(Command):
  547. def run(self, args) -> None:
  548. from dulwich import log_utils
  549. from .protocol import TCP_GIT_PORT
  550. parser = argparse.ArgumentParser()
  551. parser.add_argument(
  552. "-l",
  553. "--listen_address",
  554. default="localhost",
  555. help="Binding IP address.",
  556. )
  557. parser.add_argument(
  558. "-p",
  559. "--port",
  560. type=int,
  561. default=TCP_GIT_PORT,
  562. help="Binding TCP port.",
  563. )
  564. parser.add_argument(
  565. "gitdir", nargs="?", default=".", help="Git directory to serve"
  566. )
  567. args = parser.parse_args(args)
  568. log_utils.default_logging_config()
  569. porcelain.daemon(args.gitdir, address=args.listen_address, port=args.port)
  570. class cmd_web_daemon(Command):
  571. def run(self, args) -> None:
  572. from dulwich import log_utils
  573. parser = argparse.ArgumentParser()
  574. parser.add_argument(
  575. "-l",
  576. "--listen_address",
  577. default="",
  578. help="Binding IP address.",
  579. )
  580. parser.add_argument(
  581. "-p",
  582. "--port",
  583. type=int,
  584. default=8000,
  585. help="Binding TCP port.",
  586. )
  587. parser.add_argument(
  588. "gitdir", nargs="?", default=".", help="Git directory to serve"
  589. )
  590. args = parser.parse_args(args)
  591. log_utils.default_logging_config()
  592. porcelain.web_daemon(args.gitdir, address=args.listen_address, port=args.port)
  593. class cmd_write_tree(Command):
  594. def run(self, args) -> None:
  595. parser = argparse.ArgumentParser()
  596. parser.parse_args(args)
  597. sys.stdout.write("{}\n".format(porcelain.write_tree(".").decode()))
  598. class cmd_receive_pack(Command):
  599. def run(self, args) -> None:
  600. parser = argparse.ArgumentParser()
  601. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  602. args = parser.parse_args(args)
  603. porcelain.receive_pack(args.gitdir)
  604. class cmd_upload_pack(Command):
  605. def run(self, args) -> None:
  606. parser = argparse.ArgumentParser()
  607. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  608. args = parser.parse_args(args)
  609. porcelain.upload_pack(args.gitdir)
  610. class cmd_status(Command):
  611. def run(self, args) -> None:
  612. parser = argparse.ArgumentParser()
  613. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  614. args = parser.parse_args(args)
  615. status = porcelain.status(args.gitdir)
  616. if any(names for (kind, names) in status.staged.items()):
  617. sys.stdout.write("Changes to be committed:\n\n")
  618. for kind, names in status.staged.items():
  619. for name in names:
  620. sys.stdout.write(
  621. f"\t{kind}: {name.decode(sys.getfilesystemencoding())}\n"
  622. )
  623. sys.stdout.write("\n")
  624. if status.unstaged:
  625. sys.stdout.write("Changes not staged for commit:\n\n")
  626. for name in status.unstaged:
  627. sys.stdout.write(f"\t{name.decode(sys.getfilesystemencoding())}\n")
  628. sys.stdout.write("\n")
  629. if status.untracked:
  630. sys.stdout.write("Untracked files:\n\n")
  631. for name in status.untracked:
  632. sys.stdout.write(f"\t{name}\n")
  633. sys.stdout.write("\n")
  634. class cmd_ls_remote(Command):
  635. def run(self, args) -> None:
  636. parser = argparse.ArgumentParser()
  637. parser.add_argument(
  638. "--symref", action="store_true", help="Show symbolic references"
  639. )
  640. parser.add_argument("url", help="Remote URL to list references from")
  641. args = parser.parse_args(args)
  642. result = porcelain.ls_remote(args.url)
  643. if args.symref:
  644. # Show symrefs first, like git does
  645. for ref, target in sorted(result.symrefs.items()):
  646. sys.stdout.write(f"ref: {target.decode()}\t{ref.decode()}\n")
  647. # Show regular refs
  648. for ref in sorted(result.refs):
  649. sys.stdout.write(f"{result.refs[ref].decode()}\t{ref.decode()}\n")
  650. class cmd_ls_tree(Command):
  651. def run(self, args) -> None:
  652. parser = argparse.ArgumentParser()
  653. parser.add_argument(
  654. "-r",
  655. "--recursive",
  656. action="store_true",
  657. help="Recursively list tree contents.",
  658. )
  659. parser.add_argument(
  660. "--name-only", action="store_true", help="Only display name."
  661. )
  662. parser.add_argument("treeish", nargs="?", help="Tree-ish to list")
  663. args = parser.parse_args(args)
  664. porcelain.ls_tree(
  665. ".",
  666. args.treeish,
  667. outstream=sys.stdout,
  668. recursive=args.recursive,
  669. name_only=args.name_only,
  670. )
  671. class cmd_pack_objects(Command):
  672. def run(self, args) -> None:
  673. parser = argparse.ArgumentParser()
  674. parser.add_argument(
  675. "--stdout", action="store_true", help="Write pack to stdout"
  676. )
  677. parser.add_argument("--deltify", action="store_true", help="Create deltas")
  678. parser.add_argument(
  679. "--no-reuse-deltas", action="store_true", help="Don't reuse existing deltas"
  680. )
  681. parser.add_argument("basename", nargs="?", help="Base name for pack files")
  682. args = parser.parse_args(args)
  683. if not args.stdout and not args.basename:
  684. parser.error("basename required when not using --stdout")
  685. object_ids = [line.strip() for line in sys.stdin.readlines()]
  686. deltify = args.deltify
  687. reuse_deltas = not args.no_reuse_deltas
  688. if args.stdout:
  689. packf = getattr(sys.stdout, "buffer", sys.stdout)
  690. idxf = None
  691. close = []
  692. else:
  693. packf = open(args.basename + ".pack", "wb")
  694. idxf = open(args.basename + ".idx", "wb")
  695. close = [packf, idxf]
  696. porcelain.pack_objects(
  697. ".", object_ids, packf, idxf, deltify=deltify, reuse_deltas=reuse_deltas
  698. )
  699. for f in close:
  700. f.close()
  701. class cmd_unpack_objects(Command):
  702. def run(self, args) -> None:
  703. parser = argparse.ArgumentParser()
  704. parser.add_argument("pack_file", help="Pack file to unpack")
  705. args = parser.parse_args(args)
  706. count = porcelain.unpack_objects(args.pack_file)
  707. print(f"Unpacked {count} objects")
  708. class cmd_prune(Command):
  709. def run(self, args) -> Optional[int]:
  710. import datetime
  711. import time
  712. from dulwich.object_store import DEFAULT_TEMPFILE_GRACE_PERIOD
  713. parser = argparse.ArgumentParser(
  714. description="Remove temporary pack files left behind by interrupted operations"
  715. )
  716. parser.add_argument(
  717. "--expire",
  718. nargs="?",
  719. const="2.weeks.ago",
  720. help="Only prune files older than the specified date (default: 2.weeks.ago)",
  721. )
  722. parser.add_argument(
  723. "--dry-run",
  724. "-n",
  725. action="store_true",
  726. help="Only report what would be removed",
  727. )
  728. parser.add_argument(
  729. "--verbose",
  730. "-v",
  731. action="store_true",
  732. help="Report all actions",
  733. )
  734. args = parser.parse_args(args)
  735. # Parse expire grace period
  736. grace_period = DEFAULT_TEMPFILE_GRACE_PERIOD
  737. if args.expire:
  738. try:
  739. grace_period = parse_relative_time(args.expire)
  740. except ValueError:
  741. # Try to parse as absolute date
  742. try:
  743. date = datetime.datetime.strptime(args.expire, "%Y-%m-%d")
  744. grace_period = int(time.time() - date.timestamp())
  745. except ValueError:
  746. print(f"Error: Invalid expire date: {args.expire}", file=sys.stderr)
  747. return 1
  748. # Progress callback
  749. def progress(msg):
  750. if args.verbose:
  751. print(msg)
  752. try:
  753. porcelain.prune(
  754. ".",
  755. grace_period=grace_period,
  756. dry_run=args.dry_run,
  757. progress=progress if args.verbose else None,
  758. )
  759. return None
  760. except porcelain.Error as e:
  761. print(f"Error: {e}", file=sys.stderr)
  762. return 1
  763. class cmd_pull(Command):
  764. def run(self, args) -> None:
  765. parser = argparse.ArgumentParser()
  766. parser.add_argument("from_location", type=str)
  767. parser.add_argument("refspec", type=str, nargs="*")
  768. parser.add_argument("--filter", type=str, nargs=1)
  769. parser.add_argument("--protocol", type=int)
  770. args = parser.parse_args(args)
  771. porcelain.pull(
  772. ".",
  773. args.from_location or None,
  774. args.refspec or None,
  775. filter_spec=args.filter,
  776. protocol_version=args.protocol or None,
  777. )
  778. class cmd_push(Command):
  779. def run(self, argv) -> Optional[int]:
  780. parser = argparse.ArgumentParser()
  781. parser.add_argument("-f", "--force", action="store_true", help="Force")
  782. parser.add_argument("to_location", type=str)
  783. parser.add_argument("refspec", type=str, nargs="*")
  784. args = parser.parse_args(argv)
  785. try:
  786. porcelain.push(
  787. ".", args.to_location, args.refspec or None, force=args.force
  788. )
  789. except porcelain.DivergedBranches:
  790. sys.stderr.write("Diverged branches; specify --force to override")
  791. return 1
  792. return None
  793. class cmd_remote_add(Command):
  794. def run(self, args) -> None:
  795. parser = argparse.ArgumentParser()
  796. parser.add_argument("name", help="Name of the remote")
  797. parser.add_argument("url", help="URL of the remote")
  798. args = parser.parse_args(args)
  799. porcelain.remote_add(".", args.name, args.url)
  800. class SuperCommand(Command):
  801. subcommands: ClassVar[dict[str, type[Command]]] = {}
  802. default_command: ClassVar[Optional[type[Command]]] = None
  803. def run(self, args):
  804. if not args:
  805. if self.default_command:
  806. return self.default_command().run(args)
  807. else:
  808. print(
  809. "Supported subcommands: {}".format(
  810. ", ".join(self.subcommands.keys())
  811. )
  812. )
  813. return False
  814. cmd = args[0]
  815. try:
  816. cmd_kls = self.subcommands[cmd]
  817. except KeyError:
  818. print(f"No such subcommand: {args[0]}")
  819. return False
  820. return cmd_kls().run(args[1:])
  821. class cmd_remote(SuperCommand):
  822. subcommands: ClassVar[dict[str, type[Command]]] = {
  823. "add": cmd_remote_add,
  824. }
  825. class cmd_submodule_list(Command):
  826. def run(self, argv) -> None:
  827. parser = argparse.ArgumentParser()
  828. parser.parse_args(argv)
  829. for path, sha in porcelain.submodule_list("."):
  830. sys.stdout.write(f" {sha} {path}\n")
  831. class cmd_submodule_init(Command):
  832. def run(self, argv) -> None:
  833. parser = argparse.ArgumentParser()
  834. parser.parse_args(argv)
  835. porcelain.submodule_init(".")
  836. class cmd_submodule_add(Command):
  837. def run(self, argv) -> None:
  838. parser = argparse.ArgumentParser()
  839. parser.add_argument("url", help="URL of repository to add as submodule")
  840. parser.add_argument("path", nargs="?", help="Path where submodule should live")
  841. parser.add_argument("--name", help="Name for the submodule")
  842. args = parser.parse_args(argv)
  843. porcelain.submodule_add(".", args.url, args.path, args.name)
  844. class cmd_submodule_update(Command):
  845. def run(self, argv) -> None:
  846. parser = argparse.ArgumentParser()
  847. parser.add_argument(
  848. "--init", action="store_true", help="Initialize submodules first"
  849. )
  850. parser.add_argument(
  851. "--force",
  852. action="store_true",
  853. help="Force update even if local changes exist",
  854. )
  855. parser.add_argument(
  856. "paths", nargs="*", help="Specific submodule paths to update"
  857. )
  858. args = parser.parse_args(argv)
  859. paths = args.paths if args.paths else None
  860. porcelain.submodule_update(".", paths=paths, init=args.init, force=args.force)
  861. class cmd_submodule(SuperCommand):
  862. subcommands: ClassVar[dict[str, type[Command]]] = {
  863. "add": cmd_submodule_add,
  864. "init": cmd_submodule_init,
  865. "list": cmd_submodule_list,
  866. "update": cmd_submodule_update,
  867. }
  868. default_command = cmd_submodule_list
  869. class cmd_check_ignore(Command):
  870. def run(self, args):
  871. parser = argparse.ArgumentParser()
  872. parser.add_argument("paths", nargs="+", help="Paths to check")
  873. args = parser.parse_args(args)
  874. ret = 1
  875. for path in porcelain.check_ignore(".", args.paths):
  876. print(path)
  877. ret = 0
  878. return ret
  879. class cmd_check_mailmap(Command):
  880. def run(self, args) -> None:
  881. parser = argparse.ArgumentParser()
  882. parser.add_argument("identities", nargs="+", help="Identities to check")
  883. args = parser.parse_args(args)
  884. for identity in args.identities:
  885. canonical_identity = porcelain.check_mailmap(".", identity)
  886. print(canonical_identity)
  887. class cmd_branch(Command):
  888. def run(self, args) -> Optional[int]:
  889. parser = argparse.ArgumentParser()
  890. parser.add_argument(
  891. "branch",
  892. type=str,
  893. help="Name of the branch",
  894. )
  895. parser.add_argument(
  896. "-d",
  897. "--delete",
  898. action="store_true",
  899. help="Delete branch",
  900. )
  901. args = parser.parse_args(args)
  902. if not args.branch:
  903. print("Usage: dulwich branch [-d] BRANCH_NAME")
  904. return 1
  905. if args.delete:
  906. porcelain.branch_delete(".", name=args.branch)
  907. else:
  908. try:
  909. porcelain.branch_create(".", name=args.branch)
  910. except porcelain.Error as e:
  911. sys.stderr.write(f"{e}")
  912. return 1
  913. return 0
  914. class cmd_checkout(Command):
  915. def run(self, args) -> Optional[int]:
  916. parser = argparse.ArgumentParser()
  917. parser.add_argument(
  918. "target",
  919. type=str,
  920. help="Name of the branch, tag, or commit to checkout",
  921. )
  922. parser.add_argument(
  923. "-f",
  924. "--force",
  925. action="store_true",
  926. help="Force checkout",
  927. )
  928. parser.add_argument(
  929. "-b",
  930. "--new-branch",
  931. type=str,
  932. help="Create a new branch at the target and switch to it",
  933. )
  934. args = parser.parse_args(args)
  935. if not args.target:
  936. print("Usage: dulwich checkout TARGET [--force] [-b NEW_BRANCH]")
  937. return 1
  938. try:
  939. porcelain.checkout(
  940. ".", target=args.target, force=args.force, new_branch=args.new_branch
  941. )
  942. except porcelain.CheckoutError as e:
  943. sys.stderr.write(f"{e}\n")
  944. return 1
  945. return 0
  946. class cmd_stash_list(Command):
  947. def run(self, args) -> None:
  948. parser = argparse.ArgumentParser()
  949. parser.parse_args(args)
  950. for i, entry in porcelain.stash_list("."):
  951. print("stash@{{{}}}: {}".format(i, entry.message.rstrip("\n")))
  952. class cmd_stash_push(Command):
  953. def run(self, args) -> None:
  954. parser = argparse.ArgumentParser()
  955. parser.parse_args(args)
  956. porcelain.stash_push(".")
  957. print("Saved working directory and index state")
  958. class cmd_stash_pop(Command):
  959. def run(self, args) -> None:
  960. parser = argparse.ArgumentParser()
  961. parser.parse_args(args)
  962. porcelain.stash_pop(".")
  963. print("Restored working directory and index state")
  964. class cmd_bisect(SuperCommand):
  965. """Git bisect command implementation."""
  966. subcommands: ClassVar[dict[str, type[Command]]] = {}
  967. def run(self, args):
  968. parser = argparse.ArgumentParser(prog="dulwich bisect")
  969. subparsers = parser.add_subparsers(dest="subcommand", help="bisect subcommands")
  970. # bisect start
  971. start_parser = subparsers.add_parser("start", help="Start a new bisect session")
  972. start_parser.add_argument("bad", nargs="?", help="Bad commit")
  973. start_parser.add_argument("good", nargs="*", help="Good commit(s)")
  974. start_parser.add_argument(
  975. "--no-checkout",
  976. action="store_true",
  977. help="Don't checkout commits during bisect",
  978. )
  979. start_parser.add_argument(
  980. "--term-bad", default="bad", help="Term to use for bad commits"
  981. )
  982. start_parser.add_argument(
  983. "--term-good", default="good", help="Term to use for good commits"
  984. )
  985. start_parser.add_argument(
  986. "--", dest="paths", nargs="*", help="Paths to limit bisect to"
  987. )
  988. # bisect bad
  989. bad_parser = subparsers.add_parser("bad", help="Mark a commit as bad")
  990. bad_parser.add_argument("rev", nargs="?", help="Commit to mark as bad")
  991. # bisect good
  992. good_parser = subparsers.add_parser("good", help="Mark a commit as good")
  993. good_parser.add_argument("rev", nargs="?", help="Commit to mark as good")
  994. # bisect skip
  995. skip_parser = subparsers.add_parser("skip", help="Skip commits")
  996. skip_parser.add_argument("revs", nargs="*", help="Commits to skip")
  997. # bisect reset
  998. reset_parser = subparsers.add_parser("reset", help="Reset bisect state")
  999. reset_parser.add_argument("commit", nargs="?", help="Commit to reset to")
  1000. # bisect log
  1001. subparsers.add_parser("log", help="Show bisect log")
  1002. # bisect replay
  1003. replay_parser = subparsers.add_parser("replay", help="Replay bisect log")
  1004. replay_parser.add_argument("logfile", help="Log file to replay")
  1005. # bisect help
  1006. subparsers.add_parser("help", help="Show help")
  1007. parsed_args = parser.parse_args(args)
  1008. if not parsed_args.subcommand:
  1009. parser.print_help()
  1010. return 1
  1011. try:
  1012. if parsed_args.subcommand == "start":
  1013. next_sha = porcelain.bisect_start(
  1014. bad=parsed_args.bad,
  1015. good=parsed_args.good if parsed_args.good else None,
  1016. paths=parsed_args.paths,
  1017. no_checkout=parsed_args.no_checkout,
  1018. term_bad=parsed_args.term_bad,
  1019. term_good=parsed_args.term_good,
  1020. )
  1021. if next_sha:
  1022. print(f"Bisecting: checking out '{next_sha.decode('ascii')}'")
  1023. elif parsed_args.subcommand == "bad":
  1024. next_sha = porcelain.bisect_bad(rev=parsed_args.rev)
  1025. if next_sha:
  1026. print(f"Bisecting: checking out '{next_sha.decode('ascii')}'")
  1027. else:
  1028. # Bisect complete - find the first bad commit
  1029. with porcelain.open_repo_closing(".") as r:
  1030. bad_ref = os.path.join(r.controldir(), "refs", "bisect", "bad")
  1031. with open(bad_ref, "rb") as f:
  1032. bad_sha = f.read().strip()
  1033. commit = r.object_store[bad_sha]
  1034. message = commit.message.decode(
  1035. "utf-8", errors="replace"
  1036. ).split("\n")[0]
  1037. print(f"{bad_sha.decode('ascii')} is the first bad commit")
  1038. print(f"commit {bad_sha.decode('ascii')}")
  1039. print(f" {message}")
  1040. elif parsed_args.subcommand == "good":
  1041. next_sha = porcelain.bisect_good(rev=parsed_args.rev)
  1042. if next_sha:
  1043. print(f"Bisecting: checking out '{next_sha.decode('ascii')}'")
  1044. elif parsed_args.subcommand == "skip":
  1045. next_sha = porcelain.bisect_skip(
  1046. revs=parsed_args.revs if parsed_args.revs else None
  1047. )
  1048. if next_sha:
  1049. print(f"Bisecting: checking out '{next_sha.decode('ascii')}'")
  1050. elif parsed_args.subcommand == "reset":
  1051. porcelain.bisect_reset(commit=parsed_args.commit)
  1052. print("Bisect reset")
  1053. elif parsed_args.subcommand == "log":
  1054. log = porcelain.bisect_log()
  1055. print(log, end="")
  1056. elif parsed_args.subcommand == "replay":
  1057. porcelain.bisect_replay(log_file=parsed_args.logfile)
  1058. print(f"Replayed bisect log from {parsed_args.logfile}")
  1059. elif parsed_args.subcommand == "help":
  1060. parser.print_help()
  1061. except porcelain.Error as e:
  1062. print(f"Error: {e}", file=sys.stderr)
  1063. return 1
  1064. except ValueError as e:
  1065. print(f"Error: {e}", file=sys.stderr)
  1066. return 1
  1067. return 0
  1068. class cmd_stash(SuperCommand):
  1069. subcommands: ClassVar[dict[str, type[Command]]] = {
  1070. "list": cmd_stash_list,
  1071. "pop": cmd_stash_pop,
  1072. "push": cmd_stash_push,
  1073. }
  1074. class cmd_ls_files(Command):
  1075. def run(self, args) -> None:
  1076. parser = argparse.ArgumentParser()
  1077. parser.parse_args(args)
  1078. for name in porcelain.ls_files("."):
  1079. print(name)
  1080. class cmd_describe(Command):
  1081. def run(self, args) -> None:
  1082. parser = argparse.ArgumentParser()
  1083. parser.parse_args(args)
  1084. print(porcelain.describe("."))
  1085. class cmd_merge(Command):
  1086. def run(self, args) -> Optional[int]:
  1087. parser = argparse.ArgumentParser()
  1088. parser.add_argument("commit", type=str, help="Commit to merge")
  1089. parser.add_argument(
  1090. "--no-commit", action="store_true", help="Do not create a merge commit"
  1091. )
  1092. parser.add_argument(
  1093. "--no-ff", action="store_true", help="Force create a merge commit"
  1094. )
  1095. parser.add_argument("-m", "--message", type=str, help="Merge commit message")
  1096. args = parser.parse_args(args)
  1097. try:
  1098. merge_commit_id, conflicts = porcelain.merge(
  1099. ".",
  1100. args.commit,
  1101. no_commit=args.no_commit,
  1102. no_ff=args.no_ff,
  1103. message=args.message,
  1104. )
  1105. if conflicts:
  1106. print(f"Merge conflicts in {len(conflicts)} file(s):")
  1107. for conflict_path in conflicts:
  1108. print(f" {conflict_path.decode()}")
  1109. print(
  1110. "\nAutomatic merge failed; fix conflicts and then commit the result."
  1111. )
  1112. return 1
  1113. elif merge_commit_id is None and not args.no_commit:
  1114. print("Already up to date.")
  1115. elif args.no_commit:
  1116. print("Automatic merge successful; not committing as requested.")
  1117. else:
  1118. print(
  1119. f"Merge successful. Created merge commit {merge_commit_id.decode()}"
  1120. )
  1121. return 0
  1122. except porcelain.Error as e:
  1123. print(f"Error: {e}")
  1124. return 1
  1125. class cmd_notes_add(Command):
  1126. def run(self, args) -> None:
  1127. parser = argparse.ArgumentParser()
  1128. parser.add_argument("object", help="Object to annotate")
  1129. parser.add_argument("-m", "--message", help="Note message", required=True)
  1130. parser.add_argument(
  1131. "--ref", default="commits", help="Notes ref (default: commits)"
  1132. )
  1133. args = parser.parse_args(args)
  1134. porcelain.notes_add(".", args.object, args.message, ref=args.ref)
  1135. class cmd_notes_show(Command):
  1136. def run(self, args) -> None:
  1137. parser = argparse.ArgumentParser()
  1138. parser.add_argument("object", help="Object to show notes for")
  1139. parser.add_argument(
  1140. "--ref", default="commits", help="Notes ref (default: commits)"
  1141. )
  1142. args = parser.parse_args(args)
  1143. note = porcelain.notes_show(".", args.object, ref=args.ref)
  1144. if note:
  1145. sys.stdout.buffer.write(note)
  1146. else:
  1147. print(f"No notes found for object {args.object}")
  1148. class cmd_notes_remove(Command):
  1149. def run(self, args) -> None:
  1150. parser = argparse.ArgumentParser()
  1151. parser.add_argument("object", help="Object to remove notes from")
  1152. parser.add_argument(
  1153. "--ref", default="commits", help="Notes ref (default: commits)"
  1154. )
  1155. args = parser.parse_args(args)
  1156. result = porcelain.notes_remove(".", args.object, ref=args.ref)
  1157. if result:
  1158. print(f"Removed notes for object {args.object}")
  1159. else:
  1160. print(f"No notes found for object {args.object}")
  1161. class cmd_notes_list(Command):
  1162. def run(self, args) -> None:
  1163. parser = argparse.ArgumentParser()
  1164. parser.add_argument(
  1165. "--ref", default="commits", help="Notes ref (default: commits)"
  1166. )
  1167. args = parser.parse_args(args)
  1168. notes = porcelain.notes_list(".", ref=args.ref)
  1169. for object_sha, note_content in notes:
  1170. print(f"{object_sha.hex()}")
  1171. class cmd_notes(SuperCommand):
  1172. subcommands: ClassVar[dict[str, type[Command]]] = {
  1173. "add": cmd_notes_add,
  1174. "show": cmd_notes_show,
  1175. "remove": cmd_notes_remove,
  1176. "list": cmd_notes_list,
  1177. }
  1178. default_command = cmd_notes_list
  1179. class cmd_cherry_pick(Command):
  1180. def run(self, args) -> Optional[int]:
  1181. parser = argparse.ArgumentParser(
  1182. description="Apply the changes introduced by some existing commits"
  1183. )
  1184. parser.add_argument("commit", nargs="?", help="Commit to cherry-pick")
  1185. parser.add_argument(
  1186. "-n",
  1187. "--no-commit",
  1188. action="store_true",
  1189. help="Apply changes without making a commit",
  1190. )
  1191. parser.add_argument(
  1192. "--continue",
  1193. dest="continue_",
  1194. action="store_true",
  1195. help="Continue after resolving conflicts",
  1196. )
  1197. parser.add_argument(
  1198. "--abort",
  1199. action="store_true",
  1200. help="Abort the current cherry-pick operation",
  1201. )
  1202. args = parser.parse_args(args)
  1203. # Check argument validity
  1204. if args.continue_ or args.abort:
  1205. if args.commit is not None:
  1206. parser.error("Cannot specify commit with --continue or --abort")
  1207. return 1
  1208. else:
  1209. if args.commit is None:
  1210. parser.error("Commit argument is required")
  1211. return 1
  1212. try:
  1213. commit_arg = args.commit
  1214. result = porcelain.cherry_pick(
  1215. ".",
  1216. commit_arg,
  1217. no_commit=args.no_commit,
  1218. continue_=args.continue_,
  1219. abort=args.abort,
  1220. )
  1221. if args.abort:
  1222. print("Cherry-pick aborted.")
  1223. elif args.continue_:
  1224. if result:
  1225. print(f"Cherry-pick completed: {result.decode()}")
  1226. else:
  1227. print("Cherry-pick completed.")
  1228. elif result is None:
  1229. if args.no_commit:
  1230. print("Cherry-pick applied successfully (no commit created).")
  1231. else:
  1232. # This shouldn't happen unless there were conflicts
  1233. print("Cherry-pick resulted in conflicts.")
  1234. else:
  1235. print(f"Cherry-pick successful: {result.decode()}")
  1236. return None
  1237. except porcelain.Error as e:
  1238. print(f"Error: {e}", file=sys.stderr)
  1239. return 1
  1240. class cmd_merge_tree(Command):
  1241. def run(self, args) -> Optional[int]:
  1242. parser = argparse.ArgumentParser(
  1243. description="Perform a tree-level merge without touching the working directory"
  1244. )
  1245. parser.add_argument(
  1246. "base_tree",
  1247. nargs="?",
  1248. help="The common ancestor tree (optional, defaults to empty tree)",
  1249. )
  1250. parser.add_argument("our_tree", help="Our side of the merge")
  1251. parser.add_argument("their_tree", help="Their side of the merge")
  1252. parser.add_argument(
  1253. "-z",
  1254. "--name-only",
  1255. action="store_true",
  1256. help="Output only conflict paths, null-terminated",
  1257. )
  1258. args = parser.parse_args(args)
  1259. try:
  1260. # Determine base tree - if only two args provided, base is None
  1261. if args.base_tree is None:
  1262. # Only two arguments provided
  1263. base_tree = None
  1264. our_tree = args.our_tree
  1265. their_tree = args.their_tree
  1266. else:
  1267. # Three arguments provided
  1268. base_tree = args.base_tree
  1269. our_tree = args.our_tree
  1270. their_tree = args.their_tree
  1271. merged_tree_id, conflicts = porcelain.merge_tree(
  1272. ".", base_tree, our_tree, their_tree
  1273. )
  1274. if args.name_only:
  1275. # Output only conflict paths, null-terminated
  1276. for conflict_path in conflicts:
  1277. sys.stdout.buffer.write(conflict_path)
  1278. sys.stdout.buffer.write(b"\0")
  1279. else:
  1280. # Output the merged tree SHA
  1281. print(merged_tree_id.decode("ascii"))
  1282. # Output conflict information
  1283. if conflicts:
  1284. print(f"\nConflicts in {len(conflicts)} file(s):")
  1285. for conflict_path in conflicts:
  1286. print(f" {conflict_path.decode()}")
  1287. return None
  1288. except porcelain.Error as e:
  1289. print(f"Error: {e}", file=sys.stderr)
  1290. return 1
  1291. except KeyError as e:
  1292. print(f"Error: Object not found: {e}", file=sys.stderr)
  1293. return 1
  1294. class cmd_gc(Command):
  1295. def run(self, args) -> Optional[int]:
  1296. import datetime
  1297. import time
  1298. parser = argparse.ArgumentParser()
  1299. parser.add_argument(
  1300. "--auto",
  1301. action="store_true",
  1302. help="Only run gc if needed",
  1303. )
  1304. parser.add_argument(
  1305. "--aggressive",
  1306. action="store_true",
  1307. help="Use more aggressive settings",
  1308. )
  1309. parser.add_argument(
  1310. "--no-prune",
  1311. action="store_true",
  1312. help="Do not prune unreachable objects",
  1313. )
  1314. parser.add_argument(
  1315. "--prune",
  1316. nargs="?",
  1317. const="now",
  1318. help="Prune unreachable objects older than date (default: 2 weeks ago)",
  1319. )
  1320. parser.add_argument(
  1321. "--dry-run",
  1322. "-n",
  1323. action="store_true",
  1324. help="Only report what would be done",
  1325. )
  1326. parser.add_argument(
  1327. "--quiet",
  1328. "-q",
  1329. action="store_true",
  1330. help="Only report errors",
  1331. )
  1332. args = parser.parse_args(args)
  1333. # Parse prune grace period
  1334. grace_period = None
  1335. if args.prune:
  1336. try:
  1337. grace_period = parse_relative_time(args.prune)
  1338. except ValueError:
  1339. # Try to parse as absolute date
  1340. try:
  1341. date = datetime.datetime.strptime(args.prune, "%Y-%m-%d")
  1342. grace_period = int(time.time() - date.timestamp())
  1343. except ValueError:
  1344. print(f"Error: Invalid prune date: {args.prune}")
  1345. return 1
  1346. elif not args.no_prune:
  1347. # Default to 2 weeks
  1348. grace_period = 1209600
  1349. # Progress callback
  1350. def progress(msg):
  1351. if not args.quiet:
  1352. print(msg)
  1353. try:
  1354. stats = porcelain.gc(
  1355. ".",
  1356. auto=args.auto,
  1357. aggressive=args.aggressive,
  1358. prune=not args.no_prune,
  1359. grace_period=grace_period,
  1360. dry_run=args.dry_run,
  1361. progress=progress if not args.quiet else None,
  1362. )
  1363. # Report results
  1364. if not args.quiet:
  1365. if args.dry_run:
  1366. print("\nDry run results:")
  1367. else:
  1368. print("\nGarbage collection complete:")
  1369. if stats.pruned_objects:
  1370. print(f" Pruned {len(stats.pruned_objects)} unreachable objects")
  1371. print(f" Freed {format_bytes(stats.bytes_freed)}")
  1372. if stats.packs_before != stats.packs_after:
  1373. print(
  1374. f" Reduced pack files from {stats.packs_before} to {stats.packs_after}"
  1375. )
  1376. except porcelain.Error as e:
  1377. print(f"Error: {e}")
  1378. return 1
  1379. return None
  1380. class cmd_count_objects(Command):
  1381. def run(self, args) -> None:
  1382. parser = argparse.ArgumentParser()
  1383. parser.add_argument(
  1384. "-v",
  1385. "--verbose",
  1386. action="store_true",
  1387. help="Display verbose information.",
  1388. )
  1389. args = parser.parse_args(args)
  1390. if args.verbose:
  1391. stats = porcelain.count_objects(".", verbose=True)
  1392. # Display verbose output
  1393. print(f"count: {stats.count}")
  1394. print(f"size: {stats.size // 1024}") # Size in KiB
  1395. assert stats.in_pack is not None
  1396. print(f"in-pack: {stats.in_pack}")
  1397. assert stats.packs is not None
  1398. print(f"packs: {stats.packs}")
  1399. assert stats.size_pack is not None
  1400. print(f"size-pack: {stats.size_pack // 1024}") # Size in KiB
  1401. else:
  1402. # Simple output
  1403. stats = porcelain.count_objects(".", verbose=False)
  1404. print(f"{stats.count} objects, {stats.size // 1024} kilobytes")
  1405. class cmd_rebase(Command):
  1406. def run(self, args) -> int:
  1407. parser = argparse.ArgumentParser()
  1408. parser.add_argument(
  1409. "upstream", nargs="?", help="Upstream branch to rebase onto"
  1410. )
  1411. parser.add_argument("--onto", type=str, help="Rebase onto specific commit")
  1412. parser.add_argument(
  1413. "--branch", type=str, help="Branch to rebase (default: current)"
  1414. )
  1415. parser.add_argument(
  1416. "--abort", action="store_true", help="Abort an in-progress rebase"
  1417. )
  1418. parser.add_argument(
  1419. "--continue",
  1420. dest="continue_rebase",
  1421. action="store_true",
  1422. help="Continue an in-progress rebase",
  1423. )
  1424. parser.add_argument(
  1425. "--skip", action="store_true", help="Skip current commit and continue"
  1426. )
  1427. args = parser.parse_args(args)
  1428. # Handle abort/continue/skip first
  1429. if args.abort:
  1430. try:
  1431. porcelain.rebase(".", args.upstream or "HEAD", abort=True)
  1432. print("Rebase aborted.")
  1433. except porcelain.Error as e:
  1434. print(f"Error: {e}")
  1435. return 1
  1436. return 0
  1437. if args.continue_rebase:
  1438. try:
  1439. new_shas = porcelain.rebase(
  1440. ".", args.upstream or "HEAD", continue_rebase=True
  1441. )
  1442. print("Rebase complete.")
  1443. except porcelain.Error as e:
  1444. print(f"Error: {e}")
  1445. return 1
  1446. return 0
  1447. # Normal rebase requires upstream
  1448. if not args.upstream:
  1449. print("Error: Missing required argument 'upstream'")
  1450. return 1
  1451. try:
  1452. new_shas = porcelain.rebase(
  1453. ".",
  1454. args.upstream,
  1455. onto=args.onto,
  1456. branch=args.branch,
  1457. )
  1458. if new_shas:
  1459. print(f"Successfully rebased {len(new_shas)} commits.")
  1460. else:
  1461. print("Already up to date.")
  1462. return 0
  1463. except porcelain.Error as e:
  1464. print(f"Error: {e}")
  1465. return 1
  1466. class cmd_filter_branch(Command):
  1467. def run(self, args) -> Optional[int]:
  1468. import subprocess
  1469. parser = argparse.ArgumentParser(description="Rewrite branches")
  1470. # Supported Git-compatible options
  1471. parser.add_argument(
  1472. "--subdirectory-filter",
  1473. type=str,
  1474. help="Only include history for subdirectory",
  1475. )
  1476. parser.add_argument("--env-filter", type=str, help="Environment filter command")
  1477. parser.add_argument("--tree-filter", type=str, help="Tree filter command")
  1478. parser.add_argument("--index-filter", type=str, help="Index filter command")
  1479. parser.add_argument("--parent-filter", type=str, help="Parent filter command")
  1480. parser.add_argument("--msg-filter", type=str, help="Message filter command")
  1481. parser.add_argument("--commit-filter", type=str, help="Commit filter command")
  1482. parser.add_argument(
  1483. "--tag-name-filter", type=str, help="Tag name filter command"
  1484. )
  1485. parser.add_argument(
  1486. "--prune-empty", action="store_true", help="Remove empty commits"
  1487. )
  1488. parser.add_argument(
  1489. "--original",
  1490. type=str,
  1491. default="refs/original",
  1492. help="Namespace for original refs",
  1493. )
  1494. parser.add_argument(
  1495. "-f",
  1496. "--force",
  1497. action="store_true",
  1498. help="Force operation even if refs/original/* exists",
  1499. )
  1500. # Branch/ref to rewrite (defaults to HEAD)
  1501. parser.add_argument(
  1502. "branch", nargs="?", default="HEAD", help="Branch or ref to rewrite"
  1503. )
  1504. args = parser.parse_args(args)
  1505. # Track if any filter fails
  1506. filter_error = False
  1507. # Setup environment for filters
  1508. env = os.environ.copy()
  1509. # Helper function to run shell commands
  1510. def run_filter(cmd, input_data=None, cwd=None, extra_env=None):
  1511. nonlocal filter_error
  1512. filter_env = env.copy()
  1513. if extra_env:
  1514. filter_env.update(extra_env)
  1515. result = subprocess.run(
  1516. cmd,
  1517. shell=True,
  1518. input=input_data,
  1519. cwd=cwd,
  1520. env=filter_env,
  1521. capture_output=True,
  1522. )
  1523. if result.returncode != 0:
  1524. filter_error = True
  1525. return None
  1526. return result.stdout
  1527. # Create filter functions based on arguments
  1528. filter_message = None
  1529. if args.msg_filter:
  1530. def filter_message(message):
  1531. result = run_filter(args.msg_filter, input_data=message)
  1532. return result if result is not None else message
  1533. tree_filter = None
  1534. if args.tree_filter:
  1535. def tree_filter(tree_sha, tmpdir):
  1536. from dulwich.objects import Blob, Tree
  1537. # Export tree to tmpdir
  1538. with Repo(".") as r:
  1539. tree = r.object_store[tree_sha]
  1540. for entry in tree.items():
  1541. path = Path(tmpdir) / entry.path.decode()
  1542. if entry.mode & 0o040000: # Directory
  1543. path.mkdir(exist_ok=True)
  1544. else:
  1545. obj = r.object_store[entry.sha]
  1546. path.write_bytes(obj.data)
  1547. # Run the filter command in the temp directory
  1548. run_filter(args.tree_filter, cwd=tmpdir)
  1549. # Rebuild tree from modified temp directory
  1550. def build_tree_from_dir(dir_path):
  1551. tree = Tree()
  1552. for name in sorted(os.listdir(dir_path)):
  1553. if name.startswith("."):
  1554. continue
  1555. path = os.path.join(dir_path, name)
  1556. if os.path.isdir(path):
  1557. subtree_sha = build_tree_from_dir(path)
  1558. tree.add(name.encode(), 0o040000, subtree_sha)
  1559. else:
  1560. with open(path, "rb") as f:
  1561. data = f.read()
  1562. blob = Blob.from_string(data)
  1563. r.object_store.add_object(blob)
  1564. # Use appropriate file mode
  1565. mode = os.stat(path).st_mode
  1566. if mode & 0o100:
  1567. file_mode = 0o100755
  1568. else:
  1569. file_mode = 0o100644
  1570. tree.add(name.encode(), file_mode, blob.id)
  1571. r.object_store.add_object(tree)
  1572. return tree.id
  1573. return build_tree_from_dir(tmpdir)
  1574. index_filter = None
  1575. if args.index_filter:
  1576. def index_filter(tree_sha, index_path):
  1577. run_filter(args.index_filter, extra_env={"GIT_INDEX_FILE": index_path})
  1578. return None # Read back from index
  1579. parent_filter = None
  1580. if args.parent_filter:
  1581. def parent_filter(parents):
  1582. parent_str = " ".join(p.hex() for p in parents)
  1583. result = run_filter(args.parent_filter, input_data=parent_str.encode())
  1584. if result is None:
  1585. return parents
  1586. output = result.decode().strip()
  1587. if not output:
  1588. return []
  1589. new_parents = []
  1590. for sha in output.split():
  1591. if valid_hexsha(sha):
  1592. new_parents.append(sha)
  1593. return new_parents
  1594. commit_filter = None
  1595. if args.commit_filter:
  1596. def commit_filter(commit_obj, tree_sha):
  1597. # The filter receives: tree parent1 parent2...
  1598. cmd_input = tree_sha.hex()
  1599. for parent in commit_obj.parents:
  1600. cmd_input += " " + parent.hex()
  1601. result = run_filter(
  1602. args.commit_filter,
  1603. input_data=cmd_input.encode(),
  1604. extra_env={"GIT_COMMIT": commit_obj.id.hex()},
  1605. )
  1606. if result is None:
  1607. return None
  1608. output = result.decode().strip()
  1609. if not output:
  1610. return None # Skip commit
  1611. if valid_hexsha(output):
  1612. return output
  1613. return None
  1614. tag_name_filter = None
  1615. if args.tag_name_filter:
  1616. def tag_name_filter(tag_name):
  1617. result = run_filter(args.tag_name_filter, input_data=tag_name)
  1618. return result.strip() if result is not None else tag_name
  1619. # Open repo once
  1620. with Repo(".") as r:
  1621. # Check for refs/original if not forcing
  1622. if not args.force:
  1623. original_prefix = args.original.encode() + b"/"
  1624. for ref in r.refs.allkeys():
  1625. if ref.startswith(original_prefix):
  1626. print("Cannot create a new backup.")
  1627. print(f"A previous backup already exists in {args.original}/")
  1628. print("Force overwriting the backup with -f")
  1629. return 1
  1630. try:
  1631. # Call porcelain.filter_branch with the repo object
  1632. result = porcelain.filter_branch(
  1633. r,
  1634. args.branch,
  1635. filter_message=filter_message,
  1636. tree_filter=tree_filter if args.tree_filter else None,
  1637. index_filter=index_filter if args.index_filter else None,
  1638. parent_filter=parent_filter if args.parent_filter else None,
  1639. commit_filter=commit_filter if args.commit_filter else None,
  1640. subdirectory_filter=args.subdirectory_filter,
  1641. prune_empty=args.prune_empty,
  1642. tag_name_filter=tag_name_filter if args.tag_name_filter else None,
  1643. force=args.force,
  1644. keep_original=True, # Always keep original with git
  1645. )
  1646. # Check if any filter failed
  1647. if filter_error:
  1648. print("Error: Filter command failed", file=sys.stderr)
  1649. return 1
  1650. # Git filter-branch shows progress
  1651. if result:
  1652. print(f"Rewrite {args.branch} ({len(result)} commits)")
  1653. # Git shows: Ref 'refs/heads/branch' was rewritten
  1654. if args.branch != "HEAD":
  1655. ref_name = (
  1656. args.branch
  1657. if args.branch.startswith("refs/")
  1658. else f"refs/heads/{args.branch}"
  1659. )
  1660. print(f"Ref '{ref_name}' was rewritten")
  1661. return 0
  1662. except porcelain.Error as e:
  1663. print(f"Error: {e}", file=sys.stderr)
  1664. return 1
  1665. class cmd_lfs(Command):
  1666. """Git LFS management commands."""
  1667. def run(self, argv) -> None:
  1668. parser = argparse.ArgumentParser(prog="dulwich lfs")
  1669. subparsers = parser.add_subparsers(dest="subcommand", help="LFS subcommands")
  1670. # lfs init
  1671. subparsers.add_parser("init", help="Initialize Git LFS")
  1672. # lfs track
  1673. parser_track = subparsers.add_parser(
  1674. "track", help="Track file patterns with LFS"
  1675. )
  1676. parser_track.add_argument("patterns", nargs="*", help="File patterns to track")
  1677. # lfs untrack
  1678. parser_untrack = subparsers.add_parser(
  1679. "untrack", help="Untrack file patterns from LFS"
  1680. )
  1681. parser_untrack.add_argument(
  1682. "patterns", nargs="+", help="File patterns to untrack"
  1683. )
  1684. # lfs ls-files
  1685. parser_ls = subparsers.add_parser("ls-files", help="List LFS files")
  1686. parser_ls.add_argument("--ref", help="Git ref to check (defaults to HEAD)")
  1687. # lfs migrate
  1688. parser_migrate = subparsers.add_parser("migrate", help="Migrate files to LFS")
  1689. parser_migrate.add_argument("--include", nargs="+", help="Patterns to include")
  1690. parser_migrate.add_argument("--exclude", nargs="+", help="Patterns to exclude")
  1691. parser_migrate.add_argument(
  1692. "--everything", action="store_true", help="Migrate all files above 100MB"
  1693. )
  1694. # lfs pointer
  1695. parser_pointer = subparsers.add_parser("pointer", help="Check LFS pointers")
  1696. parser_pointer.add_argument(
  1697. "--check", nargs="*", dest="paths", help="Check if files are LFS pointers"
  1698. )
  1699. # lfs clean
  1700. parser_clean = subparsers.add_parser("clean", help="Clean file to LFS pointer")
  1701. parser_clean.add_argument("path", help="File path to clean")
  1702. # lfs smudge
  1703. parser_smudge = subparsers.add_parser(
  1704. "smudge", help="Smudge LFS pointer to content"
  1705. )
  1706. parser_smudge.add_argument(
  1707. "--stdin", action="store_true", help="Read pointer from stdin"
  1708. )
  1709. # lfs fetch
  1710. parser_fetch = subparsers.add_parser(
  1711. "fetch", help="Fetch LFS objects from remote"
  1712. )
  1713. parser_fetch.add_argument(
  1714. "--remote", default="origin", help="Remote to fetch from"
  1715. )
  1716. parser_fetch.add_argument("refs", nargs="*", help="Specific refs to fetch")
  1717. # lfs pull
  1718. parser_pull = subparsers.add_parser(
  1719. "pull", help="Pull LFS objects for current checkout"
  1720. )
  1721. parser_pull.add_argument(
  1722. "--remote", default="origin", help="Remote to pull from"
  1723. )
  1724. # lfs push
  1725. parser_push = subparsers.add_parser("push", help="Push LFS objects to remote")
  1726. parser_push.add_argument("--remote", default="origin", help="Remote to push to")
  1727. parser_push.add_argument("refs", nargs="*", help="Specific refs to push")
  1728. # lfs status
  1729. subparsers.add_parser("status", help="Show status of LFS files")
  1730. args = parser.parse_args(argv)
  1731. if args.subcommand == "init":
  1732. porcelain.lfs_init()
  1733. print("Git LFS initialized.")
  1734. elif args.subcommand == "track":
  1735. if args.patterns:
  1736. tracked = porcelain.lfs_track(patterns=args.patterns)
  1737. print("Tracking patterns:")
  1738. else:
  1739. tracked = porcelain.lfs_track()
  1740. print("Currently tracked patterns:")
  1741. for pattern in tracked:
  1742. print(f" {pattern}")
  1743. elif args.subcommand == "untrack":
  1744. tracked = porcelain.lfs_untrack(patterns=args.patterns)
  1745. print("Remaining tracked patterns:")
  1746. for pattern in tracked:
  1747. print(f" {pattern}")
  1748. elif args.subcommand == "ls-files":
  1749. files = porcelain.lfs_ls_files(ref=args.ref)
  1750. for path, oid, size in files:
  1751. print(f"{oid[:12]} * {path} ({format_bytes(size)})")
  1752. elif args.subcommand == "migrate":
  1753. count = porcelain.lfs_migrate(
  1754. include=args.include, exclude=args.exclude, everything=args.everything
  1755. )
  1756. print(f"Migrated {count} file(s) to Git LFS.")
  1757. elif args.subcommand == "pointer":
  1758. if args.paths is not None:
  1759. results = porcelain.lfs_pointer_check(paths=args.paths or None)
  1760. for path, pointer in results.items():
  1761. if pointer:
  1762. print(
  1763. f"{path}: LFS pointer (oid: {pointer.oid[:12]}, size: {format_bytes(pointer.size)})"
  1764. )
  1765. else:
  1766. print(f"{path}: Not an LFS pointer")
  1767. elif args.subcommand == "clean":
  1768. pointer = porcelain.lfs_clean(path=args.path)
  1769. sys.stdout.buffer.write(pointer)
  1770. elif args.subcommand == "smudge":
  1771. if args.stdin:
  1772. pointer_content = sys.stdin.buffer.read()
  1773. content = porcelain.lfs_smudge(pointer_content=pointer_content)
  1774. sys.stdout.buffer.write(content)
  1775. else:
  1776. print("Error: --stdin required for smudge command")
  1777. sys.exit(1)
  1778. elif args.subcommand == "fetch":
  1779. refs = args.refs or None
  1780. count = porcelain.lfs_fetch(remote=args.remote, refs=refs)
  1781. print(f"Fetched {count} LFS object(s).")
  1782. elif args.subcommand == "pull":
  1783. count = porcelain.lfs_pull(remote=args.remote)
  1784. print(f"Pulled {count} LFS object(s).")
  1785. elif args.subcommand == "push":
  1786. refs = args.refs or None
  1787. count = porcelain.lfs_push(remote=args.remote, refs=refs)
  1788. print(f"Pushed {count} LFS object(s).")
  1789. elif args.subcommand == "status":
  1790. status = porcelain.lfs_status()
  1791. if status["tracked"]:
  1792. print(f"LFS tracked files: {len(status['tracked'])}")
  1793. if status["missing"]:
  1794. print("\nMissing LFS objects:")
  1795. for path in status["missing"]:
  1796. print(f" {path}")
  1797. if status["not_staged"]:
  1798. print("\nModified LFS files not staged:")
  1799. for path in status["not_staged"]:
  1800. print(f" {path}")
  1801. if not any(status.values()):
  1802. print("No LFS files found.")
  1803. else:
  1804. parser.print_help()
  1805. sys.exit(1)
  1806. class cmd_help(Command):
  1807. def run(self, args) -> None:
  1808. parser = argparse.ArgumentParser()
  1809. parser.add_argument(
  1810. "-a",
  1811. "--all",
  1812. action="store_true",
  1813. help="List all commands.",
  1814. )
  1815. args = parser.parse_args(args)
  1816. if args.all:
  1817. print("Available commands:")
  1818. for cmd in sorted(commands):
  1819. print(f" {cmd}")
  1820. else:
  1821. print(
  1822. """\
  1823. The dulwich command line tool is currently a very basic frontend for the
  1824. Dulwich python module. For full functionality, please see the API reference.
  1825. For a list of supported commands, see 'dulwich help -a'.
  1826. """
  1827. )
  1828. class cmd_format_patch(Command):
  1829. def run(self, args) -> None:
  1830. parser = argparse.ArgumentParser()
  1831. parser.add_argument(
  1832. "committish",
  1833. nargs="?",
  1834. help="Commit or commit range (e.g., HEAD~3..HEAD or origin/master..HEAD)",
  1835. )
  1836. parser.add_argument(
  1837. "-n",
  1838. "--numbered",
  1839. type=int,
  1840. default=1,
  1841. help="Number of commits to format (default: 1)",
  1842. )
  1843. parser.add_argument(
  1844. "-o",
  1845. "--output-directory",
  1846. dest="outdir",
  1847. help="Output directory for patches",
  1848. )
  1849. parser.add_argument(
  1850. "--stdout",
  1851. action="store_true",
  1852. help="Output patches to stdout",
  1853. )
  1854. args = parser.parse_args(args)
  1855. # Parse committish using the new function
  1856. committish = None
  1857. if args.committish:
  1858. with Repo(".") as r:
  1859. range_result = parse_committish_range(r, args.committish)
  1860. if range_result:
  1861. committish = range_result
  1862. else:
  1863. committish = args.committish
  1864. filenames = porcelain.format_patch(
  1865. ".",
  1866. committish=committish,
  1867. outstream=sys.stdout,
  1868. outdir=args.outdir,
  1869. n=args.numbered,
  1870. stdout=args.stdout,
  1871. )
  1872. if not args.stdout:
  1873. for filename in filenames:
  1874. print(filename)
  1875. class cmd_bundle(Command):
  1876. def run(self, args) -> int:
  1877. if not args:
  1878. print("Usage: bundle <create|verify|list-heads|unbundle> <options>")
  1879. return 1
  1880. subcommand = args[0]
  1881. subargs = args[1:]
  1882. if subcommand == "create":
  1883. return self._create(subargs)
  1884. elif subcommand == "verify":
  1885. return self._verify(subargs)
  1886. elif subcommand == "list-heads":
  1887. return self._list_heads(subargs)
  1888. elif subcommand == "unbundle":
  1889. return self._unbundle(subargs)
  1890. else:
  1891. print(f"Unknown bundle subcommand: {subcommand}")
  1892. return 1
  1893. def _create(self, args) -> int:
  1894. parser = argparse.ArgumentParser(prog="bundle create")
  1895. parser.add_argument(
  1896. "-q", "--quiet", action="store_true", help="Suppress progress"
  1897. )
  1898. parser.add_argument("--progress", action="store_true", help="Show progress")
  1899. parser.add_argument(
  1900. "--version", type=int, choices=[2, 3], help="Bundle version"
  1901. )
  1902. parser.add_argument("--all", action="store_true", help="Include all refs")
  1903. parser.add_argument("--stdin", action="store_true", help="Read refs from stdin")
  1904. parser.add_argument("file", help="Output bundle file (use - for stdout)")
  1905. parser.add_argument("refs", nargs="*", help="References or rev-list args")
  1906. parsed_args = parser.parse_args(args)
  1907. repo = Repo(".")
  1908. progress = None
  1909. if parsed_args.progress and not parsed_args.quiet:
  1910. def progress(msg: str) -> None:
  1911. print(msg, file=sys.stderr)
  1912. refs_to_include = []
  1913. prerequisites = []
  1914. if parsed_args.all:
  1915. refs_to_include = list(repo.refs.keys())
  1916. elif parsed_args.stdin:
  1917. for line in sys.stdin:
  1918. ref = line.strip().encode("utf-8")
  1919. if ref:
  1920. refs_to_include.append(ref)
  1921. elif parsed_args.refs:
  1922. for ref_arg in parsed_args.refs:
  1923. if ".." in ref_arg:
  1924. range_result = parse_committish_range(repo, ref_arg)
  1925. if range_result:
  1926. start_commit, end_commit = range_result
  1927. prerequisites.append(start_commit)
  1928. # For ranges like A..B, we need to include B if it's a ref
  1929. # Split the range to get the end part
  1930. end_part = ref_arg.split("..")[1]
  1931. if end_part: # Not empty (not "A..")
  1932. end_ref = end_part.encode("utf-8")
  1933. if end_ref in repo.refs:
  1934. refs_to_include.append(end_ref)
  1935. else:
  1936. sha = repo.refs[ref_arg.encode("utf-8")]
  1937. refs_to_include.append(ref_arg.encode("utf-8"))
  1938. else:
  1939. if ref_arg.startswith("^"):
  1940. sha = repo.refs[ref_arg[1:].encode("utf-8")]
  1941. prerequisites.append(sha)
  1942. else:
  1943. sha = repo.refs[ref_arg.encode("utf-8")]
  1944. refs_to_include.append(ref_arg.encode("utf-8"))
  1945. else:
  1946. print("No refs specified. Use --all, --stdin, or specify refs")
  1947. return 1
  1948. if not refs_to_include:
  1949. print("fatal: Refusing to create empty bundle.")
  1950. return 1
  1951. bundle = create_bundle_from_repo(
  1952. repo,
  1953. refs=refs_to_include,
  1954. prerequisites=prerequisites,
  1955. version=parsed_args.version,
  1956. progress=progress,
  1957. )
  1958. if parsed_args.file == "-":
  1959. write_bundle(sys.stdout.buffer, bundle)
  1960. else:
  1961. with open(parsed_args.file, "wb") as f:
  1962. write_bundle(f, bundle)
  1963. return 0
  1964. def _verify(self, args) -> int:
  1965. parser = argparse.ArgumentParser(prog="bundle verify")
  1966. parser.add_argument(
  1967. "-q", "--quiet", action="store_true", help="Suppress output"
  1968. )
  1969. parser.add_argument("file", help="Bundle file to verify (use - for stdin)")
  1970. parsed_args = parser.parse_args(args)
  1971. repo = Repo(".")
  1972. def verify_bundle(bundle):
  1973. missing_prereqs = []
  1974. for prereq_sha, comment in bundle.prerequisites:
  1975. try:
  1976. repo.object_store[prereq_sha]
  1977. except KeyError:
  1978. missing_prereqs.append(prereq_sha)
  1979. if missing_prereqs:
  1980. if not parsed_args.quiet:
  1981. print("The bundle requires these prerequisite commits:")
  1982. for sha in missing_prereqs:
  1983. print(f" {sha.decode()}")
  1984. return 1
  1985. else:
  1986. if not parsed_args.quiet:
  1987. print(
  1988. "The bundle is valid and can be applied to the current repository"
  1989. )
  1990. return 0
  1991. if parsed_args.file == "-":
  1992. bundle = read_bundle(sys.stdin.buffer)
  1993. return verify_bundle(bundle)
  1994. else:
  1995. with open(parsed_args.file, "rb") as f:
  1996. bundle = read_bundle(f)
  1997. return verify_bundle(bundle)
  1998. def _list_heads(self, args) -> int:
  1999. parser = argparse.ArgumentParser(prog="bundle list-heads")
  2000. parser.add_argument("file", help="Bundle file (use - for stdin)")
  2001. parser.add_argument("refnames", nargs="*", help="Only show these refs")
  2002. parsed_args = parser.parse_args(args)
  2003. def list_heads(bundle):
  2004. for ref, sha in bundle.references.items():
  2005. if not parsed_args.refnames or ref.decode() in parsed_args.refnames:
  2006. print(f"{sha.decode()} {ref.decode()}")
  2007. if parsed_args.file == "-":
  2008. bundle = read_bundle(sys.stdin.buffer)
  2009. list_heads(bundle)
  2010. else:
  2011. with open(parsed_args.file, "rb") as f:
  2012. bundle = read_bundle(f)
  2013. list_heads(bundle)
  2014. return 0
  2015. def _unbundle(self, args) -> int:
  2016. parser = argparse.ArgumentParser(prog="bundle unbundle")
  2017. parser.add_argument("--progress", action="store_true", help="Show progress")
  2018. parser.add_argument("file", help="Bundle file (use - for stdin)")
  2019. parser.add_argument("refnames", nargs="*", help="Only unbundle these refs")
  2020. parsed_args = parser.parse_args(args)
  2021. repo = Repo(".")
  2022. progress = None
  2023. if parsed_args.progress:
  2024. def progress(msg: str) -> None:
  2025. print(msg, file=sys.stderr)
  2026. if parsed_args.file == "-":
  2027. bundle = read_bundle(sys.stdin.buffer)
  2028. # Process the bundle while file is still available via stdin
  2029. bundle.store_objects(repo.object_store, progress=progress)
  2030. else:
  2031. # Keep the file open during bundle processing
  2032. with open(parsed_args.file, "rb") as f:
  2033. bundle = read_bundle(f)
  2034. # Process pack data while file is still open
  2035. bundle.store_objects(repo.object_store, progress=progress)
  2036. for ref, sha in bundle.references.items():
  2037. if not parsed_args.refnames or ref.decode() in parsed_args.refnames:
  2038. print(ref.decode())
  2039. return 0
  2040. commands = {
  2041. "add": cmd_add,
  2042. "annotate": cmd_annotate,
  2043. "archive": cmd_archive,
  2044. "bisect": cmd_bisect,
  2045. "blame": cmd_blame,
  2046. "branch": cmd_branch,
  2047. "bundle": cmd_bundle,
  2048. "check-ignore": cmd_check_ignore,
  2049. "check-mailmap": cmd_check_mailmap,
  2050. "checkout": cmd_checkout,
  2051. "cherry-pick": cmd_cherry_pick,
  2052. "clone": cmd_clone,
  2053. "commit": cmd_commit,
  2054. "commit-tree": cmd_commit_tree,
  2055. "count-objects": cmd_count_objects,
  2056. "describe": cmd_describe,
  2057. "daemon": cmd_daemon,
  2058. "diff": cmd_diff,
  2059. "diff-tree": cmd_diff_tree,
  2060. "dump-pack": cmd_dump_pack,
  2061. "dump-index": cmd_dump_index,
  2062. "fetch-pack": cmd_fetch_pack,
  2063. "fetch": cmd_fetch,
  2064. "filter-branch": cmd_filter_branch,
  2065. "for-each-ref": cmd_for_each_ref,
  2066. "format-patch": cmd_format_patch,
  2067. "fsck": cmd_fsck,
  2068. "gc": cmd_gc,
  2069. "help": cmd_help,
  2070. "init": cmd_init,
  2071. "lfs": cmd_lfs,
  2072. "log": cmd_log,
  2073. "ls-files": cmd_ls_files,
  2074. "ls-remote": cmd_ls_remote,
  2075. "ls-tree": cmd_ls_tree,
  2076. "merge": cmd_merge,
  2077. "merge-tree": cmd_merge_tree,
  2078. "notes": cmd_notes,
  2079. "pack-objects": cmd_pack_objects,
  2080. "pack-refs": cmd_pack_refs,
  2081. "prune": cmd_prune,
  2082. "pull": cmd_pull,
  2083. "push": cmd_push,
  2084. "rebase": cmd_rebase,
  2085. "receive-pack": cmd_receive_pack,
  2086. "reflog": cmd_reflog,
  2087. "remote": cmd_remote,
  2088. "repack": cmd_repack,
  2089. "reset": cmd_reset,
  2090. "revert": cmd_revert,
  2091. "rev-list": cmd_rev_list,
  2092. "rm": cmd_rm,
  2093. "mv": cmd_mv,
  2094. "show": cmd_show,
  2095. "stash": cmd_stash,
  2096. "status": cmd_status,
  2097. "symbolic-ref": cmd_symbolic_ref,
  2098. "submodule": cmd_submodule,
  2099. "tag": cmd_tag,
  2100. "unpack-objects": cmd_unpack_objects,
  2101. "update-server-info": cmd_update_server_info,
  2102. "upload-pack": cmd_upload_pack,
  2103. "web-daemon": cmd_web_daemon,
  2104. "write-tree": cmd_write_tree,
  2105. }
  2106. def main(argv=None) -> Optional[int]:
  2107. if argv is None:
  2108. argv = sys.argv[1:]
  2109. if len(argv) < 1:
  2110. print("Usage: dulwich <{}> [OPTIONS...]".format("|".join(commands.keys())))
  2111. return 1
  2112. cmd = argv[0]
  2113. try:
  2114. cmd_kls = commands[cmd]
  2115. except KeyError:
  2116. print(f"No such subcommand: {cmd}")
  2117. return 1
  2118. # TODO(jelmer): Return non-0 on errors
  2119. return cmd_kls().run(argv[1:])
  2120. def _main() -> None:
  2121. if "DULWICH_PDB" in os.environ and getattr(signal, "SIGQUIT", None):
  2122. signal.signal(signal.SIGQUIT, signal_quit) # type: ignore
  2123. signal.signal(signal.SIGINT, signal_int)
  2124. sys.exit(main())
  2125. if __name__ == "__main__":
  2126. _main()