cli.py 76 KB

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