cli.py 125 KB

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