cli.py 84 KB

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