cli.py 136 KB

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