cli.py 128 KB

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