cli.py 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449
  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 logging
  30. import os
  31. import shutil
  32. import signal
  33. import subprocess
  34. import sys
  35. import tempfile
  36. from pathlib import Path
  37. from typing import Callable, ClassVar, Optional, Union
  38. from dulwich import porcelain
  39. from .bundle import create_bundle_from_repo, read_bundle, write_bundle
  40. from .client import GitProtocolError, get_transport_and_path
  41. from .errors import ApplyDeltaError
  42. from .index import Index
  43. from .objects import valid_hexsha
  44. from .objectspec import parse_commit_range
  45. from .pack import Pack, sha_to_hex
  46. from .repo import Repo
  47. class CommitMessageError(Exception):
  48. """Raised when there's an issue with the commit message."""
  49. def signal_int(signal, frame) -> None:
  50. sys.exit(1)
  51. def signal_quit(signal, frame) -> None:
  52. import pdb
  53. pdb.set_trace()
  54. def parse_relative_time(time_str):
  55. """Parse a relative time string like '2 weeks ago' into seconds.
  56. Args:
  57. time_str: String like '2 weeks ago' or 'now'
  58. Returns:
  59. Number of seconds
  60. Raises:
  61. ValueError: If the time string cannot be parsed
  62. """
  63. if time_str == "now":
  64. return 0
  65. if not time_str.endswith(" ago"):
  66. raise ValueError(f"Invalid relative time format: {time_str}")
  67. parts = time_str[:-4].split()
  68. if len(parts) != 2:
  69. raise ValueError(f"Invalid relative time format: {time_str}")
  70. try:
  71. num = int(parts[0])
  72. unit = parts[1]
  73. multipliers = {
  74. "second": 1,
  75. "seconds": 1,
  76. "minute": 60,
  77. "minutes": 60,
  78. "hour": 3600,
  79. "hours": 3600,
  80. "day": 86400,
  81. "days": 86400,
  82. "week": 604800,
  83. "weeks": 604800,
  84. }
  85. if unit in multipliers:
  86. return num * multipliers[unit]
  87. else:
  88. raise ValueError(f"Unknown time unit: {unit}")
  89. except ValueError as e:
  90. if "invalid literal" in str(e):
  91. raise ValueError(f"Invalid number in relative time: {parts[0]}")
  92. raise
  93. def format_bytes(bytes):
  94. """Format bytes as human-readable string.
  95. Args:
  96. bytes: Number of bytes
  97. Returns:
  98. Human-readable string like "1.5 MB"
  99. """
  100. for unit in ["B", "KB", "MB", "GB"]:
  101. if bytes < 1024.0:
  102. return f"{bytes:.1f} {unit}"
  103. bytes /= 1024.0
  104. return f"{bytes:.1f} TB"
  105. def launch_editor(template_content=b""):
  106. """Launch an editor for the user to enter text.
  107. Args:
  108. template_content: Initial content for the editor
  109. Returns:
  110. The edited content as bytes
  111. """
  112. # Determine which editor to use
  113. editor = os.environ.get("GIT_EDITOR") or os.environ.get("EDITOR") or "vi"
  114. # Create a temporary file
  115. with tempfile.NamedTemporaryFile(mode="wb", delete=False, suffix=".txt") as f:
  116. temp_file = f.name
  117. f.write(template_content)
  118. try:
  119. # Launch the editor
  120. subprocess.run([editor, temp_file], check=True)
  121. # Read the edited content
  122. with open(temp_file, "rb") as f:
  123. content = f.read()
  124. return content
  125. finally:
  126. # Clean up the temporary file
  127. os.unlink(temp_file)
  128. class PagerBuffer:
  129. """Binary buffer wrapper for Pager to mimic sys.stdout.buffer."""
  130. def __init__(self, pager):
  131. self.pager = pager
  132. def write(self, data: bytes):
  133. """Write bytes to pager."""
  134. if isinstance(data, bytes):
  135. text = data.decode("utf-8", errors="replace")
  136. return self.pager.write(text)
  137. return self.pager.write(data)
  138. def flush(self):
  139. """Flush the pager."""
  140. return self.pager.flush()
  141. def writelines(self, lines):
  142. """Write multiple lines to pager."""
  143. for line in lines:
  144. self.write(line)
  145. def readable(self):
  146. """Return whether the buffer is readable (it's not)."""
  147. return False
  148. def writable(self):
  149. """Return whether the buffer is writable."""
  150. return not self.pager._closed
  151. def seekable(self):
  152. """Return whether the buffer is seekable (it's not)."""
  153. return False
  154. def close(self):
  155. """Close the pager."""
  156. return self.pager.close()
  157. @property
  158. def closed(self):
  159. """Return whether the buffer is closed."""
  160. return self.pager.closed
  161. class Pager:
  162. """File-like object that pages output through external pager programs."""
  163. def __init__(self, pager_cmd="cat"):
  164. self.pager_process = None
  165. self.buffer = PagerBuffer(self)
  166. self._closed = False
  167. self.pager_cmd = pager_cmd
  168. self._pager_died = False
  169. def _get_pager_command(self) -> str:
  170. """Get the pager command to use."""
  171. return self.pager_cmd
  172. def _ensure_pager_started(self):
  173. """Start the pager process if not already started."""
  174. if self.pager_process is None and not self._closed:
  175. try:
  176. pager_cmd = self._get_pager_command()
  177. self.pager_process = subprocess.Popen(
  178. pager_cmd,
  179. shell=True,
  180. stdin=subprocess.PIPE,
  181. stdout=sys.stdout,
  182. stderr=sys.stderr,
  183. text=True,
  184. )
  185. except (OSError, subprocess.SubprocessError):
  186. # Pager failed to start, fall back to direct output
  187. self.pager_process = None
  188. def write(self, text: str) -> int:
  189. """Write text to the pager."""
  190. if self._closed:
  191. raise ValueError("I/O operation on closed file")
  192. # If pager died (user quit), stop writing output
  193. if self._pager_died:
  194. return len(text)
  195. self._ensure_pager_started()
  196. if self.pager_process and self.pager_process.stdin:
  197. try:
  198. return self.pager_process.stdin.write(text)
  199. except (OSError, subprocess.SubprocessError, BrokenPipeError):
  200. # Pager died (user quit), stop writing output
  201. self._pager_died = True
  202. return len(text)
  203. else:
  204. # No pager available, write directly to stdout
  205. return sys.stdout.write(text)
  206. def flush(self):
  207. """Flush the pager."""
  208. if self._closed or self._pager_died:
  209. return
  210. if self.pager_process and self.pager_process.stdin:
  211. try:
  212. self.pager_process.stdin.flush()
  213. except (OSError, subprocess.SubprocessError, BrokenPipeError):
  214. self._pager_died = True
  215. else:
  216. sys.stdout.flush()
  217. def close(self):
  218. """Close the pager."""
  219. if self._closed:
  220. return
  221. self._closed = True
  222. if self.pager_process:
  223. try:
  224. if self.pager_process.stdin:
  225. self.pager_process.stdin.close()
  226. self.pager_process.wait()
  227. except (OSError, subprocess.SubprocessError):
  228. pass
  229. self.pager_process = None
  230. def __enter__(self):
  231. """Context manager entry."""
  232. return self
  233. def __exit__(self, exc_type, exc_val, exc_tb):
  234. """Context manager exit."""
  235. self.close()
  236. # Additional file-like methods for compatibility
  237. def writelines(self, lines):
  238. """Write a list of lines to the pager."""
  239. if self._pager_died:
  240. return
  241. for line in lines:
  242. self.write(line)
  243. @property
  244. def closed(self):
  245. """Return whether the pager is closed."""
  246. return self._closed
  247. def readable(self):
  248. """Return whether the pager is readable (it's not)."""
  249. return False
  250. def writable(self):
  251. """Return whether the pager is writable."""
  252. return not self._closed
  253. def seekable(self):
  254. """Return whether the pager is seekable (it's not)."""
  255. return False
  256. class _StreamContextAdapter:
  257. """Adapter to make streams work with context manager protocol."""
  258. def __init__(self, stream):
  259. self.stream = stream
  260. # Expose buffer if it exists
  261. if hasattr(stream, "buffer"):
  262. self.buffer = stream.buffer
  263. else:
  264. self.buffer = stream
  265. def __enter__(self):
  266. return self.stream
  267. def __exit__(self, exc_type, exc_val, exc_tb):
  268. # For stdout/stderr, we don't close them
  269. pass
  270. def __getattr__(self, name):
  271. return getattr(self.stream, name)
  272. def get_pager(config=None, cmd_name=None):
  273. """Get a pager instance if paging should be used, otherwise return sys.stdout.
  274. Args:
  275. config: Optional config instance (e.g., StackedConfig) to read settings from
  276. cmd_name: Optional command name for per-command pager settings
  277. Returns:
  278. Either a wrapped sys.stdout or a Pager instance (both context managers)
  279. """
  280. # Check global pager disable flag
  281. if getattr(get_pager, "_disabled", False):
  282. return _StreamContextAdapter(sys.stdout)
  283. # Don't page if stdout is not a terminal
  284. if not sys.stdout.isatty():
  285. return _StreamContextAdapter(sys.stdout)
  286. # Priority order for pager command (following git's behavior):
  287. # 1. Check pager.<cmd> config (if cmd_name provided)
  288. # 2. Check environment variables: DULWICH_PAGER, GIT_PAGER, PAGER
  289. # 3. Check core.pager config
  290. # 4. Fallback to common pagers
  291. pager_cmd = None
  292. # 1. Check per-command pager config (pager.<cmd>)
  293. if config and cmd_name:
  294. try:
  295. pager_value = config.get(
  296. ("pager",), cmd_name.encode() if isinstance(cmd_name, str) else cmd_name
  297. )
  298. except KeyError:
  299. pass
  300. else:
  301. if pager_value == b"false":
  302. return _StreamContextAdapter(sys.stdout)
  303. elif pager_value != b"true":
  304. # It's a custom pager command
  305. pager_cmd = (
  306. pager_value.decode()
  307. if isinstance(pager_value, bytes)
  308. else pager_value
  309. )
  310. # 2. Check environment variables
  311. if not pager_cmd:
  312. for env_var in ["DULWICH_PAGER", "GIT_PAGER", "PAGER"]:
  313. pager = os.environ.get(env_var)
  314. if pager:
  315. if pager == "false":
  316. return _StreamContextAdapter(sys.stdout)
  317. pager_cmd = pager
  318. break
  319. # 3. Check core.pager config
  320. if not pager_cmd and config:
  321. try:
  322. core_pager = config.get(("core",), b"pager")
  323. except KeyError:
  324. pass
  325. else:
  326. if core_pager == b"false" or core_pager == b"":
  327. return _StreamContextAdapter(sys.stdout)
  328. pager_cmd = (
  329. core_pager.decode() if isinstance(core_pager, bytes) else core_pager
  330. )
  331. # 4. Fallback to common pagers
  332. if not pager_cmd:
  333. for pager in ["less", "more", "cat"]:
  334. if shutil.which(pager):
  335. if pager == "less":
  336. pager_cmd = "less -FRX" # -F: quit if one screen, -R: raw control chars, -X: no init/deinit
  337. else:
  338. pager_cmd = pager
  339. break
  340. else:
  341. pager_cmd = "cat" # Ultimate fallback
  342. return Pager(pager_cmd)
  343. def disable_pager():
  344. """Disable pager for this session."""
  345. get_pager._disabled = True
  346. def enable_pager():
  347. """Enable pager for this session."""
  348. get_pager._disabled = False
  349. class Command:
  350. """A Dulwich subcommand."""
  351. def run(self, args) -> Optional[int]:
  352. """Run the command."""
  353. raise NotImplementedError(self.run)
  354. class cmd_archive(Command):
  355. """Create an archive of files from a named tree."""
  356. def run(self, args) -> None:
  357. parser = argparse.ArgumentParser()
  358. parser.add_argument(
  359. "--remote",
  360. type=str,
  361. help="Retrieve archive from specified remote repo",
  362. )
  363. parser.add_argument("committish", type=str, nargs="?")
  364. args = parser.parse_args(args)
  365. if args.remote:
  366. client, path = get_transport_and_path(args.remote)
  367. client.archive(
  368. path,
  369. args.committish,
  370. sys.stdout.write,
  371. write_error=sys.stderr.write,
  372. )
  373. else:
  374. # Use buffer if available (for binary output), otherwise use stdout
  375. outstream = getattr(sys.stdout, "buffer", sys.stdout)
  376. porcelain.archive(
  377. ".", args.committish, outstream=outstream, errstream=sys.stderr
  378. )
  379. class cmd_add(Command):
  380. """Add file contents to the index."""
  381. def run(self, argv) -> None:
  382. parser = argparse.ArgumentParser()
  383. parser.add_argument("path", nargs="+")
  384. args = parser.parse_args(argv)
  385. # Convert '.' to None to add all files
  386. paths = args.path
  387. if len(paths) == 1 and paths[0] == ".":
  388. paths = None
  389. porcelain.add(".", paths=paths)
  390. class cmd_annotate(Command):
  391. """Annotate each line in a file with commit information."""
  392. def run(self, argv) -> None:
  393. parser = argparse.ArgumentParser()
  394. parser.add_argument("path", help="Path to file to annotate")
  395. parser.add_argument("committish", nargs="?", help="Commit to start from")
  396. args = parser.parse_args(argv)
  397. with Repo(".") as repo:
  398. config = repo.get_config_stack()
  399. with get_pager(config=config, cmd_name="annotate") as outstream:
  400. results = porcelain.annotate(repo, args.path, args.committish)
  401. for (commit, entry), line in results:
  402. # Show shortened commit hash and line content
  403. commit_hash = commit.id[:8]
  404. outstream.write(f"{commit_hash.decode()} {line.decode()}\n")
  405. class cmd_blame(Command):
  406. """Show what revision and author last modified each line of a file."""
  407. def run(self, argv) -> None:
  408. # blame is an alias for annotate
  409. cmd_annotate().run(argv)
  410. class cmd_rm(Command):
  411. """Remove files from the working tree and from the index."""
  412. def run(self, argv) -> None:
  413. parser = argparse.ArgumentParser()
  414. parser.add_argument(
  415. "--cached", action="store_true", help="Remove from index only"
  416. )
  417. parser.add_argument("path", type=Path, nargs="+")
  418. args = parser.parse_args(argv)
  419. porcelain.remove(".", paths=args.path, cached=args.cached)
  420. class cmd_mv(Command):
  421. """Move or rename a file, a directory, or a symlink."""
  422. def run(self, argv) -> None:
  423. parser = argparse.ArgumentParser()
  424. parser.add_argument(
  425. "-f",
  426. "--force",
  427. action="store_true",
  428. help="Force move even if destination exists",
  429. )
  430. parser.add_argument("source", type=Path)
  431. parser.add_argument("destination", type=Path)
  432. args = parser.parse_args(argv)
  433. porcelain.mv(".", args.source, args.destination, force=args.force)
  434. class cmd_fetch_pack(Command):
  435. """Receive missing objects from another repository."""
  436. def run(self, argv) -> None:
  437. parser = argparse.ArgumentParser()
  438. parser.add_argument("--all", action="store_true")
  439. parser.add_argument("location", nargs="?", type=str)
  440. parser.add_argument("refs", nargs="*", type=str)
  441. args = parser.parse_args(argv)
  442. client, path = get_transport_and_path(args.location)
  443. r = Repo(".")
  444. if args.all:
  445. determine_wants = r.object_store.determine_wants_all
  446. else:
  447. def determine_wants(refs, depth: Optional[int] = None):
  448. return [y.encode("utf-8") for y in args.refs if y not in r.object_store]
  449. client.fetch(path, r, determine_wants)
  450. class cmd_fetch(Command):
  451. """Download objects and refs from another repository."""
  452. def run(self, args) -> None:
  453. parser = argparse.ArgumentParser()
  454. parser.add_argument("location", help="Remote location to fetch from")
  455. args = parser.parse_args(args)
  456. client, path = get_transport_and_path(args.location)
  457. r = Repo(".")
  458. def progress(msg: bytes) -> None:
  459. sys.stdout.buffer.write(msg)
  460. refs = client.fetch(path, r, progress=progress)
  461. print("Remote refs:")
  462. for item in refs.items():
  463. print("{} -> {}".format(*item))
  464. class cmd_for_each_ref(Command):
  465. """Output information on each ref."""
  466. def run(self, args) -> None:
  467. parser = argparse.ArgumentParser()
  468. parser.add_argument("pattern", type=str, nargs="?")
  469. args = parser.parse_args(args)
  470. for sha, object_type, ref in porcelain.for_each_ref(".", args.pattern):
  471. print(f"{sha.decode()} {object_type.decode()}\t{ref.decode()}")
  472. class cmd_fsck(Command):
  473. """Verify the connectivity and validity of objects in the database."""
  474. def run(self, args) -> None:
  475. parser = argparse.ArgumentParser()
  476. parser.parse_args(args)
  477. for obj, msg in porcelain.fsck("."):
  478. print(f"{obj}: {msg}")
  479. class cmd_log(Command):
  480. """Show commit logs."""
  481. def run(self, args) -> None:
  482. parser = argparse.ArgumentParser()
  483. parser.add_argument(
  484. "--reverse",
  485. action="store_true",
  486. help="Reverse order in which entries are printed",
  487. )
  488. parser.add_argument(
  489. "--name-status",
  490. action="store_true",
  491. help="Print name/status for each changed file",
  492. )
  493. parser.add_argument("paths", nargs="*", help="Paths to show log for")
  494. args = parser.parse_args(args)
  495. with Repo(".") as repo:
  496. config = repo.get_config_stack()
  497. with get_pager(config=config, cmd_name="log") as outstream:
  498. porcelain.log(
  499. repo,
  500. paths=args.paths,
  501. reverse=args.reverse,
  502. name_status=args.name_status,
  503. outstream=outstream,
  504. )
  505. class cmd_diff(Command):
  506. """Show changes between commits, commit and working tree, etc."""
  507. def run(self, args) -> None:
  508. parser = argparse.ArgumentParser()
  509. parser.add_argument(
  510. "committish", nargs="*", default=[], help="Commits or refs to compare"
  511. )
  512. parser.add_argument("--staged", action="store_true", help="Show staged changes")
  513. parser.add_argument(
  514. "--cached",
  515. action="store_true",
  516. help="Show staged changes (same as --staged)",
  517. )
  518. parser.add_argument(
  519. "--color",
  520. choices=["always", "never", "auto"],
  521. default="auto",
  522. help="Use colored output (requires rich)",
  523. )
  524. parser.add_argument(
  525. "--", dest="separator", action="store_true", help=argparse.SUPPRESS
  526. )
  527. parser.add_argument("paths", nargs="*", default=[], help="Paths to limit diff")
  528. # Handle the -- separator for paths
  529. if "--" in args:
  530. sep_index = args.index("--")
  531. parsed_args = parser.parse_args(args[:sep_index])
  532. parsed_args.paths = args[sep_index + 1 :]
  533. else:
  534. parsed_args = parser.parse_args(args)
  535. args = parsed_args
  536. # Determine if we should use color
  537. def _should_use_color():
  538. if args.color == "always":
  539. return True
  540. elif args.color == "never":
  541. return False
  542. else: # auto
  543. return sys.stdout.isatty()
  544. def _create_output_stream(outstream):
  545. """Create output stream, optionally with colorization."""
  546. if not _should_use_color():
  547. return outstream.buffer
  548. from .diff import ColorizedDiffStream
  549. if not ColorizedDiffStream.is_available():
  550. if args.color == "always":
  551. raise ImportError(
  552. "Rich is required for colored output. Install with: pip install 'dulwich[colordiff]'"
  553. )
  554. else:
  555. logging.warning(
  556. "Rich not available, disabling colored output. Install with: pip install 'dulwich[colordiff]'"
  557. )
  558. return outstream.buffer
  559. return ColorizedDiffStream(outstream.buffer)
  560. with Repo(".") as repo:
  561. config = repo.get_config_stack()
  562. with get_pager(config=config, cmd_name="diff") as outstream:
  563. output_stream = _create_output_stream(outstream)
  564. if len(args.committish) == 0:
  565. # Show diff for working tree or staged changes
  566. porcelain.diff(
  567. repo,
  568. staged=(args.staged or args.cached),
  569. paths=args.paths or None,
  570. outstream=output_stream,
  571. )
  572. elif len(args.committish) == 1:
  573. # Show diff between working tree and specified commit
  574. if args.staged or args.cached:
  575. parser.error("--staged/--cached cannot be used with commits")
  576. porcelain.diff(
  577. repo,
  578. commit=args.committish[0],
  579. staged=False,
  580. paths=args.paths or None,
  581. outstream=output_stream,
  582. )
  583. elif len(args.committish) == 2:
  584. # Show diff between two commits
  585. porcelain.diff(
  586. repo,
  587. commit=args.committish[0],
  588. commit2=args.committish[1],
  589. paths=args.paths or None,
  590. outstream=output_stream,
  591. )
  592. else:
  593. parser.error("Too many arguments - specify at most two commits")
  594. # Flush any remaining output
  595. if hasattr(output_stream, "flush"):
  596. output_stream.flush()
  597. class cmd_dump_pack(Command):
  598. """Dump the contents of a pack file for debugging."""
  599. def run(self, args) -> None:
  600. parser = argparse.ArgumentParser()
  601. parser.add_argument("filename", help="Pack file to dump")
  602. args = parser.parse_args(args)
  603. basename, _ = os.path.splitext(args.filename)
  604. x = Pack(basename)
  605. print(f"Object names checksum: {x.name()}")
  606. print(f"Checksum: {sha_to_hex(x.get_stored_checksum())!r}")
  607. x.check()
  608. print(f"Length: {len(x)}")
  609. for name in x:
  610. try:
  611. print(f"\t{x[name]}")
  612. except KeyError as k:
  613. print(f"\t{name}: Unable to resolve base {k}")
  614. except ApplyDeltaError as e:
  615. print(f"\t{name}: Unable to apply delta: {e!r}")
  616. class cmd_dump_index(Command):
  617. """Show information about a pack index file."""
  618. def run(self, args) -> None:
  619. parser = argparse.ArgumentParser()
  620. parser.add_argument("filename", help="Index file to dump")
  621. args = parser.parse_args(args)
  622. idx = Index(args.filename)
  623. for o in idx:
  624. print(o, idx[o])
  625. class cmd_init(Command):
  626. """Create an empty Git repository or reinitialize an existing one."""
  627. def run(self, args) -> None:
  628. parser = argparse.ArgumentParser()
  629. parser.add_argument(
  630. "--bare", action="store_true", help="Create a bare repository"
  631. )
  632. parser.add_argument(
  633. "path", nargs="?", default=os.getcwd(), help="Repository path"
  634. )
  635. args = parser.parse_args(args)
  636. porcelain.init(args.path, bare=args.bare)
  637. class cmd_clone(Command):
  638. """Clone a repository into a new directory."""
  639. def run(self, args) -> None:
  640. parser = argparse.ArgumentParser()
  641. parser.add_argument(
  642. "--bare",
  643. help="Whether to create a bare repository.",
  644. action="store_true",
  645. )
  646. parser.add_argument("--depth", type=int, help="Depth at which to fetch")
  647. parser.add_argument(
  648. "-b",
  649. "--branch",
  650. type=str,
  651. help="Check out branch instead of branch pointed to by remote HEAD",
  652. )
  653. parser.add_argument(
  654. "--refspec",
  655. type=str,
  656. help="References to fetch",
  657. action="append",
  658. )
  659. parser.add_argument(
  660. "--filter",
  661. dest="filter_spec",
  662. type=str,
  663. help="git-rev-list-style object filter",
  664. )
  665. parser.add_argument(
  666. "--protocol",
  667. type=int,
  668. help="Git protocol version to use",
  669. )
  670. parser.add_argument(
  671. "--recurse-submodules",
  672. action="store_true",
  673. help="Initialize and clone submodules",
  674. )
  675. parser.add_argument("source", help="Repository to clone from")
  676. parser.add_argument("target", nargs="?", help="Directory to clone into")
  677. args = parser.parse_args(args)
  678. try:
  679. porcelain.clone(
  680. args.source,
  681. args.target,
  682. bare=args.bare,
  683. depth=args.depth,
  684. branch=args.branch,
  685. refspec=args.refspec,
  686. filter_spec=args.filter_spec,
  687. protocol_version=args.protocol,
  688. recurse_submodules=args.recurse_submodules,
  689. )
  690. except GitProtocolError as e:
  691. print(f"{e}")
  692. def _get_commit_message_with_template(initial_message, repo=None, commit=None):
  693. """Get commit message with an initial message template."""
  694. # Start with the initial message
  695. template = initial_message
  696. if template and not template.endswith(b"\n"):
  697. template += b"\n"
  698. template += b"\n"
  699. template += b"# Please enter the commit message for your changes. Lines starting\n"
  700. template += b"# with '#' will be ignored, and an empty message aborts the commit.\n"
  701. template += b"#\n"
  702. # Add branch info if repo is provided
  703. if repo:
  704. try:
  705. ref_names, ref_sha = repo.refs.follow(b"HEAD")
  706. ref_path = ref_names[-1] # Get the final reference
  707. if ref_path.startswith(b"refs/heads/"):
  708. branch = ref_path[11:] # Remove 'refs/heads/' prefix
  709. else:
  710. branch = ref_path
  711. template += b"# On branch %s\n" % branch
  712. except (KeyError, IndexError):
  713. template += b"# On branch (unknown)\n"
  714. template += b"#\n"
  715. template += b"# Changes to be committed:\n"
  716. # Launch editor
  717. content = launch_editor(template)
  718. # Remove comment lines and strip
  719. lines = content.split(b"\n")
  720. message_lines = [line for line in lines if not line.strip().startswith(b"#")]
  721. message = b"\n".join(message_lines).strip()
  722. if not message:
  723. raise CommitMessageError("Aborting commit due to empty commit message")
  724. return message
  725. class cmd_commit(Command):
  726. """Record changes to the repository."""
  727. def run(self, args) -> Optional[int]:
  728. parser = argparse.ArgumentParser()
  729. parser.add_argument("--message", "-m", help="Commit message")
  730. parser.add_argument(
  731. "-a",
  732. "--all",
  733. action="store_true",
  734. help="Automatically stage all tracked files that have been modified",
  735. )
  736. parser.add_argument(
  737. "--amend",
  738. action="store_true",
  739. help="Replace the tip of the current branch by creating a new commit",
  740. )
  741. args = parser.parse_args(args)
  742. message: Union[bytes, str, Callable]
  743. if args.message:
  744. message = args.message
  745. elif args.amend:
  746. # For amend, create a callable that opens editor with original message pre-populated
  747. def get_amend_message(repo, commit):
  748. # Get the original commit message from current HEAD
  749. try:
  750. head_commit = repo[repo.head()]
  751. original_message = head_commit.message
  752. except KeyError:
  753. original_message = b""
  754. # Open editor with original message
  755. return _get_commit_message_with_template(original_message, repo, commit)
  756. message = get_amend_message
  757. else:
  758. # For regular commits, use empty template
  759. def get_regular_message(repo, commit):
  760. return _get_commit_message_with_template(b"", repo, commit)
  761. message = get_regular_message
  762. try:
  763. porcelain.commit(".", message=message, all=args.all, amend=args.amend)
  764. except CommitMessageError as e:
  765. print(f"error: {e}", file=sys.stderr)
  766. return 1
  767. return None
  768. class cmd_commit_tree(Command):
  769. """Create a new commit object from a tree."""
  770. def run(self, args) -> None:
  771. parser = argparse.ArgumentParser()
  772. parser.add_argument("--message", "-m", required=True, help="Commit message")
  773. parser.add_argument("tree", help="Tree SHA to commit")
  774. args = parser.parse_args(args)
  775. porcelain.commit_tree(".", tree=args.tree, message=args.message)
  776. class cmd_update_server_info(Command):
  777. """Update auxiliary info file to help dumb servers."""
  778. def run(self, args) -> None:
  779. porcelain.update_server_info(".")
  780. class cmd_symbolic_ref(Command):
  781. """Read, modify and delete symbolic refs."""
  782. def run(self, args) -> None:
  783. parser = argparse.ArgumentParser()
  784. parser.add_argument("name", help="Symbolic reference name")
  785. parser.add_argument("ref", nargs="?", help="Target reference")
  786. parser.add_argument("--force", action="store_true", help="Force update")
  787. args = parser.parse_args(args)
  788. # If ref is provided, we're setting; otherwise we're reading
  789. if args.ref:
  790. # Set symbolic reference
  791. from .repo import Repo
  792. with Repo(".") as repo:
  793. repo.refs.set_symbolic_ref(args.name.encode(), args.ref.encode())
  794. else:
  795. # Read symbolic reference
  796. from .repo import Repo
  797. with Repo(".") as repo:
  798. try:
  799. target = repo.refs.read_ref(args.name.encode())
  800. if target.startswith(b"ref: "):
  801. print(target[5:].decode())
  802. else:
  803. print(target.decode())
  804. except KeyError:
  805. print(f"fatal: ref '{args.name}' is not a symbolic ref")
  806. class cmd_pack_refs(Command):
  807. """Pack heads and tags for efficient repository access."""
  808. def run(self, argv) -> None:
  809. parser = argparse.ArgumentParser()
  810. parser.add_argument("--all", action="store_true")
  811. # ignored, we never prune
  812. parser.add_argument("--no-prune", action="store_true")
  813. args = parser.parse_args(argv)
  814. porcelain.pack_refs(".", all=args.all)
  815. class cmd_show(Command):
  816. """Show various types of objects."""
  817. def run(self, argv) -> None:
  818. parser = argparse.ArgumentParser()
  819. parser.add_argument("objectish", type=str, nargs="*")
  820. parser.add_argument(
  821. "--color",
  822. choices=["always", "never", "auto"],
  823. default="auto",
  824. help="Use colored output (requires rich)",
  825. )
  826. args = parser.parse_args(argv)
  827. # Determine if we should use color
  828. def _should_use_color():
  829. if args.color == "always":
  830. return True
  831. elif args.color == "never":
  832. return False
  833. else: # auto
  834. return sys.stdout.isatty()
  835. def _create_output_stream(outstream):
  836. """Create output stream, optionally with colorization."""
  837. if not _should_use_color():
  838. return outstream
  839. from .diff import ColorizedDiffStream
  840. if not ColorizedDiffStream.is_available():
  841. if args.color == "always":
  842. raise ImportError(
  843. "Rich is required for colored output. Install with: pip install 'dulwich[colordiff]'"
  844. )
  845. else:
  846. logging.warning(
  847. "Rich not available, disabling colored output. Install with: pip install 'dulwich[colordiff]'"
  848. )
  849. return outstream
  850. return ColorizedDiffStream(outstream.buffer)
  851. with Repo(".") as repo:
  852. config = repo.get_config_stack()
  853. with get_pager(config=config, cmd_name="show") as outstream:
  854. output_stream = _create_output_stream(outstream)
  855. porcelain.show(repo, args.objectish or None, outstream=output_stream)
  856. class cmd_diff_tree(Command):
  857. """Compare the content and mode of trees."""
  858. def run(self, args) -> None:
  859. parser = argparse.ArgumentParser()
  860. parser.add_argument("old_tree", help="Old tree SHA")
  861. parser.add_argument("new_tree", help="New tree SHA")
  862. args = parser.parse_args(args)
  863. porcelain.diff_tree(".", args.old_tree, args.new_tree)
  864. class cmd_rev_list(Command):
  865. """List commit objects in reverse chronological order."""
  866. def run(self, args) -> None:
  867. parser = argparse.ArgumentParser()
  868. parser.add_argument("commits", nargs="+", help="Commit IDs to list")
  869. args = parser.parse_args(args)
  870. porcelain.rev_list(".", args.commits)
  871. class cmd_tag(Command):
  872. """Create, list, delete or verify a tag object."""
  873. def run(self, args) -> None:
  874. parser = argparse.ArgumentParser()
  875. parser.add_argument(
  876. "-a",
  877. "--annotated",
  878. help="Create an annotated tag.",
  879. action="store_true",
  880. )
  881. parser.add_argument(
  882. "-s", "--sign", help="Sign the annotated tag.", action="store_true"
  883. )
  884. parser.add_argument("tag_name", help="Name of the tag to create")
  885. args = parser.parse_args(args)
  886. porcelain.tag_create(
  887. ".", args.tag_name, annotated=args.annotated, sign=args.sign
  888. )
  889. class cmd_repack(Command):
  890. """Pack unpacked objects in a repository."""
  891. def run(self, args) -> None:
  892. parser = argparse.ArgumentParser()
  893. parser.parse_args(args)
  894. porcelain.repack(".")
  895. class cmd_reflog(Command):
  896. """Manage reflog information."""
  897. def run(self, args) -> None:
  898. parser = argparse.ArgumentParser()
  899. parser.add_argument(
  900. "ref", nargs="?", default="HEAD", help="Reference to show reflog for"
  901. )
  902. parser.add_argument(
  903. "--all", action="store_true", help="Show reflogs for all refs"
  904. )
  905. args = parser.parse_args(args)
  906. with Repo(".") as repo:
  907. config = repo.get_config_stack()
  908. with get_pager(config=config, cmd_name="reflog") as outstream:
  909. if args.all:
  910. # Show reflogs for all refs
  911. for ref_bytes, entry in porcelain.reflog(repo, all=True):
  912. ref_str = ref_bytes.decode("utf-8", "replace")
  913. short_new = entry.new_sha[:8].decode("ascii")
  914. outstream.write(
  915. f"{short_new} {ref_str}: {entry.message.decode('utf-8', 'replace')}\n"
  916. )
  917. else:
  918. ref = (
  919. args.ref.encode("utf-8")
  920. if isinstance(args.ref, str)
  921. else args.ref
  922. )
  923. for i, entry in enumerate(porcelain.reflog(repo, ref)):
  924. # Format similar to git reflog
  925. short_new = entry.new_sha[:8].decode("ascii")
  926. outstream.write(
  927. f"{short_new} {ref.decode('utf-8', 'replace')}@{{{i}}}: {entry.message.decode('utf-8', 'replace')}\n"
  928. )
  929. class cmd_reset(Command):
  930. """Reset current HEAD to the specified state."""
  931. def run(self, args) -> None:
  932. parser = argparse.ArgumentParser()
  933. mode_group = parser.add_mutually_exclusive_group()
  934. mode_group.add_argument(
  935. "--hard", action="store_true", help="Reset working tree and index"
  936. )
  937. mode_group.add_argument("--soft", action="store_true", help="Reset only HEAD")
  938. mode_group.add_argument(
  939. "--mixed", action="store_true", help="Reset HEAD and index"
  940. )
  941. parser.add_argument("treeish", nargs="?", help="Commit/tree to reset to")
  942. args = parser.parse_args(args)
  943. if args.hard:
  944. mode = "hard"
  945. elif args.soft:
  946. mode = "soft"
  947. elif args.mixed:
  948. mode = "mixed"
  949. else:
  950. # Default to mixed behavior
  951. mode = "mixed"
  952. # Use the porcelain.reset function for all modes
  953. porcelain.reset(".", mode=mode, treeish=args.treeish)
  954. class cmd_revert(Command):
  955. """Revert some existing commits."""
  956. def run(self, args) -> None:
  957. parser = argparse.ArgumentParser()
  958. parser.add_argument(
  959. "--no-commit",
  960. "-n",
  961. action="store_true",
  962. help="Apply changes but don't create a commit",
  963. )
  964. parser.add_argument("-m", "--message", help="Custom commit message")
  965. parser.add_argument("commits", nargs="+", help="Commits to revert")
  966. args = parser.parse_args(args)
  967. result = porcelain.revert(
  968. ".", commits=args.commits, no_commit=args.no_commit, message=args.message
  969. )
  970. if result and not args.no_commit:
  971. print(f"[{result.decode('ascii')[:7]}] Revert completed")
  972. class cmd_daemon(Command):
  973. """Run a simple Git protocol server."""
  974. def run(self, args) -> None:
  975. from dulwich import log_utils
  976. from .protocol import TCP_GIT_PORT
  977. parser = argparse.ArgumentParser()
  978. parser.add_argument(
  979. "-l",
  980. "--listen_address",
  981. default="localhost",
  982. help="Binding IP address.",
  983. )
  984. parser.add_argument(
  985. "-p",
  986. "--port",
  987. type=int,
  988. default=TCP_GIT_PORT,
  989. help="Binding TCP port.",
  990. )
  991. parser.add_argument(
  992. "gitdir", nargs="?", default=".", help="Git directory to serve"
  993. )
  994. args = parser.parse_args(args)
  995. log_utils.default_logging_config()
  996. porcelain.daemon(args.gitdir, address=args.listen_address, port=args.port)
  997. class cmd_web_daemon(Command):
  998. """Run a simple HTTP server for Git repositories."""
  999. def run(self, args) -> None:
  1000. from dulwich import log_utils
  1001. parser = argparse.ArgumentParser()
  1002. parser.add_argument(
  1003. "-l",
  1004. "--listen_address",
  1005. default="",
  1006. help="Binding IP address.",
  1007. )
  1008. parser.add_argument(
  1009. "-p",
  1010. "--port",
  1011. type=int,
  1012. default=8000,
  1013. help="Binding TCP port.",
  1014. )
  1015. parser.add_argument(
  1016. "gitdir", nargs="?", default=".", help="Git directory to serve"
  1017. )
  1018. args = parser.parse_args(args)
  1019. log_utils.default_logging_config()
  1020. porcelain.web_daemon(args.gitdir, address=args.listen_address, port=args.port)
  1021. class cmd_write_tree(Command):
  1022. """Create a tree object from the current index."""
  1023. def run(self, args) -> None:
  1024. parser = argparse.ArgumentParser()
  1025. parser.parse_args(args)
  1026. sys.stdout.write("{}\n".format(porcelain.write_tree(".").decode()))
  1027. class cmd_receive_pack(Command):
  1028. """Receive what is pushed into the repository."""
  1029. def run(self, args) -> None:
  1030. parser = argparse.ArgumentParser()
  1031. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  1032. args = parser.parse_args(args)
  1033. porcelain.receive_pack(args.gitdir)
  1034. class cmd_upload_pack(Command):
  1035. """Send objects packed back to git-fetch-pack."""
  1036. def run(self, args) -> None:
  1037. parser = argparse.ArgumentParser()
  1038. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  1039. args = parser.parse_args(args)
  1040. porcelain.upload_pack(args.gitdir)
  1041. class cmd_status(Command):
  1042. """Show the working tree status."""
  1043. def run(self, args) -> None:
  1044. parser = argparse.ArgumentParser()
  1045. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  1046. args = parser.parse_args(args)
  1047. status = porcelain.status(args.gitdir)
  1048. if any(names for (kind, names) in status.staged.items()):
  1049. sys.stdout.write("Changes to be committed:\n\n")
  1050. for kind, names in status.staged.items():
  1051. for name in names:
  1052. sys.stdout.write(
  1053. f"\t{kind}: {name.decode(sys.getfilesystemencoding())}\n"
  1054. )
  1055. sys.stdout.write("\n")
  1056. if status.unstaged:
  1057. sys.stdout.write("Changes not staged for commit:\n\n")
  1058. for name in status.unstaged:
  1059. sys.stdout.write(f"\t{name.decode(sys.getfilesystemencoding())}\n")
  1060. sys.stdout.write("\n")
  1061. if status.untracked:
  1062. sys.stdout.write("Untracked files:\n\n")
  1063. for name in status.untracked:
  1064. sys.stdout.write(f"\t{name}\n")
  1065. sys.stdout.write("\n")
  1066. class cmd_ls_remote(Command):
  1067. """List references in a remote repository."""
  1068. def run(self, args) -> None:
  1069. parser = argparse.ArgumentParser()
  1070. parser.add_argument(
  1071. "--symref", action="store_true", help="Show symbolic references"
  1072. )
  1073. parser.add_argument("url", help="Remote URL to list references from")
  1074. args = parser.parse_args(args)
  1075. result = porcelain.ls_remote(args.url)
  1076. if args.symref:
  1077. # Show symrefs first, like git does
  1078. for ref, target in sorted(result.symrefs.items()):
  1079. sys.stdout.write(f"ref: {target.decode()}\t{ref.decode()}\n")
  1080. # Show regular refs
  1081. for ref in sorted(result.refs):
  1082. sys.stdout.write(f"{result.refs[ref].decode()}\t{ref.decode()}\n")
  1083. class cmd_ls_tree(Command):
  1084. """List the contents of a tree object."""
  1085. def run(self, args) -> None:
  1086. parser = argparse.ArgumentParser()
  1087. parser.add_argument(
  1088. "-r",
  1089. "--recursive",
  1090. action="store_true",
  1091. help="Recursively list tree contents.",
  1092. )
  1093. parser.add_argument(
  1094. "--name-only", action="store_true", help="Only display name."
  1095. )
  1096. parser.add_argument("treeish", nargs="?", help="Tree-ish to list")
  1097. args = parser.parse_args(args)
  1098. with Repo(".") as repo:
  1099. config = repo.get_config_stack()
  1100. with get_pager(config=config, cmd_name="ls-tree") as outstream:
  1101. porcelain.ls_tree(
  1102. repo,
  1103. args.treeish,
  1104. outstream=outstream,
  1105. recursive=args.recursive,
  1106. name_only=args.name_only,
  1107. )
  1108. class cmd_pack_objects(Command):
  1109. """Create a packed archive of objects."""
  1110. def run(self, args) -> None:
  1111. parser = argparse.ArgumentParser()
  1112. parser.add_argument(
  1113. "--stdout", action="store_true", help="Write pack to stdout"
  1114. )
  1115. parser.add_argument("--deltify", action="store_true", help="Create deltas")
  1116. parser.add_argument(
  1117. "--no-reuse-deltas", action="store_true", help="Don't reuse existing deltas"
  1118. )
  1119. parser.add_argument("basename", nargs="?", help="Base name for pack files")
  1120. args = parser.parse_args(args)
  1121. if not args.stdout and not args.basename:
  1122. parser.error("basename required when not using --stdout")
  1123. object_ids = [line.strip() for line in sys.stdin.readlines()]
  1124. deltify = args.deltify
  1125. reuse_deltas = not args.no_reuse_deltas
  1126. if args.stdout:
  1127. packf = getattr(sys.stdout, "buffer", sys.stdout)
  1128. idxf = None
  1129. close = []
  1130. else:
  1131. packf = open(args.basename + ".pack", "wb")
  1132. idxf = open(args.basename + ".idx", "wb")
  1133. close = [packf, idxf]
  1134. porcelain.pack_objects(
  1135. ".", object_ids, packf, idxf, deltify=deltify, reuse_deltas=reuse_deltas
  1136. )
  1137. for f in close:
  1138. f.close()
  1139. class cmd_unpack_objects(Command):
  1140. """Unpack objects from a packed archive."""
  1141. def run(self, args) -> None:
  1142. parser = argparse.ArgumentParser()
  1143. parser.add_argument("pack_file", help="Pack file to unpack")
  1144. args = parser.parse_args(args)
  1145. count = porcelain.unpack_objects(args.pack_file)
  1146. print(f"Unpacked {count} objects")
  1147. class cmd_prune(Command):
  1148. """Prune all unreachable objects from the object database."""
  1149. def run(self, args) -> Optional[int]:
  1150. import datetime
  1151. import time
  1152. from dulwich.object_store import DEFAULT_TEMPFILE_GRACE_PERIOD
  1153. parser = argparse.ArgumentParser(
  1154. description="Remove temporary pack files left behind by interrupted operations"
  1155. )
  1156. parser.add_argument(
  1157. "--expire",
  1158. nargs="?",
  1159. const="2.weeks.ago",
  1160. help="Only prune files older than the specified date (default: 2.weeks.ago)",
  1161. )
  1162. parser.add_argument(
  1163. "--dry-run",
  1164. "-n",
  1165. action="store_true",
  1166. help="Only report what would be removed",
  1167. )
  1168. parser.add_argument(
  1169. "--verbose",
  1170. "-v",
  1171. action="store_true",
  1172. help="Report all actions",
  1173. )
  1174. args = parser.parse_args(args)
  1175. # Parse expire grace period
  1176. grace_period = DEFAULT_TEMPFILE_GRACE_PERIOD
  1177. if args.expire:
  1178. try:
  1179. grace_period = parse_relative_time(args.expire)
  1180. except ValueError:
  1181. # Try to parse as absolute date
  1182. try:
  1183. date = datetime.datetime.strptime(args.expire, "%Y-%m-%d")
  1184. grace_period = int(time.time() - date.timestamp())
  1185. except ValueError:
  1186. print(f"Error: Invalid expire date: {args.expire}", file=sys.stderr)
  1187. return 1
  1188. # Progress callback
  1189. def progress(msg):
  1190. if args.verbose:
  1191. print(msg)
  1192. try:
  1193. porcelain.prune(
  1194. ".",
  1195. grace_period=grace_period,
  1196. dry_run=args.dry_run,
  1197. progress=progress if args.verbose else None,
  1198. )
  1199. return None
  1200. except porcelain.Error as e:
  1201. print(f"Error: {e}", file=sys.stderr)
  1202. return 1
  1203. class cmd_pull(Command):
  1204. """Fetch from and integrate with another repository or a local branch."""
  1205. def run(self, args) -> None:
  1206. parser = argparse.ArgumentParser()
  1207. parser.add_argument("from_location", type=str)
  1208. parser.add_argument("refspec", type=str, nargs="*")
  1209. parser.add_argument("--filter", type=str, nargs=1)
  1210. parser.add_argument("--protocol", type=int)
  1211. args = parser.parse_args(args)
  1212. porcelain.pull(
  1213. ".",
  1214. args.from_location or None,
  1215. args.refspec or None,
  1216. filter_spec=args.filter,
  1217. protocol_version=args.protocol or None,
  1218. )
  1219. class cmd_push(Command):
  1220. """Update remote refs along with associated objects."""
  1221. def run(self, argv) -> Optional[int]:
  1222. parser = argparse.ArgumentParser()
  1223. parser.add_argument("-f", "--force", action="store_true", help="Force")
  1224. parser.add_argument("to_location", type=str)
  1225. parser.add_argument("refspec", type=str, nargs="*")
  1226. args = parser.parse_args(argv)
  1227. try:
  1228. porcelain.push(
  1229. ".", args.to_location, args.refspec or None, force=args.force
  1230. )
  1231. except porcelain.DivergedBranches:
  1232. sys.stderr.write("Diverged branches; specify --force to override")
  1233. return 1
  1234. return None
  1235. class cmd_remote_add(Command):
  1236. """Add a remote repository."""
  1237. def run(self, args) -> None:
  1238. parser = argparse.ArgumentParser()
  1239. parser.add_argument("name", help="Name of the remote")
  1240. parser.add_argument("url", help="URL of the remote")
  1241. args = parser.parse_args(args)
  1242. porcelain.remote_add(".", args.name, args.url)
  1243. class SuperCommand(Command):
  1244. """Base class for commands that have subcommands."""
  1245. subcommands: ClassVar[dict[str, type[Command]]] = {}
  1246. default_command: ClassVar[Optional[type[Command]]] = None
  1247. def run(self, args):
  1248. if not args:
  1249. if self.default_command:
  1250. return self.default_command().run(args)
  1251. else:
  1252. print(
  1253. "Supported subcommands: {}".format(
  1254. ", ".join(self.subcommands.keys())
  1255. )
  1256. )
  1257. return False
  1258. cmd = args[0]
  1259. try:
  1260. cmd_kls = self.subcommands[cmd]
  1261. except KeyError:
  1262. print(f"No such subcommand: {args[0]}")
  1263. sys.exit(1)
  1264. return cmd_kls().run(args[1:])
  1265. class cmd_remote(SuperCommand):
  1266. """Manage set of tracked repositories."""
  1267. subcommands: ClassVar[dict[str, type[Command]]] = {
  1268. "add": cmd_remote_add,
  1269. }
  1270. class cmd_submodule_list(Command):
  1271. """List submodules."""
  1272. def run(self, argv) -> None:
  1273. parser = argparse.ArgumentParser()
  1274. parser.parse_args(argv)
  1275. for path, sha in porcelain.submodule_list("."):
  1276. sys.stdout.write(f" {sha} {path}\n")
  1277. class cmd_submodule_init(Command):
  1278. """Initialize submodules."""
  1279. def run(self, argv) -> None:
  1280. parser = argparse.ArgumentParser()
  1281. parser.parse_args(argv)
  1282. porcelain.submodule_init(".")
  1283. class cmd_submodule_add(Command):
  1284. """Add a submodule."""
  1285. def run(self, argv) -> None:
  1286. parser = argparse.ArgumentParser()
  1287. parser.add_argument("url", help="URL of repository to add as submodule")
  1288. parser.add_argument("path", nargs="?", help="Path where submodule should live")
  1289. parser.add_argument("--name", help="Name for the submodule")
  1290. args = parser.parse_args(argv)
  1291. porcelain.submodule_add(".", args.url, args.path, args.name)
  1292. class cmd_submodule_update(Command):
  1293. """Update submodules."""
  1294. def run(self, argv) -> None:
  1295. parser = argparse.ArgumentParser()
  1296. parser.add_argument(
  1297. "--init", action="store_true", help="Initialize submodules first"
  1298. )
  1299. parser.add_argument(
  1300. "--force",
  1301. action="store_true",
  1302. help="Force update even if local changes exist",
  1303. )
  1304. parser.add_argument(
  1305. "paths", nargs="*", help="Specific submodule paths to update"
  1306. )
  1307. args = parser.parse_args(argv)
  1308. paths = args.paths if args.paths else None
  1309. porcelain.submodule_update(".", paths=paths, init=args.init, force=args.force)
  1310. class cmd_submodule(SuperCommand):
  1311. """Initialize, update or inspect submodules."""
  1312. subcommands: ClassVar[dict[str, type[Command]]] = {
  1313. "add": cmd_submodule_add,
  1314. "init": cmd_submodule_init,
  1315. "list": cmd_submodule_list,
  1316. "update": cmd_submodule_update,
  1317. }
  1318. default_command = cmd_submodule_list
  1319. class cmd_check_ignore(Command):
  1320. """Check whether files are excluded by gitignore."""
  1321. def run(self, args):
  1322. parser = argparse.ArgumentParser()
  1323. parser.add_argument("paths", nargs="+", help="Paths to check")
  1324. args = parser.parse_args(args)
  1325. ret = 1
  1326. for path in porcelain.check_ignore(".", args.paths):
  1327. print(path)
  1328. ret = 0
  1329. return ret
  1330. class cmd_check_mailmap(Command):
  1331. """Show canonical names and email addresses of contacts."""
  1332. def run(self, args) -> None:
  1333. parser = argparse.ArgumentParser()
  1334. parser.add_argument("identities", nargs="+", help="Identities to check")
  1335. args = parser.parse_args(args)
  1336. for identity in args.identities:
  1337. canonical_identity = porcelain.check_mailmap(".", identity)
  1338. print(canonical_identity)
  1339. class cmd_branch(Command):
  1340. """List, create, or delete branches."""
  1341. def run(self, args) -> Optional[int]:
  1342. parser = argparse.ArgumentParser()
  1343. parser.add_argument(
  1344. "branch",
  1345. type=str,
  1346. help="Name of the branch",
  1347. )
  1348. parser.add_argument(
  1349. "-d",
  1350. "--delete",
  1351. action="store_true",
  1352. help="Delete branch",
  1353. )
  1354. args = parser.parse_args(args)
  1355. if not args.branch:
  1356. print("Usage: dulwich branch [-d] BRANCH_NAME")
  1357. return 1
  1358. if args.delete:
  1359. porcelain.branch_delete(".", name=args.branch)
  1360. else:
  1361. try:
  1362. porcelain.branch_create(".", name=args.branch)
  1363. except porcelain.Error as e:
  1364. sys.stderr.write(f"{e}")
  1365. return 1
  1366. return 0
  1367. class cmd_checkout(Command):
  1368. """Switch branches or restore working tree files."""
  1369. def run(self, args) -> Optional[int]:
  1370. parser = argparse.ArgumentParser()
  1371. parser.add_argument(
  1372. "target",
  1373. type=str,
  1374. help="Name of the branch, tag, or commit to checkout",
  1375. )
  1376. parser.add_argument(
  1377. "-f",
  1378. "--force",
  1379. action="store_true",
  1380. help="Force checkout",
  1381. )
  1382. parser.add_argument(
  1383. "-b",
  1384. "--new-branch",
  1385. type=str,
  1386. help="Create a new branch at the target and switch to it",
  1387. )
  1388. args = parser.parse_args(args)
  1389. if not args.target:
  1390. print("Usage: dulwich checkout TARGET [--force] [-b NEW_BRANCH]")
  1391. return 1
  1392. try:
  1393. porcelain.checkout(
  1394. ".", target=args.target, force=args.force, new_branch=args.new_branch
  1395. )
  1396. except porcelain.CheckoutError as e:
  1397. sys.stderr.write(f"{e}\n")
  1398. return 1
  1399. return 0
  1400. class cmd_stash_list(Command):
  1401. """List stash entries."""
  1402. def run(self, args) -> None:
  1403. parser = argparse.ArgumentParser()
  1404. parser.parse_args(args)
  1405. for i, entry in porcelain.stash_list("."):
  1406. print("stash@{{{}}}: {}".format(i, entry.message.rstrip("\n")))
  1407. class cmd_stash_push(Command):
  1408. """Save your local modifications to a new stash."""
  1409. def run(self, args) -> None:
  1410. parser = argparse.ArgumentParser()
  1411. parser.parse_args(args)
  1412. porcelain.stash_push(".")
  1413. print("Saved working directory and index state")
  1414. class cmd_stash_pop(Command):
  1415. """Apply a stash and remove it from the stash list."""
  1416. def run(self, args) -> None:
  1417. parser = argparse.ArgumentParser()
  1418. parser.parse_args(args)
  1419. porcelain.stash_pop(".")
  1420. print("Restored working directory and index state")
  1421. class cmd_bisect(SuperCommand):
  1422. """Use binary search to find the commit that introduced a bug."""
  1423. subcommands: ClassVar[dict[str, type[Command]]] = {}
  1424. def run(self, args):
  1425. parser = argparse.ArgumentParser(prog="dulwich bisect")
  1426. subparsers = parser.add_subparsers(dest="subcommand", help="bisect subcommands")
  1427. # bisect start
  1428. start_parser = subparsers.add_parser("start", help="Start a new bisect session")
  1429. start_parser.add_argument("bad", nargs="?", help="Bad commit")
  1430. start_parser.add_argument("good", nargs="*", help="Good commit(s)")
  1431. start_parser.add_argument(
  1432. "--no-checkout",
  1433. action="store_true",
  1434. help="Don't checkout commits during bisect",
  1435. )
  1436. start_parser.add_argument(
  1437. "--term-bad", default="bad", help="Term to use for bad commits"
  1438. )
  1439. start_parser.add_argument(
  1440. "--term-good", default="good", help="Term to use for good commits"
  1441. )
  1442. start_parser.add_argument(
  1443. "--", dest="paths", nargs="*", help="Paths to limit bisect to"
  1444. )
  1445. # bisect bad
  1446. bad_parser = subparsers.add_parser("bad", help="Mark a commit as bad")
  1447. bad_parser.add_argument("rev", nargs="?", help="Commit to mark as bad")
  1448. # bisect good
  1449. good_parser = subparsers.add_parser("good", help="Mark a commit as good")
  1450. good_parser.add_argument("rev", nargs="?", help="Commit to mark as good")
  1451. # bisect skip
  1452. skip_parser = subparsers.add_parser("skip", help="Skip commits")
  1453. skip_parser.add_argument("revs", nargs="*", help="Commits to skip")
  1454. # bisect reset
  1455. reset_parser = subparsers.add_parser("reset", help="Reset bisect state")
  1456. reset_parser.add_argument("commit", nargs="?", help="Commit to reset to")
  1457. # bisect log
  1458. subparsers.add_parser("log", help="Show bisect log")
  1459. # bisect replay
  1460. replay_parser = subparsers.add_parser("replay", help="Replay bisect log")
  1461. replay_parser.add_argument("logfile", help="Log file to replay")
  1462. # bisect help
  1463. subparsers.add_parser("help", help="Show help")
  1464. parsed_args = parser.parse_args(args)
  1465. if not parsed_args.subcommand:
  1466. parser.print_help()
  1467. return 1
  1468. try:
  1469. if parsed_args.subcommand == "start":
  1470. next_sha = porcelain.bisect_start(
  1471. bad=parsed_args.bad,
  1472. good=parsed_args.good if parsed_args.good else None,
  1473. paths=parsed_args.paths,
  1474. no_checkout=parsed_args.no_checkout,
  1475. term_bad=parsed_args.term_bad,
  1476. term_good=parsed_args.term_good,
  1477. )
  1478. if next_sha:
  1479. print(f"Bisecting: checking out '{next_sha.decode('ascii')}'")
  1480. elif parsed_args.subcommand == "bad":
  1481. next_sha = porcelain.bisect_bad(rev=parsed_args.rev)
  1482. if next_sha:
  1483. print(f"Bisecting: checking out '{next_sha.decode('ascii')}'")
  1484. else:
  1485. # Bisect complete - find the first bad commit
  1486. with porcelain.open_repo_closing(".") as r:
  1487. bad_ref = os.path.join(r.controldir(), "refs", "bisect", "bad")
  1488. with open(bad_ref, "rb") as f:
  1489. bad_sha = f.read().strip()
  1490. commit = r.object_store[bad_sha]
  1491. message = commit.message.decode(
  1492. "utf-8", errors="replace"
  1493. ).split("\n")[0]
  1494. print(f"{bad_sha.decode('ascii')} is the first bad commit")
  1495. print(f"commit {bad_sha.decode('ascii')}")
  1496. print(f" {message}")
  1497. elif parsed_args.subcommand == "good":
  1498. next_sha = porcelain.bisect_good(rev=parsed_args.rev)
  1499. if next_sha:
  1500. print(f"Bisecting: checking out '{next_sha.decode('ascii')}'")
  1501. elif parsed_args.subcommand == "skip":
  1502. next_sha = porcelain.bisect_skip(
  1503. revs=parsed_args.revs if parsed_args.revs else None
  1504. )
  1505. if next_sha:
  1506. print(f"Bisecting: checking out '{next_sha.decode('ascii')}'")
  1507. elif parsed_args.subcommand == "reset":
  1508. porcelain.bisect_reset(commit=parsed_args.commit)
  1509. print("Bisect reset")
  1510. elif parsed_args.subcommand == "log":
  1511. log = porcelain.bisect_log()
  1512. print(log, end="")
  1513. elif parsed_args.subcommand == "replay":
  1514. porcelain.bisect_replay(log_file=parsed_args.logfile)
  1515. print(f"Replayed bisect log from {parsed_args.logfile}")
  1516. elif parsed_args.subcommand == "help":
  1517. parser.print_help()
  1518. except porcelain.Error as e:
  1519. print(f"Error: {e}", file=sys.stderr)
  1520. return 1
  1521. except ValueError as e:
  1522. print(f"Error: {e}", file=sys.stderr)
  1523. return 1
  1524. return 0
  1525. class cmd_stash(SuperCommand):
  1526. """Stash the changes in a dirty working directory away."""
  1527. subcommands: ClassVar[dict[str, type[Command]]] = {
  1528. "list": cmd_stash_list,
  1529. "pop": cmd_stash_pop,
  1530. "push": cmd_stash_push,
  1531. }
  1532. class cmd_ls_files(Command):
  1533. """Show information about files in the index and working tree."""
  1534. def run(self, args) -> None:
  1535. parser = argparse.ArgumentParser()
  1536. parser.parse_args(args)
  1537. for name in porcelain.ls_files("."):
  1538. print(name)
  1539. class cmd_describe(Command):
  1540. """Give an object a human readable name based on an available ref."""
  1541. def run(self, args) -> None:
  1542. parser = argparse.ArgumentParser()
  1543. parser.parse_args(args)
  1544. print(porcelain.describe("."))
  1545. class cmd_merge(Command):
  1546. """Join two or more development histories together."""
  1547. def run(self, args) -> Optional[int]:
  1548. parser = argparse.ArgumentParser()
  1549. parser.add_argument("commit", type=str, help="Commit to merge")
  1550. parser.add_argument(
  1551. "--no-commit", action="store_true", help="Do not create a merge commit"
  1552. )
  1553. parser.add_argument(
  1554. "--no-ff", action="store_true", help="Force create a merge commit"
  1555. )
  1556. parser.add_argument("-m", "--message", type=str, help="Merge commit message")
  1557. args = parser.parse_args(args)
  1558. try:
  1559. merge_commit_id, conflicts = porcelain.merge(
  1560. ".",
  1561. args.commit,
  1562. no_commit=args.no_commit,
  1563. no_ff=args.no_ff,
  1564. message=args.message,
  1565. )
  1566. if conflicts:
  1567. print(f"Merge conflicts in {len(conflicts)} file(s):")
  1568. for conflict_path in conflicts:
  1569. print(f" {conflict_path.decode()}")
  1570. print(
  1571. "\nAutomatic merge failed; fix conflicts and then commit the result."
  1572. )
  1573. return 1
  1574. elif merge_commit_id is None and not args.no_commit:
  1575. print("Already up to date.")
  1576. elif args.no_commit:
  1577. print("Automatic merge successful; not committing as requested.")
  1578. else:
  1579. print(
  1580. f"Merge successful. Created merge commit {merge_commit_id.decode()}"
  1581. )
  1582. return 0
  1583. except porcelain.Error as e:
  1584. print(f"Error: {e}")
  1585. return 1
  1586. class cmd_notes_add(Command):
  1587. """Add notes to a commit."""
  1588. def run(self, args) -> None:
  1589. parser = argparse.ArgumentParser()
  1590. parser.add_argument("object", help="Object to annotate")
  1591. parser.add_argument("-m", "--message", help="Note message", required=True)
  1592. parser.add_argument(
  1593. "--ref", default="commits", help="Notes ref (default: commits)"
  1594. )
  1595. args = parser.parse_args(args)
  1596. porcelain.notes_add(".", args.object, args.message, ref=args.ref)
  1597. class cmd_notes_show(Command):
  1598. """Show notes for a commit."""
  1599. def run(self, args) -> None:
  1600. parser = argparse.ArgumentParser()
  1601. parser.add_argument("object", help="Object to show notes for")
  1602. parser.add_argument(
  1603. "--ref", default="commits", help="Notes ref (default: commits)"
  1604. )
  1605. args = parser.parse_args(args)
  1606. note = porcelain.notes_show(".", args.object, ref=args.ref)
  1607. if note:
  1608. sys.stdout.buffer.write(note)
  1609. else:
  1610. print(f"No notes found for object {args.object}")
  1611. class cmd_notes_remove(Command):
  1612. """Remove notes for a commit."""
  1613. def run(self, args) -> None:
  1614. parser = argparse.ArgumentParser()
  1615. parser.add_argument("object", help="Object to remove notes from")
  1616. parser.add_argument(
  1617. "--ref", default="commits", help="Notes ref (default: commits)"
  1618. )
  1619. args = parser.parse_args(args)
  1620. result = porcelain.notes_remove(".", args.object, ref=args.ref)
  1621. if result:
  1622. print(f"Removed notes for object {args.object}")
  1623. else:
  1624. print(f"No notes found for object {args.object}")
  1625. class cmd_notes_list(Command):
  1626. """List all note objects."""
  1627. def run(self, args) -> None:
  1628. parser = argparse.ArgumentParser()
  1629. parser.add_argument(
  1630. "--ref", default="commits", help="Notes ref (default: commits)"
  1631. )
  1632. args = parser.parse_args(args)
  1633. notes = porcelain.notes_list(".", ref=args.ref)
  1634. for object_sha, note_content in notes:
  1635. print(f"{object_sha.hex()}")
  1636. class cmd_notes(SuperCommand):
  1637. """Add or inspect object notes."""
  1638. subcommands: ClassVar[dict[str, type[Command]]] = {
  1639. "add": cmd_notes_add,
  1640. "show": cmd_notes_show,
  1641. "remove": cmd_notes_remove,
  1642. "list": cmd_notes_list,
  1643. }
  1644. default_command = cmd_notes_list
  1645. class cmd_cherry_pick(Command):
  1646. """Apply the changes introduced by some existing commits."""
  1647. def run(self, args) -> Optional[int]:
  1648. parser = argparse.ArgumentParser(
  1649. description="Apply the changes introduced by some existing commits"
  1650. )
  1651. parser.add_argument("commit", nargs="?", help="Commit to cherry-pick")
  1652. parser.add_argument(
  1653. "-n",
  1654. "--no-commit",
  1655. action="store_true",
  1656. help="Apply changes without making a commit",
  1657. )
  1658. parser.add_argument(
  1659. "--continue",
  1660. dest="continue_",
  1661. action="store_true",
  1662. help="Continue after resolving conflicts",
  1663. )
  1664. parser.add_argument(
  1665. "--abort",
  1666. action="store_true",
  1667. help="Abort the current cherry-pick operation",
  1668. )
  1669. args = parser.parse_args(args)
  1670. # Check argument validity
  1671. if args.continue_ or args.abort:
  1672. if args.commit is not None:
  1673. parser.error("Cannot specify commit with --continue or --abort")
  1674. return 1
  1675. else:
  1676. if args.commit is None:
  1677. parser.error("Commit argument is required")
  1678. return 1
  1679. try:
  1680. commit_arg = args.commit
  1681. result = porcelain.cherry_pick(
  1682. ".",
  1683. commit_arg,
  1684. no_commit=args.no_commit,
  1685. continue_=args.continue_,
  1686. abort=args.abort,
  1687. )
  1688. if args.abort:
  1689. print("Cherry-pick aborted.")
  1690. elif args.continue_:
  1691. if result:
  1692. print(f"Cherry-pick completed: {result.decode()}")
  1693. else:
  1694. print("Cherry-pick completed.")
  1695. elif result is None:
  1696. if args.no_commit:
  1697. print("Cherry-pick applied successfully (no commit created).")
  1698. else:
  1699. # This shouldn't happen unless there were conflicts
  1700. print("Cherry-pick resulted in conflicts.")
  1701. else:
  1702. print(f"Cherry-pick successful: {result.decode()}")
  1703. return None
  1704. except porcelain.Error as e:
  1705. print(f"Error: {e}", file=sys.stderr)
  1706. return 1
  1707. class cmd_merge_tree(Command):
  1708. """Show three-way merge without touching index."""
  1709. def run(self, args) -> Optional[int]:
  1710. parser = argparse.ArgumentParser(
  1711. description="Perform a tree-level merge without touching the working directory"
  1712. )
  1713. parser.add_argument(
  1714. "base_tree",
  1715. nargs="?",
  1716. help="The common ancestor tree (optional, defaults to empty tree)",
  1717. )
  1718. parser.add_argument("our_tree", help="Our side of the merge")
  1719. parser.add_argument("their_tree", help="Their side of the merge")
  1720. parser.add_argument(
  1721. "-z",
  1722. "--name-only",
  1723. action="store_true",
  1724. help="Output only conflict paths, null-terminated",
  1725. )
  1726. args = parser.parse_args(args)
  1727. try:
  1728. # Determine base tree - if only two args provided, base is None
  1729. if args.base_tree is None:
  1730. # Only two arguments provided
  1731. base_tree = None
  1732. our_tree = args.our_tree
  1733. their_tree = args.their_tree
  1734. else:
  1735. # Three arguments provided
  1736. base_tree = args.base_tree
  1737. our_tree = args.our_tree
  1738. their_tree = args.their_tree
  1739. merged_tree_id, conflicts = porcelain.merge_tree(
  1740. ".", base_tree, our_tree, their_tree
  1741. )
  1742. if args.name_only:
  1743. # Output only conflict paths, null-terminated
  1744. for conflict_path in conflicts:
  1745. sys.stdout.buffer.write(conflict_path)
  1746. sys.stdout.buffer.write(b"\0")
  1747. else:
  1748. # Output the merged tree SHA
  1749. print(merged_tree_id.decode("ascii"))
  1750. # Output conflict information
  1751. if conflicts:
  1752. print(f"\nConflicts in {len(conflicts)} file(s):")
  1753. for conflict_path in conflicts:
  1754. print(f" {conflict_path.decode()}")
  1755. return None
  1756. except porcelain.Error as e:
  1757. print(f"Error: {e}", file=sys.stderr)
  1758. return 1
  1759. except KeyError as e:
  1760. print(f"Error: Object not found: {e}", file=sys.stderr)
  1761. return 1
  1762. class cmd_gc(Command):
  1763. """Cleanup unnecessary files and optimize the local repository."""
  1764. def run(self, args) -> Optional[int]:
  1765. import datetime
  1766. import time
  1767. parser = argparse.ArgumentParser()
  1768. parser.add_argument(
  1769. "--auto",
  1770. action="store_true",
  1771. help="Only run gc if needed",
  1772. )
  1773. parser.add_argument(
  1774. "--aggressive",
  1775. action="store_true",
  1776. help="Use more aggressive settings",
  1777. )
  1778. parser.add_argument(
  1779. "--no-prune",
  1780. action="store_true",
  1781. help="Do not prune unreachable objects",
  1782. )
  1783. parser.add_argument(
  1784. "--prune",
  1785. nargs="?",
  1786. const="now",
  1787. help="Prune unreachable objects older than date (default: 2 weeks ago)",
  1788. )
  1789. parser.add_argument(
  1790. "--dry-run",
  1791. "-n",
  1792. action="store_true",
  1793. help="Only report what would be done",
  1794. )
  1795. parser.add_argument(
  1796. "--quiet",
  1797. "-q",
  1798. action="store_true",
  1799. help="Only report errors",
  1800. )
  1801. args = parser.parse_args(args)
  1802. # Parse prune grace period
  1803. grace_period = None
  1804. if args.prune:
  1805. try:
  1806. grace_period = parse_relative_time(args.prune)
  1807. except ValueError:
  1808. # Try to parse as absolute date
  1809. try:
  1810. date = datetime.datetime.strptime(args.prune, "%Y-%m-%d")
  1811. grace_period = int(time.time() - date.timestamp())
  1812. except ValueError:
  1813. print(f"Error: Invalid prune date: {args.prune}")
  1814. return 1
  1815. elif not args.no_prune:
  1816. # Default to 2 weeks
  1817. grace_period = 1209600
  1818. # Progress callback
  1819. def progress(msg):
  1820. if not args.quiet:
  1821. print(msg)
  1822. try:
  1823. stats = porcelain.gc(
  1824. ".",
  1825. auto=args.auto,
  1826. aggressive=args.aggressive,
  1827. prune=not args.no_prune,
  1828. grace_period=grace_period,
  1829. dry_run=args.dry_run,
  1830. progress=progress if not args.quiet else None,
  1831. )
  1832. # Report results
  1833. if not args.quiet:
  1834. if args.dry_run:
  1835. print("\nDry run results:")
  1836. else:
  1837. print("\nGarbage collection complete:")
  1838. if stats.pruned_objects:
  1839. print(f" Pruned {len(stats.pruned_objects)} unreachable objects")
  1840. print(f" Freed {format_bytes(stats.bytes_freed)}")
  1841. if stats.packs_before != stats.packs_after:
  1842. print(
  1843. f" Reduced pack files from {stats.packs_before} to {stats.packs_after}"
  1844. )
  1845. except porcelain.Error as e:
  1846. print(f"Error: {e}")
  1847. return 1
  1848. return None
  1849. class cmd_count_objects(Command):
  1850. """Count unpacked number of objects and their disk consumption."""
  1851. def run(self, args) -> None:
  1852. parser = argparse.ArgumentParser()
  1853. parser.add_argument(
  1854. "-v",
  1855. "--verbose",
  1856. action="store_true",
  1857. help="Display verbose information.",
  1858. )
  1859. args = parser.parse_args(args)
  1860. if args.verbose:
  1861. stats = porcelain.count_objects(".", verbose=True)
  1862. # Display verbose output
  1863. print(f"count: {stats.count}")
  1864. print(f"size: {stats.size // 1024}") # Size in KiB
  1865. assert stats.in_pack is not None
  1866. print(f"in-pack: {stats.in_pack}")
  1867. assert stats.packs is not None
  1868. print(f"packs: {stats.packs}")
  1869. assert stats.size_pack is not None
  1870. print(f"size-pack: {stats.size_pack // 1024}") # Size in KiB
  1871. else:
  1872. # Simple output
  1873. stats = porcelain.count_objects(".", verbose=False)
  1874. print(f"{stats.count} objects, {stats.size // 1024} kilobytes")
  1875. class cmd_rebase(Command):
  1876. """Reapply commits on top of another base tip."""
  1877. def run(self, args) -> int:
  1878. parser = argparse.ArgumentParser()
  1879. parser.add_argument(
  1880. "upstream", nargs="?", help="Upstream branch to rebase onto"
  1881. )
  1882. parser.add_argument("--onto", type=str, help="Rebase onto specific commit")
  1883. parser.add_argument(
  1884. "--branch", type=str, help="Branch to rebase (default: current)"
  1885. )
  1886. parser.add_argument(
  1887. "--abort", action="store_true", help="Abort an in-progress rebase"
  1888. )
  1889. parser.add_argument(
  1890. "--continue",
  1891. dest="continue_rebase",
  1892. action="store_true",
  1893. help="Continue an in-progress rebase",
  1894. )
  1895. parser.add_argument(
  1896. "--skip", action="store_true", help="Skip current commit and continue"
  1897. )
  1898. args = parser.parse_args(args)
  1899. # Handle abort/continue/skip first
  1900. if args.abort:
  1901. try:
  1902. porcelain.rebase(".", args.upstream or "HEAD", abort=True)
  1903. print("Rebase aborted.")
  1904. except porcelain.Error as e:
  1905. print(f"Error: {e}")
  1906. return 1
  1907. return 0
  1908. if args.continue_rebase:
  1909. try:
  1910. new_shas = porcelain.rebase(
  1911. ".", args.upstream or "HEAD", continue_rebase=True
  1912. )
  1913. print("Rebase complete.")
  1914. except porcelain.Error as e:
  1915. print(f"Error: {e}")
  1916. return 1
  1917. return 0
  1918. # Normal rebase requires upstream
  1919. if not args.upstream:
  1920. print("Error: Missing required argument 'upstream'")
  1921. return 1
  1922. try:
  1923. new_shas = porcelain.rebase(
  1924. ".",
  1925. args.upstream,
  1926. onto=args.onto,
  1927. branch=args.branch,
  1928. )
  1929. if new_shas:
  1930. print(f"Successfully rebased {len(new_shas)} commits.")
  1931. else:
  1932. print("Already up to date.")
  1933. return 0
  1934. except porcelain.Error as e:
  1935. print(f"Error: {e}")
  1936. return 1
  1937. class cmd_filter_branch(Command):
  1938. """Rewrite branches."""
  1939. def run(self, args) -> Optional[int]:
  1940. import subprocess
  1941. parser = argparse.ArgumentParser(description="Rewrite branches")
  1942. # Supported Git-compatible options
  1943. parser.add_argument(
  1944. "--subdirectory-filter",
  1945. type=str,
  1946. help="Only include history for subdirectory",
  1947. )
  1948. parser.add_argument("--env-filter", type=str, help="Environment filter command")
  1949. parser.add_argument("--tree-filter", type=str, help="Tree filter command")
  1950. parser.add_argument("--index-filter", type=str, help="Index filter command")
  1951. parser.add_argument("--parent-filter", type=str, help="Parent filter command")
  1952. parser.add_argument("--msg-filter", type=str, help="Message filter command")
  1953. parser.add_argument("--commit-filter", type=str, help="Commit filter command")
  1954. parser.add_argument(
  1955. "--tag-name-filter", type=str, help="Tag name filter command"
  1956. )
  1957. parser.add_argument(
  1958. "--prune-empty", action="store_true", help="Remove empty commits"
  1959. )
  1960. parser.add_argument(
  1961. "--original",
  1962. type=str,
  1963. default="refs/original",
  1964. help="Namespace for original refs",
  1965. )
  1966. parser.add_argument(
  1967. "-f",
  1968. "--force",
  1969. action="store_true",
  1970. help="Force operation even if refs/original/* exists",
  1971. )
  1972. # Branch/ref to rewrite (defaults to HEAD)
  1973. parser.add_argument(
  1974. "branch", nargs="?", default="HEAD", help="Branch or ref to rewrite"
  1975. )
  1976. args = parser.parse_args(args)
  1977. # Track if any filter fails
  1978. filter_error = False
  1979. # Setup environment for filters
  1980. env = os.environ.copy()
  1981. # Helper function to run shell commands
  1982. def run_filter(cmd, input_data=None, cwd=None, extra_env=None):
  1983. nonlocal filter_error
  1984. filter_env = env.copy()
  1985. if extra_env:
  1986. filter_env.update(extra_env)
  1987. result = subprocess.run(
  1988. cmd,
  1989. shell=True,
  1990. input=input_data,
  1991. cwd=cwd,
  1992. env=filter_env,
  1993. capture_output=True,
  1994. )
  1995. if result.returncode != 0:
  1996. filter_error = True
  1997. return None
  1998. return result.stdout
  1999. # Create filter functions based on arguments
  2000. filter_message = None
  2001. if args.msg_filter:
  2002. def filter_message(message):
  2003. result = run_filter(args.msg_filter, input_data=message)
  2004. return result if result is not None else message
  2005. tree_filter = None
  2006. if args.tree_filter:
  2007. def tree_filter(tree_sha, tmpdir):
  2008. from dulwich.objects import Blob, Tree
  2009. # Export tree to tmpdir
  2010. with Repo(".") as r:
  2011. tree = r.object_store[tree_sha]
  2012. for entry in tree.items():
  2013. path = Path(tmpdir) / entry.path.decode()
  2014. if entry.mode & 0o040000: # Directory
  2015. path.mkdir(exist_ok=True)
  2016. else:
  2017. obj = r.object_store[entry.sha]
  2018. path.write_bytes(obj.data)
  2019. # Run the filter command in the temp directory
  2020. run_filter(args.tree_filter, cwd=tmpdir)
  2021. # Rebuild tree from modified temp directory
  2022. def build_tree_from_dir(dir_path):
  2023. tree = Tree()
  2024. for name in sorted(os.listdir(dir_path)):
  2025. if name.startswith("."):
  2026. continue
  2027. path = os.path.join(dir_path, name)
  2028. if os.path.isdir(path):
  2029. subtree_sha = build_tree_from_dir(path)
  2030. tree.add(name.encode(), 0o040000, subtree_sha)
  2031. else:
  2032. with open(path, "rb") as f:
  2033. data = f.read()
  2034. blob = Blob.from_string(data)
  2035. r.object_store.add_object(blob)
  2036. # Use appropriate file mode
  2037. mode = os.stat(path).st_mode
  2038. if mode & 0o100:
  2039. file_mode = 0o100755
  2040. else:
  2041. file_mode = 0o100644
  2042. tree.add(name.encode(), file_mode, blob.id)
  2043. r.object_store.add_object(tree)
  2044. return tree.id
  2045. return build_tree_from_dir(tmpdir)
  2046. index_filter = None
  2047. if args.index_filter:
  2048. def index_filter(tree_sha, index_path):
  2049. run_filter(args.index_filter, extra_env={"GIT_INDEX_FILE": index_path})
  2050. return None # Read back from index
  2051. parent_filter = None
  2052. if args.parent_filter:
  2053. def parent_filter(parents):
  2054. parent_str = " ".join(p.hex() for p in parents)
  2055. result = run_filter(args.parent_filter, input_data=parent_str.encode())
  2056. if result is None:
  2057. return parents
  2058. output = result.decode().strip()
  2059. if not output:
  2060. return []
  2061. new_parents = []
  2062. for sha in output.split():
  2063. if valid_hexsha(sha):
  2064. new_parents.append(sha)
  2065. return new_parents
  2066. commit_filter = None
  2067. if args.commit_filter:
  2068. def commit_filter(commit_obj, tree_sha):
  2069. # The filter receives: tree parent1 parent2...
  2070. cmd_input = tree_sha.hex()
  2071. for parent in commit_obj.parents:
  2072. cmd_input += " " + parent.hex()
  2073. result = run_filter(
  2074. args.commit_filter,
  2075. input_data=cmd_input.encode(),
  2076. extra_env={"GIT_COMMIT": commit_obj.id.hex()},
  2077. )
  2078. if result is None:
  2079. return None
  2080. output = result.decode().strip()
  2081. if not output:
  2082. return None # Skip commit
  2083. if valid_hexsha(output):
  2084. return output
  2085. return None
  2086. tag_name_filter = None
  2087. if args.tag_name_filter:
  2088. def tag_name_filter(tag_name):
  2089. result = run_filter(args.tag_name_filter, input_data=tag_name)
  2090. return result.strip() if result is not None else tag_name
  2091. # Open repo once
  2092. with Repo(".") as r:
  2093. # Check for refs/original if not forcing
  2094. if not args.force:
  2095. original_prefix = args.original.encode() + b"/"
  2096. for ref in r.refs.allkeys():
  2097. if ref.startswith(original_prefix):
  2098. print("Cannot create a new backup.")
  2099. print(f"A previous backup already exists in {args.original}/")
  2100. print("Force overwriting the backup with -f")
  2101. return 1
  2102. try:
  2103. # Call porcelain.filter_branch with the repo object
  2104. result = porcelain.filter_branch(
  2105. r,
  2106. args.branch,
  2107. filter_message=filter_message,
  2108. tree_filter=tree_filter if args.tree_filter else None,
  2109. index_filter=index_filter if args.index_filter else None,
  2110. parent_filter=parent_filter if args.parent_filter else None,
  2111. commit_filter=commit_filter if args.commit_filter else None,
  2112. subdirectory_filter=args.subdirectory_filter,
  2113. prune_empty=args.prune_empty,
  2114. tag_name_filter=tag_name_filter if args.tag_name_filter else None,
  2115. force=args.force,
  2116. keep_original=True, # Always keep original with git
  2117. )
  2118. # Check if any filter failed
  2119. if filter_error:
  2120. print("Error: Filter command failed", file=sys.stderr)
  2121. return 1
  2122. # Git filter-branch shows progress
  2123. if result:
  2124. print(f"Rewrite {args.branch} ({len(result)} commits)")
  2125. # Git shows: Ref 'refs/heads/branch' was rewritten
  2126. if args.branch != "HEAD":
  2127. ref_name = (
  2128. args.branch
  2129. if args.branch.startswith("refs/")
  2130. else f"refs/heads/{args.branch}"
  2131. )
  2132. print(f"Ref '{ref_name}' was rewritten")
  2133. return 0
  2134. except porcelain.Error as e:
  2135. print(f"Error: {e}", file=sys.stderr)
  2136. return 1
  2137. class cmd_lfs(Command):
  2138. """Git Large File Storage management."""
  2139. """Git LFS management commands."""
  2140. def run(self, argv) -> None:
  2141. parser = argparse.ArgumentParser(prog="dulwich lfs")
  2142. subparsers = parser.add_subparsers(dest="subcommand", help="LFS subcommands")
  2143. # lfs init
  2144. subparsers.add_parser("init", help="Initialize Git LFS")
  2145. # lfs track
  2146. parser_track = subparsers.add_parser(
  2147. "track", help="Track file patterns with LFS"
  2148. )
  2149. parser_track.add_argument("patterns", nargs="*", help="File patterns to track")
  2150. # lfs untrack
  2151. parser_untrack = subparsers.add_parser(
  2152. "untrack", help="Untrack file patterns from LFS"
  2153. )
  2154. parser_untrack.add_argument(
  2155. "patterns", nargs="+", help="File patterns to untrack"
  2156. )
  2157. # lfs ls-files
  2158. parser_ls = subparsers.add_parser("ls-files", help="List LFS files")
  2159. parser_ls.add_argument("--ref", help="Git ref to check (defaults to HEAD)")
  2160. # lfs migrate
  2161. parser_migrate = subparsers.add_parser("migrate", help="Migrate files to LFS")
  2162. parser_migrate.add_argument("--include", nargs="+", help="Patterns to include")
  2163. parser_migrate.add_argument("--exclude", nargs="+", help="Patterns to exclude")
  2164. parser_migrate.add_argument(
  2165. "--everything", action="store_true", help="Migrate all files above 100MB"
  2166. )
  2167. # lfs pointer
  2168. parser_pointer = subparsers.add_parser("pointer", help="Check LFS pointers")
  2169. parser_pointer.add_argument(
  2170. "--check", nargs="*", dest="paths", help="Check if files are LFS pointers"
  2171. )
  2172. # lfs clean
  2173. parser_clean = subparsers.add_parser("clean", help="Clean file to LFS pointer")
  2174. parser_clean.add_argument("path", help="File path to clean")
  2175. # lfs smudge
  2176. parser_smudge = subparsers.add_parser(
  2177. "smudge", help="Smudge LFS pointer to content"
  2178. )
  2179. parser_smudge.add_argument(
  2180. "--stdin", action="store_true", help="Read pointer from stdin"
  2181. )
  2182. # lfs fetch
  2183. parser_fetch = subparsers.add_parser(
  2184. "fetch", help="Fetch LFS objects from remote"
  2185. )
  2186. parser_fetch.add_argument(
  2187. "--remote", default="origin", help="Remote to fetch from"
  2188. )
  2189. parser_fetch.add_argument("refs", nargs="*", help="Specific refs to fetch")
  2190. # lfs pull
  2191. parser_pull = subparsers.add_parser(
  2192. "pull", help="Pull LFS objects for current checkout"
  2193. )
  2194. parser_pull.add_argument(
  2195. "--remote", default="origin", help="Remote to pull from"
  2196. )
  2197. # lfs push
  2198. parser_push = subparsers.add_parser("push", help="Push LFS objects to remote")
  2199. parser_push.add_argument("--remote", default="origin", help="Remote to push to")
  2200. parser_push.add_argument("refs", nargs="*", help="Specific refs to push")
  2201. # lfs status
  2202. subparsers.add_parser("status", help="Show status of LFS files")
  2203. args = parser.parse_args(argv)
  2204. if args.subcommand == "init":
  2205. porcelain.lfs_init()
  2206. print("Git LFS initialized.")
  2207. elif args.subcommand == "track":
  2208. if args.patterns:
  2209. tracked = porcelain.lfs_track(patterns=args.patterns)
  2210. print("Tracking patterns:")
  2211. else:
  2212. tracked = porcelain.lfs_track()
  2213. print("Currently tracked patterns:")
  2214. for pattern in tracked:
  2215. print(f" {pattern}")
  2216. elif args.subcommand == "untrack":
  2217. tracked = porcelain.lfs_untrack(patterns=args.patterns)
  2218. print("Remaining tracked patterns:")
  2219. for pattern in tracked:
  2220. print(f" {pattern}")
  2221. elif args.subcommand == "ls-files":
  2222. files = porcelain.lfs_ls_files(ref=args.ref)
  2223. for path, oid, size in files:
  2224. print(f"{oid[:12]} * {path} ({format_bytes(size)})")
  2225. elif args.subcommand == "migrate":
  2226. count = porcelain.lfs_migrate(
  2227. include=args.include, exclude=args.exclude, everything=args.everything
  2228. )
  2229. print(f"Migrated {count} file(s) to Git LFS.")
  2230. elif args.subcommand == "pointer":
  2231. if args.paths is not None:
  2232. results = porcelain.lfs_pointer_check(paths=args.paths or None)
  2233. for path, pointer in results.items():
  2234. if pointer:
  2235. print(
  2236. f"{path}: LFS pointer (oid: {pointer.oid[:12]}, size: {format_bytes(pointer.size)})"
  2237. )
  2238. else:
  2239. print(f"{path}: Not an LFS pointer")
  2240. elif args.subcommand == "clean":
  2241. pointer = porcelain.lfs_clean(path=args.path)
  2242. sys.stdout.buffer.write(pointer)
  2243. elif args.subcommand == "smudge":
  2244. if args.stdin:
  2245. pointer_content = sys.stdin.buffer.read()
  2246. content = porcelain.lfs_smudge(pointer_content=pointer_content)
  2247. sys.stdout.buffer.write(content)
  2248. else:
  2249. print("Error: --stdin required for smudge command")
  2250. sys.exit(1)
  2251. elif args.subcommand == "fetch":
  2252. refs = args.refs or None
  2253. count = porcelain.lfs_fetch(remote=args.remote, refs=refs)
  2254. print(f"Fetched {count} LFS object(s).")
  2255. elif args.subcommand == "pull":
  2256. count = porcelain.lfs_pull(remote=args.remote)
  2257. print(f"Pulled {count} LFS object(s).")
  2258. elif args.subcommand == "push":
  2259. refs = args.refs or None
  2260. count = porcelain.lfs_push(remote=args.remote, refs=refs)
  2261. print(f"Pushed {count} LFS object(s).")
  2262. elif args.subcommand == "status":
  2263. status = porcelain.lfs_status()
  2264. if status["tracked"]:
  2265. print(f"LFS tracked files: {len(status['tracked'])}")
  2266. if status["missing"]:
  2267. print("\nMissing LFS objects:")
  2268. for path in status["missing"]:
  2269. print(f" {path}")
  2270. if status["not_staged"]:
  2271. print("\nModified LFS files not staged:")
  2272. for path in status["not_staged"]:
  2273. print(f" {path}")
  2274. if not any(status.values()):
  2275. print("No LFS files found.")
  2276. else:
  2277. parser.print_help()
  2278. sys.exit(1)
  2279. class cmd_help(Command):
  2280. """Display help information about git."""
  2281. def run(self, args) -> None:
  2282. parser = argparse.ArgumentParser()
  2283. parser.add_argument(
  2284. "-a",
  2285. "--all",
  2286. action="store_true",
  2287. help="List all commands.",
  2288. )
  2289. args = parser.parse_args(args)
  2290. if args.all:
  2291. print("Available commands:")
  2292. for cmd in sorted(commands):
  2293. print(f" {cmd}")
  2294. else:
  2295. print(
  2296. """\
  2297. The dulwich command line tool is currently a very basic frontend for the
  2298. Dulwich python module. For full functionality, please see the API reference.
  2299. For a list of supported commands, see 'dulwich help -a'.
  2300. """
  2301. )
  2302. class cmd_format_patch(Command):
  2303. """Prepare patches for e-mail submission."""
  2304. def run(self, args) -> None:
  2305. parser = argparse.ArgumentParser()
  2306. parser.add_argument(
  2307. "committish",
  2308. nargs="?",
  2309. help="Commit or commit range (e.g., HEAD~3..HEAD or origin/master..HEAD)",
  2310. )
  2311. parser.add_argument(
  2312. "-n",
  2313. "--numbered",
  2314. type=int,
  2315. default=1,
  2316. help="Number of commits to format (default: 1)",
  2317. )
  2318. parser.add_argument(
  2319. "-o",
  2320. "--output-directory",
  2321. dest="outdir",
  2322. help="Output directory for patches",
  2323. )
  2324. parser.add_argument(
  2325. "--stdout",
  2326. action="store_true",
  2327. help="Output patches to stdout",
  2328. )
  2329. args = parser.parse_args(args)
  2330. # Parse committish using the new function
  2331. committish = None
  2332. if args.committish:
  2333. with Repo(".") as r:
  2334. range_result = parse_commit_range(r, args.committish)
  2335. if range_result:
  2336. committish = range_result
  2337. else:
  2338. committish = args.committish
  2339. filenames = porcelain.format_patch(
  2340. ".",
  2341. committish=committish,
  2342. outstream=sys.stdout,
  2343. outdir=args.outdir,
  2344. n=args.numbered,
  2345. stdout=args.stdout,
  2346. )
  2347. if not args.stdout:
  2348. for filename in filenames:
  2349. print(filename)
  2350. class cmd_bundle(Command):
  2351. """Create, unpack, and manipulate bundle files."""
  2352. def run(self, args) -> int:
  2353. if not args:
  2354. print("Usage: bundle <create|verify|list-heads|unbundle> <options>")
  2355. return 1
  2356. subcommand = args[0]
  2357. subargs = args[1:]
  2358. if subcommand == "create":
  2359. return self._create(subargs)
  2360. elif subcommand == "verify":
  2361. return self._verify(subargs)
  2362. elif subcommand == "list-heads":
  2363. return self._list_heads(subargs)
  2364. elif subcommand == "unbundle":
  2365. return self._unbundle(subargs)
  2366. else:
  2367. print(f"Unknown bundle subcommand: {subcommand}")
  2368. return 1
  2369. def _create(self, args) -> int:
  2370. parser = argparse.ArgumentParser(prog="bundle create")
  2371. parser.add_argument(
  2372. "-q", "--quiet", action="store_true", help="Suppress progress"
  2373. )
  2374. parser.add_argument("--progress", action="store_true", help="Show progress")
  2375. parser.add_argument(
  2376. "--version", type=int, choices=[2, 3], help="Bundle version"
  2377. )
  2378. parser.add_argument("--all", action="store_true", help="Include all refs")
  2379. parser.add_argument("--stdin", action="store_true", help="Read refs from stdin")
  2380. parser.add_argument("file", help="Output bundle file (use - for stdout)")
  2381. parser.add_argument("refs", nargs="*", help="References or rev-list args")
  2382. parsed_args = parser.parse_args(args)
  2383. repo = Repo(".")
  2384. progress = None
  2385. if parsed_args.progress and not parsed_args.quiet:
  2386. def progress(msg: str) -> None:
  2387. print(msg, file=sys.stderr)
  2388. refs_to_include = []
  2389. prerequisites = []
  2390. if parsed_args.all:
  2391. refs_to_include = list(repo.refs.keys())
  2392. elif parsed_args.stdin:
  2393. for line in sys.stdin:
  2394. ref = line.strip().encode("utf-8")
  2395. if ref:
  2396. refs_to_include.append(ref)
  2397. elif parsed_args.refs:
  2398. for ref_arg in parsed_args.refs:
  2399. if ".." in ref_arg:
  2400. range_result = parse_commit_range(repo, ref_arg)
  2401. if range_result:
  2402. start_commit, end_commit = range_result
  2403. prerequisites.append(start_commit.id)
  2404. # For ranges like A..B, we need to include B if it's a ref
  2405. # Split the range to get the end part
  2406. end_part = ref_arg.split("..")[1]
  2407. if end_part: # Not empty (not "A..")
  2408. end_ref = end_part.encode("utf-8")
  2409. if end_ref in repo.refs:
  2410. refs_to_include.append(end_ref)
  2411. else:
  2412. sha = repo.refs[ref_arg.encode("utf-8")]
  2413. refs_to_include.append(ref_arg.encode("utf-8"))
  2414. else:
  2415. if ref_arg.startswith("^"):
  2416. sha = repo.refs[ref_arg[1:].encode("utf-8")]
  2417. prerequisites.append(sha)
  2418. else:
  2419. sha = repo.refs[ref_arg.encode("utf-8")]
  2420. refs_to_include.append(ref_arg.encode("utf-8"))
  2421. else:
  2422. print("No refs specified. Use --all, --stdin, or specify refs")
  2423. return 1
  2424. if not refs_to_include:
  2425. print("fatal: Refusing to create empty bundle.")
  2426. return 1
  2427. bundle = create_bundle_from_repo(
  2428. repo,
  2429. refs=refs_to_include,
  2430. prerequisites=prerequisites,
  2431. version=parsed_args.version,
  2432. progress=progress,
  2433. )
  2434. if parsed_args.file == "-":
  2435. write_bundle(sys.stdout.buffer, bundle)
  2436. else:
  2437. with open(parsed_args.file, "wb") as f:
  2438. write_bundle(f, bundle)
  2439. return 0
  2440. def _verify(self, args) -> int:
  2441. parser = argparse.ArgumentParser(prog="bundle verify")
  2442. parser.add_argument(
  2443. "-q", "--quiet", action="store_true", help="Suppress output"
  2444. )
  2445. parser.add_argument("file", help="Bundle file to verify (use - for stdin)")
  2446. parsed_args = parser.parse_args(args)
  2447. repo = Repo(".")
  2448. def verify_bundle(bundle):
  2449. missing_prereqs = []
  2450. for prereq_sha, comment in bundle.prerequisites:
  2451. try:
  2452. repo.object_store[prereq_sha]
  2453. except KeyError:
  2454. missing_prereqs.append(prereq_sha)
  2455. if missing_prereqs:
  2456. if not parsed_args.quiet:
  2457. print("The bundle requires these prerequisite commits:")
  2458. for sha in missing_prereqs:
  2459. print(f" {sha.decode()}")
  2460. return 1
  2461. else:
  2462. if not parsed_args.quiet:
  2463. print(
  2464. "The bundle is valid and can be applied to the current repository"
  2465. )
  2466. return 0
  2467. if parsed_args.file == "-":
  2468. bundle = read_bundle(sys.stdin.buffer)
  2469. return verify_bundle(bundle)
  2470. else:
  2471. with open(parsed_args.file, "rb") as f:
  2472. bundle = read_bundle(f)
  2473. return verify_bundle(bundle)
  2474. def _list_heads(self, args) -> int:
  2475. parser = argparse.ArgumentParser(prog="bundle list-heads")
  2476. parser.add_argument("file", help="Bundle file (use - for stdin)")
  2477. parser.add_argument("refnames", nargs="*", help="Only show these refs")
  2478. parsed_args = parser.parse_args(args)
  2479. def list_heads(bundle):
  2480. for ref, sha in bundle.references.items():
  2481. if not parsed_args.refnames or ref.decode() in parsed_args.refnames:
  2482. print(f"{sha.decode()} {ref.decode()}")
  2483. if parsed_args.file == "-":
  2484. bundle = read_bundle(sys.stdin.buffer)
  2485. list_heads(bundle)
  2486. else:
  2487. with open(parsed_args.file, "rb") as f:
  2488. bundle = read_bundle(f)
  2489. list_heads(bundle)
  2490. return 0
  2491. def _unbundle(self, args) -> int:
  2492. parser = argparse.ArgumentParser(prog="bundle unbundle")
  2493. parser.add_argument("--progress", action="store_true", help="Show progress")
  2494. parser.add_argument("file", help="Bundle file (use - for stdin)")
  2495. parser.add_argument("refnames", nargs="*", help="Only unbundle these refs")
  2496. parsed_args = parser.parse_args(args)
  2497. repo = Repo(".")
  2498. progress = None
  2499. if parsed_args.progress:
  2500. def progress(msg: str) -> None:
  2501. print(msg, file=sys.stderr)
  2502. if parsed_args.file == "-":
  2503. bundle = read_bundle(sys.stdin.buffer)
  2504. # Process the bundle while file is still available via stdin
  2505. bundle.store_objects(repo.object_store, progress=progress)
  2506. else:
  2507. # Keep the file open during bundle processing
  2508. with open(parsed_args.file, "rb") as f:
  2509. bundle = read_bundle(f)
  2510. # Process pack data while file is still open
  2511. bundle.store_objects(repo.object_store, progress=progress)
  2512. for ref, sha in bundle.references.items():
  2513. if not parsed_args.refnames or ref.decode() in parsed_args.refnames:
  2514. print(ref.decode())
  2515. return 0
  2516. class cmd_worktree_add(Command):
  2517. """Create a new worktree."""
  2518. """Add a new worktree to the repository."""
  2519. def run(self, args) -> Optional[int]:
  2520. parser = argparse.ArgumentParser(
  2521. description="Add a new worktree", prog="dulwich worktree add"
  2522. )
  2523. parser.add_argument("path", help="Path for the new worktree")
  2524. parser.add_argument("committish", nargs="?", help="Commit-ish to checkout")
  2525. parser.add_argument("-b", "--create-branch", help="Create a new branch")
  2526. parser.add_argument(
  2527. "-B", "--force-create-branch", help="Create or reset a branch"
  2528. )
  2529. parser.add_argument(
  2530. "--detach", action="store_true", help="Detach HEAD in new worktree"
  2531. )
  2532. parser.add_argument("--force", action="store_true", help="Force creation")
  2533. parsed_args = parser.parse_args(args)
  2534. from dulwich import porcelain
  2535. branch = None
  2536. commit = None
  2537. if parsed_args.create_branch or parsed_args.force_create_branch:
  2538. branch = (
  2539. parsed_args.create_branch or parsed_args.force_create_branch
  2540. ).encode()
  2541. elif parsed_args.committish and not parsed_args.detach:
  2542. # If committish is provided and not detaching, treat as branch
  2543. branch = parsed_args.committish.encode()
  2544. elif parsed_args.committish:
  2545. # If committish is provided and detaching, treat as commit
  2546. commit = parsed_args.committish.encode()
  2547. worktree_path = porcelain.worktree_add(
  2548. repo=".",
  2549. path=parsed_args.path,
  2550. branch=branch,
  2551. commit=commit,
  2552. detach=parsed_args.detach,
  2553. force=parsed_args.force or bool(parsed_args.force_create_branch),
  2554. )
  2555. print(f"Worktree added: {worktree_path}")
  2556. return 0
  2557. class cmd_worktree_list(Command):
  2558. """List worktrees."""
  2559. """List details of each worktree."""
  2560. def run(self, args) -> Optional[int]:
  2561. parser = argparse.ArgumentParser(
  2562. description="List worktrees", prog="dulwich worktree list"
  2563. )
  2564. parser.add_argument(
  2565. "-v", "--verbose", action="store_true", help="Show additional information"
  2566. )
  2567. parser.add_argument(
  2568. "--porcelain", action="store_true", help="Machine-readable output"
  2569. )
  2570. parsed_args = parser.parse_args(args)
  2571. from dulwich import porcelain
  2572. worktrees = porcelain.worktree_list(repo=".")
  2573. for wt in worktrees:
  2574. path = wt.path
  2575. if wt.bare:
  2576. status = "(bare)"
  2577. elif wt.detached:
  2578. status = (
  2579. f"(detached HEAD {wt.head[:7].decode() if wt.head else 'unknown'})"
  2580. )
  2581. elif wt.branch:
  2582. branch_name = wt.branch.decode().replace("refs/heads/", "")
  2583. status = f"[{branch_name}]"
  2584. else:
  2585. status = "(unknown)"
  2586. if parsed_args.porcelain:
  2587. locked = "locked" if wt.locked else "unlocked"
  2588. prunable = "prunable" if wt.prunable else "unprunable"
  2589. print(
  2590. f"{path} {wt.head.decode() if wt.head else 'unknown'} {status} {locked} {prunable}"
  2591. )
  2592. else:
  2593. line = f"{path} {status}"
  2594. if wt.locked:
  2595. line += " locked"
  2596. if wt.prunable:
  2597. line += " prunable"
  2598. print(line)
  2599. return 0
  2600. class cmd_worktree_remove(Command):
  2601. """Remove a worktree."""
  2602. """Remove a worktree."""
  2603. def run(self, args) -> Optional[int]:
  2604. parser = argparse.ArgumentParser(
  2605. description="Remove a worktree", prog="dulwich worktree remove"
  2606. )
  2607. parser.add_argument("worktree", help="Path to worktree to remove")
  2608. parser.add_argument("--force", action="store_true", help="Force removal")
  2609. parsed_args = parser.parse_args(args)
  2610. from dulwich import porcelain
  2611. porcelain.worktree_remove(
  2612. repo=".", path=parsed_args.worktree, force=parsed_args.force
  2613. )
  2614. print(f"Worktree removed: {parsed_args.worktree}")
  2615. return 0
  2616. class cmd_worktree_prune(Command):
  2617. """Prune worktree information."""
  2618. """Prune worktree information."""
  2619. def run(self, args) -> Optional[int]:
  2620. parser = argparse.ArgumentParser(
  2621. description="Prune worktree information", prog="dulwich worktree prune"
  2622. )
  2623. parser.add_argument(
  2624. "--dry-run", action="store_true", help="Do not remove anything"
  2625. )
  2626. parser.add_argument(
  2627. "-v", "--verbose", action="store_true", help="Report all removals"
  2628. )
  2629. parser.add_argument(
  2630. "--expire", type=int, help="Expire worktrees older than time (seconds)"
  2631. )
  2632. parsed_args = parser.parse_args(args)
  2633. from dulwich import porcelain
  2634. pruned = porcelain.worktree_prune(
  2635. repo=".", dry_run=parsed_args.dry_run, expire=parsed_args.expire
  2636. )
  2637. if pruned:
  2638. if parsed_args.dry_run:
  2639. print("Would prune worktrees:")
  2640. elif parsed_args.verbose:
  2641. print("Pruned worktrees:")
  2642. for wt_id in pruned:
  2643. print(f" {wt_id}")
  2644. elif parsed_args.verbose:
  2645. print("No worktrees to prune")
  2646. return 0
  2647. class cmd_worktree_lock(Command):
  2648. """Lock a worktree to prevent it from being pruned."""
  2649. """Lock a worktree."""
  2650. def run(self, args) -> Optional[int]:
  2651. parser = argparse.ArgumentParser(
  2652. description="Lock a worktree", prog="dulwich worktree lock"
  2653. )
  2654. parser.add_argument("worktree", help="Path to worktree to lock")
  2655. parser.add_argument("--reason", help="Reason for locking")
  2656. parsed_args = parser.parse_args(args)
  2657. from dulwich import porcelain
  2658. porcelain.worktree_lock(
  2659. repo=".", path=parsed_args.worktree, reason=parsed_args.reason
  2660. )
  2661. print(f"Worktree locked: {parsed_args.worktree}")
  2662. return 0
  2663. class cmd_worktree_unlock(Command):
  2664. """Unlock a locked worktree."""
  2665. """Unlock a worktree."""
  2666. def run(self, args) -> Optional[int]:
  2667. parser = argparse.ArgumentParser(
  2668. description="Unlock a worktree", prog="dulwich worktree unlock"
  2669. )
  2670. parser.add_argument("worktree", help="Path to worktree to unlock")
  2671. parsed_args = parser.parse_args(args)
  2672. from dulwich import porcelain
  2673. porcelain.worktree_unlock(repo=".", path=parsed_args.worktree)
  2674. print(f"Worktree unlocked: {parsed_args.worktree}")
  2675. return 0
  2676. class cmd_worktree_move(Command):
  2677. """Move a worktree to a new location."""
  2678. """Move a worktree."""
  2679. def run(self, args) -> Optional[int]:
  2680. parser = argparse.ArgumentParser(
  2681. description="Move a worktree", prog="dulwich worktree move"
  2682. )
  2683. parser.add_argument("worktree", help="Path to worktree to move")
  2684. parser.add_argument("new_path", help="New path for the worktree")
  2685. parsed_args = parser.parse_args(args)
  2686. from dulwich import porcelain
  2687. porcelain.worktree_move(
  2688. repo=".", old_path=parsed_args.worktree, new_path=parsed_args.new_path
  2689. )
  2690. print(f"Worktree moved: {parsed_args.worktree} -> {parsed_args.new_path}")
  2691. return 0
  2692. class cmd_worktree(SuperCommand):
  2693. """Manage multiple working trees."""
  2694. """Manage multiple working trees."""
  2695. subcommands: ClassVar[dict[str, type[Command]]] = {
  2696. "add": cmd_worktree_add,
  2697. "list": cmd_worktree_list,
  2698. "remove": cmd_worktree_remove,
  2699. "prune": cmd_worktree_prune,
  2700. "lock": cmd_worktree_lock,
  2701. "unlock": cmd_worktree_unlock,
  2702. "move": cmd_worktree_move,
  2703. }
  2704. default_command = cmd_worktree_list
  2705. commands = {
  2706. "add": cmd_add,
  2707. "annotate": cmd_annotate,
  2708. "archive": cmd_archive,
  2709. "bisect": cmd_bisect,
  2710. "blame": cmd_blame,
  2711. "branch": cmd_branch,
  2712. "bundle": cmd_bundle,
  2713. "check-ignore": cmd_check_ignore,
  2714. "check-mailmap": cmd_check_mailmap,
  2715. "checkout": cmd_checkout,
  2716. "cherry-pick": cmd_cherry_pick,
  2717. "clone": cmd_clone,
  2718. "commit": cmd_commit,
  2719. "commit-tree": cmd_commit_tree,
  2720. "count-objects": cmd_count_objects,
  2721. "describe": cmd_describe,
  2722. "daemon": cmd_daemon,
  2723. "diff": cmd_diff,
  2724. "diff-tree": cmd_diff_tree,
  2725. "dump-pack": cmd_dump_pack,
  2726. "dump-index": cmd_dump_index,
  2727. "fetch-pack": cmd_fetch_pack,
  2728. "fetch": cmd_fetch,
  2729. "filter-branch": cmd_filter_branch,
  2730. "for-each-ref": cmd_for_each_ref,
  2731. "format-patch": cmd_format_patch,
  2732. "fsck": cmd_fsck,
  2733. "gc": cmd_gc,
  2734. "help": cmd_help,
  2735. "init": cmd_init,
  2736. "lfs": cmd_lfs,
  2737. "log": cmd_log,
  2738. "ls-files": cmd_ls_files,
  2739. "ls-remote": cmd_ls_remote,
  2740. "ls-tree": cmd_ls_tree,
  2741. "merge": cmd_merge,
  2742. "merge-tree": cmd_merge_tree,
  2743. "notes": cmd_notes,
  2744. "pack-objects": cmd_pack_objects,
  2745. "pack-refs": cmd_pack_refs,
  2746. "prune": cmd_prune,
  2747. "pull": cmd_pull,
  2748. "push": cmd_push,
  2749. "rebase": cmd_rebase,
  2750. "receive-pack": cmd_receive_pack,
  2751. "reflog": cmd_reflog,
  2752. "remote": cmd_remote,
  2753. "repack": cmd_repack,
  2754. "reset": cmd_reset,
  2755. "revert": cmd_revert,
  2756. "rev-list": cmd_rev_list,
  2757. "rm": cmd_rm,
  2758. "mv": cmd_mv,
  2759. "show": cmd_show,
  2760. "stash": cmd_stash,
  2761. "status": cmd_status,
  2762. "symbolic-ref": cmd_symbolic_ref,
  2763. "submodule": cmd_submodule,
  2764. "tag": cmd_tag,
  2765. "unpack-objects": cmd_unpack_objects,
  2766. "update-server-info": cmd_update_server_info,
  2767. "upload-pack": cmd_upload_pack,
  2768. "web-daemon": cmd_web_daemon,
  2769. "worktree": cmd_worktree,
  2770. "write-tree": cmd_write_tree,
  2771. }
  2772. def main(argv=None) -> Optional[int]:
  2773. if argv is None:
  2774. argv = sys.argv[1:]
  2775. # Parse only the global options and command, stop at first positional
  2776. parser = argparse.ArgumentParser(
  2777. prog="dulwich",
  2778. description="Simple command-line interface to Dulwich",
  2779. add_help=False, # We'll handle help ourselves
  2780. )
  2781. parser.add_argument("--no-pager", action="store_true", help="Disable pager")
  2782. parser.add_argument("--pager", action="store_true", help="Force enable pager")
  2783. parser.add_argument("--help", "-h", action="store_true", help="Show help")
  2784. # Parse known args to separate global options from command args
  2785. global_args, remaining = parser.parse_known_args(argv)
  2786. # Apply global pager settings
  2787. if global_args.no_pager:
  2788. disable_pager()
  2789. elif global_args.pager:
  2790. enable_pager()
  2791. # Handle help
  2792. if global_args.help or not remaining:
  2793. parser = argparse.ArgumentParser(
  2794. prog="dulwich", description="Simple command-line interface to Dulwich"
  2795. )
  2796. parser.add_argument("--no-pager", action="store_true", help="Disable pager")
  2797. parser.add_argument("--pager", action="store_true", help="Force enable pager")
  2798. parser.add_argument(
  2799. "command",
  2800. nargs="?",
  2801. help=f"Command to run. Available: {', '.join(sorted(commands.keys()))}",
  2802. )
  2803. parser.print_help()
  2804. return 1
  2805. # First remaining arg is the command
  2806. cmd = remaining[0]
  2807. cmd_args = remaining[1:]
  2808. try:
  2809. cmd_kls = commands[cmd]
  2810. except KeyError:
  2811. print(f"No such subcommand: {cmd}")
  2812. return 1
  2813. # TODO(jelmer): Return non-0 on errors
  2814. return cmd_kls().run(cmd_args)
  2815. def _main() -> None:
  2816. if "DULWICH_PDB" in os.environ and getattr(signal, "SIGQUIT", None):
  2817. signal.signal(signal.SIGQUIT, signal_quit) # type: ignore
  2818. signal.signal(signal.SIGINT, signal_int)
  2819. sys.exit(main())
  2820. if __name__ == "__main__":
  2821. _main()