porcelain.py 160 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867
  1. # porcelain.py -- Porcelain-like layer on top of Dulwich
  2. # Copyright (C) 2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Simple wrapper that provides porcelain-like functions on top of Dulwich.
  22. Currently implemented:
  23. * archive
  24. * add
  25. * bisect{_start,_bad,_good,_skip,_reset,_log,_replay}
  26. * branch{_create,_delete,_list}
  27. * check_ignore
  28. * checkout
  29. * checkout_branch
  30. * clone
  31. * cone mode{_init, _set, _add}
  32. * commit
  33. * commit_tree
  34. * daemon
  35. * describe
  36. * diff_tree
  37. * fetch
  38. * filter_branch
  39. * for_each_ref
  40. * init
  41. * ls_files
  42. * ls_remote
  43. * ls_tree
  44. * merge
  45. * merge_tree
  46. * mv/move
  47. * prune
  48. * pull
  49. * push
  50. * rm
  51. * remote{_add}
  52. * receive_pack
  53. * reset
  54. * revert
  55. * sparse_checkout
  56. * submodule_add
  57. * submodule_init
  58. * submodule_list
  59. * rev_list
  60. * tag{_create,_delete,_list}
  61. * upload_pack
  62. * update_server_info
  63. * write_commit_graph
  64. * status
  65. * symbolic_ref
  66. These functions are meant to behave similarly to the git subcommands.
  67. Differences in behaviour are considered bugs.
  68. Note: one of the consequences of this is that paths tend to be
  69. interpreted relative to the current working directory rather than relative
  70. to the repository root.
  71. Functions should generally accept both unicode strings and bytestrings
  72. """
  73. import datetime
  74. import fnmatch
  75. import os
  76. import posixpath
  77. import stat
  78. import sys
  79. import time
  80. from collections import namedtuple
  81. from contextlib import closing, contextmanager
  82. from dataclasses import dataclass
  83. from io import BytesIO, RawIOBase
  84. from pathlib import Path
  85. from typing import Optional, Union
  86. from . import replace_me
  87. from .archive import tar_stream
  88. from .bisect import BisectState
  89. from .client import get_transport_and_path
  90. from .config import Config, ConfigFile, StackedConfig, read_submodules
  91. from .diff_tree import (
  92. CHANGE_ADD,
  93. CHANGE_COPY,
  94. CHANGE_DELETE,
  95. CHANGE_MODIFY,
  96. CHANGE_RENAME,
  97. RENAME_CHANGE_TYPES,
  98. )
  99. from .errors import SendPackError
  100. from .graph import can_fast_forward
  101. from .ignore import IgnoreFilterManager
  102. from .index import (
  103. _fs_to_tree_path,
  104. blob_from_path_and_stat,
  105. build_file_from_blob,
  106. get_unstaged_changes,
  107. update_working_tree,
  108. )
  109. from .object_store import tree_lookup_path
  110. from .objects import (
  111. Commit,
  112. Tag,
  113. Tree,
  114. format_timezone,
  115. parse_timezone,
  116. pretty_format_tree_entry,
  117. )
  118. from .objectspec import (
  119. parse_commit,
  120. parse_object,
  121. parse_ref,
  122. parse_reftuples,
  123. parse_tree,
  124. )
  125. from .pack import write_pack_from_container, write_pack_index
  126. from .patch import write_commit_patch, write_tree_diff
  127. from .protocol import ZERO_SHA, Protocol
  128. from .refs import (
  129. LOCAL_BRANCH_PREFIX,
  130. LOCAL_NOTES_PREFIX,
  131. LOCAL_TAG_PREFIX,
  132. Ref,
  133. SymrefLoop,
  134. _import_remote_refs,
  135. )
  136. from .repo import BaseRepo, Repo, get_user_identity
  137. from .server import (
  138. FileSystemBackend,
  139. ReceivePackHandler,
  140. TCPGitServer,
  141. UploadPackHandler,
  142. )
  143. from .server import update_server_info as server_update_server_info
  144. from .sparse_patterns import (
  145. SparseCheckoutConflictError,
  146. apply_included_paths,
  147. determine_included_paths,
  148. )
  149. # Module level tuple definition for status output
  150. GitStatus = namedtuple("GitStatus", "staged unstaged untracked")
  151. @dataclass
  152. class CountObjectsResult:
  153. """Result of counting objects in a repository.
  154. Attributes:
  155. count: Number of loose objects
  156. size: Total size of loose objects in bytes
  157. in_pack: Number of objects in pack files
  158. packs: Number of pack files
  159. size_pack: Total size of pack files in bytes
  160. """
  161. count: int
  162. size: int
  163. in_pack: Optional[int] = None
  164. packs: Optional[int] = None
  165. size_pack: Optional[int] = None
  166. class NoneStream(RawIOBase):
  167. """Fallback if stdout or stderr are unavailable, does nothing."""
  168. def read(self, size=-1) -> None:
  169. return None
  170. def readall(self) -> bytes:
  171. return b""
  172. def readinto(self, b) -> None:
  173. return None
  174. def write(self, b) -> None:
  175. return None
  176. default_bytes_out_stream = getattr(sys.stdout, "buffer", None) or NoneStream()
  177. default_bytes_err_stream = getattr(sys.stderr, "buffer", None) or NoneStream()
  178. DEFAULT_ENCODING = "utf-8"
  179. class Error(Exception):
  180. """Porcelain-based error."""
  181. def __init__(self, msg) -> None:
  182. super().__init__(msg)
  183. class RemoteExists(Error):
  184. """Raised when the remote already exists."""
  185. class TimezoneFormatError(Error):
  186. """Raised when the timezone cannot be determined from a given string."""
  187. class CheckoutError(Error):
  188. """Indicates that a checkout cannot be performed."""
  189. def parse_timezone_format(tz_str):
  190. """Parse given string and attempt to return a timezone offset.
  191. Different formats are considered in the following order:
  192. - Git internal format: <unix timestamp> <timezone offset>
  193. - RFC 2822: e.g. Mon, 20 Nov 1995 19:12:08 -0500
  194. - ISO 8601: e.g. 1995-11-20T19:12:08-0500
  195. Args:
  196. tz_str: datetime string
  197. Returns: Timezone offset as integer
  198. Raises:
  199. TimezoneFormatError: if timezone information cannot be extracted
  200. """
  201. import re
  202. # Git internal format
  203. internal_format_pattern = re.compile("^[0-9]+ [+-][0-9]{,4}$")
  204. if re.match(internal_format_pattern, tz_str):
  205. try:
  206. tz_internal = parse_timezone(tz_str.split(" ")[1].encode(DEFAULT_ENCODING))
  207. return tz_internal[0]
  208. except ValueError:
  209. pass
  210. # RFC 2822
  211. import email.utils
  212. rfc_2822 = email.utils.parsedate_tz(tz_str)
  213. if rfc_2822:
  214. return rfc_2822[9]
  215. # ISO 8601
  216. # Supported offsets:
  217. # sHHMM, sHH:MM, sHH
  218. iso_8601_pattern = re.compile(
  219. "[0-9] ?([+-])([0-9]{2})(?::(?=[0-9]{2}))?([0-9]{2})?$"
  220. )
  221. match = re.search(iso_8601_pattern, tz_str)
  222. total_secs = 0
  223. if match:
  224. sign, hours, minutes = match.groups()
  225. total_secs += int(hours) * 3600
  226. if minutes:
  227. total_secs += int(minutes) * 60
  228. total_secs = -total_secs if sign == "-" else total_secs
  229. return total_secs
  230. # YYYY.MM.DD, MM/DD/YYYY, DD.MM.YYYY contain no timezone information
  231. raise TimezoneFormatError(tz_str)
  232. def get_user_timezones():
  233. """Retrieve local timezone as described in
  234. https://raw.githubusercontent.com/git/git/v2.3.0/Documentation/date-formats.txt
  235. Returns: A tuple containing author timezone, committer timezone.
  236. """
  237. local_timezone = time.localtime().tm_gmtoff
  238. if os.environ.get("GIT_AUTHOR_DATE"):
  239. author_timezone = parse_timezone_format(os.environ["GIT_AUTHOR_DATE"])
  240. else:
  241. author_timezone = local_timezone
  242. if os.environ.get("GIT_COMMITTER_DATE"):
  243. commit_timezone = parse_timezone_format(os.environ["GIT_COMMITTER_DATE"])
  244. else:
  245. commit_timezone = local_timezone
  246. return author_timezone, commit_timezone
  247. def open_repo(path_or_repo: Union[str, os.PathLike, BaseRepo]):
  248. """Open an argument that can be a repository or a path for a repository."""
  249. if isinstance(path_or_repo, BaseRepo):
  250. return path_or_repo
  251. return Repo(path_or_repo)
  252. @contextmanager
  253. def _noop_context_manager(obj):
  254. """Context manager that has the same api as closing but does nothing."""
  255. yield obj
  256. def open_repo_closing(path_or_repo: Union[str, os.PathLike, BaseRepo]):
  257. """Open an argument that can be a repository or a path for a repository.
  258. returns a context manager that will close the repo on exit if the argument
  259. is a path, else does nothing if the argument is a repo.
  260. """
  261. if isinstance(path_or_repo, BaseRepo):
  262. return _noop_context_manager(path_or_repo)
  263. return closing(Repo(path_or_repo))
  264. def path_to_tree_path(repopath, path, tree_encoding=DEFAULT_ENCODING):
  265. """Convert a path to a path usable in an index, e.g. bytes and relative to
  266. the repository root.
  267. Args:
  268. repopath: Repository path, absolute or relative to the cwd
  269. path: A path, absolute or relative to the cwd
  270. Returns: A path formatted for use in e.g. an index
  271. """
  272. # Resolve might returns a relative path on Windows
  273. # https://bugs.python.org/issue38671
  274. if sys.platform == "win32":
  275. path = os.path.abspath(path)
  276. path = Path(path)
  277. resolved_path = path.resolve()
  278. # Resolve and abspath seems to behave differently regarding symlinks,
  279. # as we are doing abspath on the file path, we need to do the same on
  280. # the repo path or they might not match
  281. if sys.platform == "win32":
  282. repopath = os.path.abspath(repopath)
  283. repopath = Path(repopath).resolve()
  284. try:
  285. relpath = resolved_path.relative_to(repopath)
  286. except ValueError:
  287. # If path is a symlink that points to a file outside the repo, we
  288. # want the relpath for the link itself, not the resolved target
  289. if path.is_symlink():
  290. parent = path.parent.resolve()
  291. relpath = (parent / path.name).relative_to(repopath)
  292. else:
  293. raise
  294. if sys.platform == "win32":
  295. return str(relpath).replace(os.path.sep, "/").encode(tree_encoding)
  296. else:
  297. return bytes(relpath)
  298. class DivergedBranches(Error):
  299. """Branches have diverged and fast-forward is not possible."""
  300. def __init__(self, current_sha, new_sha) -> None:
  301. self.current_sha = current_sha
  302. self.new_sha = new_sha
  303. def check_diverged(repo, current_sha, new_sha) -> None:
  304. """Check if updating to a sha can be done with fast forwarding.
  305. Args:
  306. repo: Repository object
  307. current_sha: Current head sha
  308. new_sha: New head sha
  309. """
  310. try:
  311. can = can_fast_forward(repo, current_sha, new_sha)
  312. except KeyError:
  313. can = False
  314. if not can:
  315. raise DivergedBranches(current_sha, new_sha)
  316. def archive(
  317. repo,
  318. committish: Optional[Union[str, bytes, Commit, Tag]] = None,
  319. outstream=default_bytes_out_stream,
  320. errstream=default_bytes_err_stream,
  321. ) -> None:
  322. """Create an archive.
  323. Args:
  324. repo: Path of repository for which to generate an archive.
  325. committish: Commit SHA1 or ref to use
  326. outstream: Output stream (defaults to stdout)
  327. errstream: Error stream (defaults to stderr)
  328. """
  329. if committish is None:
  330. committish = "HEAD"
  331. with open_repo_closing(repo) as repo_obj:
  332. c = parse_commit(repo_obj, committish)
  333. for chunk in tar_stream(
  334. repo_obj.object_store, repo_obj.object_store[c.tree], c.commit_time
  335. ):
  336. outstream.write(chunk)
  337. def update_server_info(repo=".") -> None:
  338. """Update server info files for a repository.
  339. Args:
  340. repo: path to the repository
  341. """
  342. with open_repo_closing(repo) as r:
  343. server_update_server_info(r)
  344. def write_commit_graph(repo=".", reachable=True) -> None:
  345. """Write a commit graph file for a repository.
  346. Args:
  347. repo: path to the repository or a Repo object
  348. reachable: if True, include all commits reachable from refs.
  349. if False, only include direct ref targets.
  350. """
  351. with open_repo_closing(repo) as r:
  352. # Get all refs
  353. refs = list(r.refs.as_dict().values())
  354. if refs:
  355. r.object_store.write_commit_graph(refs, reachable=reachable)
  356. def symbolic_ref(repo, ref_name, force=False) -> None:
  357. """Set git symbolic ref into HEAD.
  358. Args:
  359. repo: path to the repository
  360. ref_name: short name of the new ref
  361. force: force settings without checking if it exists in refs/heads
  362. """
  363. with open_repo_closing(repo) as repo_obj:
  364. ref_path = _make_branch_ref(ref_name)
  365. if not force and ref_path not in repo_obj.refs.keys():
  366. raise Error(f"fatal: ref `{ref_name}` is not a ref")
  367. repo_obj.refs.set_symbolic_ref(b"HEAD", ref_path)
  368. def pack_refs(repo, all=False) -> None:
  369. with open_repo_closing(repo) as repo_obj:
  370. repo_obj.refs.pack_refs(all=all)
  371. def commit(
  372. repo=".",
  373. message=None,
  374. author=None,
  375. author_timezone=None,
  376. committer=None,
  377. commit_timezone=None,
  378. encoding=None,
  379. no_verify=False,
  380. signoff=False,
  381. ):
  382. """Create a new commit.
  383. Args:
  384. repo: Path to repository
  385. message: Optional commit message
  386. author: Optional author name and email
  387. author_timezone: Author timestamp timezone
  388. committer: Optional committer name and email
  389. commit_timezone: Commit timestamp timezone
  390. no_verify: Skip pre-commit and commit-msg hooks
  391. signoff: GPG Sign the commit (bool, defaults to False,
  392. pass True to use default GPG key,
  393. pass a str containing Key ID to use a specific GPG key)
  394. Returns: SHA1 of the new commit
  395. """
  396. # FIXME: Support --all argument
  397. if getattr(message, "encode", None):
  398. message = message.encode(encoding or DEFAULT_ENCODING)
  399. if getattr(author, "encode", None):
  400. author = author.encode(encoding or DEFAULT_ENCODING)
  401. if getattr(committer, "encode", None):
  402. committer = committer.encode(encoding or DEFAULT_ENCODING)
  403. local_timezone = get_user_timezones()
  404. if author_timezone is None:
  405. author_timezone = local_timezone[0]
  406. if commit_timezone is None:
  407. commit_timezone = local_timezone[1]
  408. with open_repo_closing(repo) as r:
  409. return r.do_commit(
  410. message=message,
  411. author=author,
  412. author_timezone=author_timezone,
  413. committer=committer,
  414. commit_timezone=commit_timezone,
  415. encoding=encoding,
  416. no_verify=no_verify,
  417. sign=signoff if isinstance(signoff, (str, bool)) else None,
  418. )
  419. def commit_tree(repo, tree, message=None, author=None, committer=None):
  420. """Create a new commit object.
  421. Args:
  422. repo: Path to repository
  423. tree: An existing tree object
  424. author: Optional author name and email
  425. committer: Optional committer name and email
  426. """
  427. with open_repo_closing(repo) as r:
  428. return r.do_commit(
  429. message=message, tree=tree, committer=committer, author=author
  430. )
  431. def init(
  432. path: Union[str, os.PathLike] = ".", *, bare=False, symlinks: Optional[bool] = None
  433. ):
  434. """Create a new git repository.
  435. Args:
  436. path: Path to repository.
  437. bare: Whether to create a bare repository.
  438. symlinks: Whether to create actual symlinks (defaults to autodetect)
  439. Returns: A Repo instance
  440. """
  441. if not os.path.exists(path):
  442. os.mkdir(path)
  443. if bare:
  444. return Repo.init_bare(path)
  445. else:
  446. return Repo.init(path, symlinks=symlinks)
  447. def clone(
  448. source,
  449. target: Optional[Union[str, os.PathLike]] = None,
  450. bare=False,
  451. checkout=None,
  452. errstream=default_bytes_err_stream,
  453. outstream=None,
  454. origin: Optional[str] = "origin",
  455. depth: Optional[int] = None,
  456. branch: Optional[Union[str, bytes]] = None,
  457. config: Optional[Config] = None,
  458. filter_spec=None,
  459. protocol_version: Optional[int] = None,
  460. recurse_submodules: bool = False,
  461. **kwargs,
  462. ):
  463. """Clone a local or remote git repository.
  464. Args:
  465. source: Path or URL for source repository
  466. target: Path to target repository (optional)
  467. bare: Whether or not to create a bare repository
  468. checkout: Whether or not to check-out HEAD after cloning
  469. errstream: Optional stream to write progress to
  470. outstream: Optional stream to write progress to (deprecated)
  471. origin: Name of remote from the repository used to clone
  472. depth: Depth to fetch at
  473. branch: Optional branch or tag to be used as HEAD in the new repository
  474. instead of the cloned repository's HEAD.
  475. config: Configuration to use
  476. filter_spec: A git-rev-list-style object filter spec, as an ASCII string.
  477. Only used if the server supports the Git protocol-v2 'filter'
  478. feature, and ignored otherwise.
  479. protocol_version: desired Git protocol version. By default the highest
  480. mutually supported protocol version will be used.
  481. recurse_submodules: Whether to initialize and clone submodules
  482. Keyword Args:
  483. refspecs: refspecs to fetch. Can be a bytestring, a string, or a list of
  484. bytestring/string.
  485. Returns: The new repository
  486. """
  487. if outstream is not None:
  488. import warnings
  489. warnings.warn(
  490. "outstream= has been deprecated in favour of errstream=.",
  491. DeprecationWarning,
  492. stacklevel=3,
  493. )
  494. # TODO(jelmer): Capture logging output and stream to errstream
  495. if config is None:
  496. config = StackedConfig.default()
  497. if checkout is None:
  498. checkout = not bare
  499. if checkout and bare:
  500. raise Error("checkout and bare are incompatible")
  501. if target is None:
  502. target = source.split("/")[-1]
  503. if isinstance(branch, str):
  504. branch = branch.encode(DEFAULT_ENCODING)
  505. mkdir = not os.path.exists(target)
  506. (client, path) = get_transport_and_path(source, config=config, **kwargs)
  507. if filter_spec:
  508. filter_spec = filter_spec.encode("ascii")
  509. repo = client.clone(
  510. path,
  511. target,
  512. mkdir=mkdir,
  513. bare=bare,
  514. origin=origin,
  515. checkout=checkout,
  516. branch=branch,
  517. progress=errstream.write,
  518. depth=depth,
  519. filter_spec=filter_spec,
  520. protocol_version=protocol_version,
  521. )
  522. # Initialize and update submodules if requested
  523. if recurse_submodules and not bare:
  524. try:
  525. submodule_init(repo)
  526. submodule_update(repo, init=True)
  527. except FileNotFoundError as e:
  528. # .gitmodules file doesn't exist - no submodules to process
  529. import logging
  530. logging.debug("No .gitmodules file found: %s", e)
  531. except KeyError as e:
  532. # Submodule configuration missing
  533. import logging
  534. logging.warning("Submodule configuration error: %s", e)
  535. if errstream:
  536. errstream.write(
  537. f"Warning: Submodule configuration error: {e}\n".encode()
  538. )
  539. return repo
  540. def add(repo: Union[str, os.PathLike, BaseRepo] = ".", paths=None):
  541. """Add files to the staging area.
  542. Args:
  543. repo: Repository for the files
  544. paths: Paths to add. If None, stages all untracked and modified files from the
  545. current working directory (mimicking 'git add .' behavior).
  546. Returns: Tuple with set of added files and ignored files
  547. If the repository contains ignored directories, the returned set will
  548. contain the path to an ignored directory (with trailing slash). Individual
  549. files within ignored directories will not be returned.
  550. Note: When paths=None, this function adds all untracked and modified files
  551. from the entire repository, mimicking 'git add -A' behavior.
  552. """
  553. ignored = set()
  554. with open_repo_closing(repo) as r:
  555. repo_path = Path(r.path).resolve()
  556. ignore_manager = IgnoreFilterManager.from_repo(r)
  557. # Get unstaged changes once for the entire operation
  558. index = r.open_index()
  559. normalizer = r.get_blob_normalizer()
  560. filter_callback = normalizer.checkin_normalize
  561. all_unstaged_paths = list(get_unstaged_changes(index, r.path, filter_callback))
  562. if not paths:
  563. # When no paths specified, add all untracked and modified files from repo root
  564. paths = [str(repo_path)]
  565. relpaths = []
  566. if not isinstance(paths, list):
  567. paths = [paths]
  568. for p in paths:
  569. path = Path(p)
  570. if not path.is_absolute():
  571. # Make relative paths relative to the repo directory
  572. path = repo_path / path
  573. # Don't resolve symlinks completely - only resolve the parent directory
  574. # to avoid issues when symlinks point outside the repository
  575. if path.is_symlink():
  576. # For symlinks, resolve only the parent directory
  577. parent_resolved = path.parent.resolve()
  578. resolved_path = parent_resolved / path.name
  579. else:
  580. # For regular files/dirs, resolve normally
  581. resolved_path = path.resolve()
  582. try:
  583. relpath = str(resolved_path.relative_to(repo_path)).replace(os.sep, "/")
  584. except ValueError as e:
  585. # Path is not within the repository
  586. raise ValueError(
  587. f"Path {p} is not within repository {repo_path}"
  588. ) from e
  589. # Handle directories by scanning their contents
  590. if resolved_path.is_dir():
  591. # Check if the directory itself is ignored
  592. dir_relpath = posixpath.join(relpath, "") if relpath != "." else ""
  593. if dir_relpath and ignore_manager.is_ignored(dir_relpath):
  594. ignored.add(dir_relpath)
  595. continue
  596. # When adding a directory, add all untracked files within it
  597. current_untracked = list(
  598. get_untracked_paths(
  599. str(resolved_path),
  600. str(repo_path),
  601. index,
  602. )
  603. )
  604. for untracked_path in current_untracked:
  605. # If we're scanning a subdirectory, adjust the path
  606. if relpath != ".":
  607. untracked_path = posixpath.join(relpath, untracked_path)
  608. if not ignore_manager.is_ignored(untracked_path):
  609. relpaths.append(untracked_path)
  610. else:
  611. ignored.add(untracked_path)
  612. # Also add unstaged (modified) files within this directory
  613. for unstaged_path in all_unstaged_paths:
  614. if isinstance(unstaged_path, bytes):
  615. unstaged_path_str = unstaged_path.decode("utf-8")
  616. else:
  617. unstaged_path_str = unstaged_path
  618. # Check if this unstaged file is within the directory we're processing
  619. unstaged_full_path = repo_path / unstaged_path_str
  620. try:
  621. unstaged_full_path.relative_to(resolved_path)
  622. # File is within this directory, add it
  623. if not ignore_manager.is_ignored(unstaged_path_str):
  624. relpaths.append(unstaged_path_str)
  625. else:
  626. ignored.add(unstaged_path_str)
  627. except ValueError:
  628. # File is not within this directory, skip it
  629. continue
  630. continue
  631. # FIXME: Support patterns
  632. if ignore_manager.is_ignored(relpath):
  633. ignored.add(relpath)
  634. continue
  635. relpaths.append(relpath)
  636. r.stage(relpaths)
  637. return (relpaths, ignored)
  638. def _is_subdir(subdir, parentdir):
  639. """Check whether subdir is parentdir or a subdir of parentdir.
  640. If parentdir or subdir is a relative path, it will be disamgibuated
  641. relative to the pwd.
  642. """
  643. parentdir_abs = os.path.realpath(parentdir) + os.path.sep
  644. subdir_abs = os.path.realpath(subdir) + os.path.sep
  645. return subdir_abs.startswith(parentdir_abs)
  646. # TODO: option to remove ignored files also, in line with `git clean -fdx`
  647. def clean(repo=".", target_dir=None) -> None:
  648. """Remove any untracked files from the target directory recursively.
  649. Equivalent to running ``git clean -fd`` in target_dir.
  650. Args:
  651. repo: Repository where the files may be tracked
  652. target_dir: Directory to clean - current directory if None
  653. """
  654. if target_dir is None:
  655. target_dir = os.getcwd()
  656. with open_repo_closing(repo) as r:
  657. if not _is_subdir(target_dir, r.path):
  658. raise Error("target_dir must be in the repo's working dir")
  659. config = r.get_config_stack()
  660. config.get_boolean((b"clean",), b"requireForce", True)
  661. # TODO(jelmer): if require_force is set, then make sure that -f, -i or
  662. # -n is specified.
  663. index = r.open_index()
  664. ignore_manager = IgnoreFilterManager.from_repo(r)
  665. paths_in_wd = _walk_working_dir_paths(target_dir, r.path)
  666. # Reverse file visit order, so that files and subdirectories are
  667. # removed before containing directory
  668. for ap, is_dir in reversed(list(paths_in_wd)):
  669. if is_dir:
  670. # All subdirectories and files have been removed if untracked,
  671. # so dir contains no tracked files iff it is empty.
  672. is_empty = len(os.listdir(ap)) == 0
  673. if is_empty:
  674. os.rmdir(ap)
  675. else:
  676. ip = path_to_tree_path(r.path, ap)
  677. is_tracked = ip in index
  678. rp = os.path.relpath(ap, r.path)
  679. is_ignored = ignore_manager.is_ignored(rp)
  680. if not is_tracked and not is_ignored:
  681. os.remove(ap)
  682. def remove(repo=".", paths=None, cached=False) -> None:
  683. """Remove files from the staging area.
  684. Args:
  685. repo: Repository for the files
  686. paths: Paths to remove. Can be absolute or relative to the repository root.
  687. """
  688. with open_repo_closing(repo) as r:
  689. index = r.open_index()
  690. blob_normalizer = r.get_blob_normalizer()
  691. for p in paths:
  692. # If path is absolute, use it as-is. Otherwise, treat it as relative to repo
  693. if os.path.isabs(p):
  694. full_path = p
  695. else:
  696. # Treat relative paths as relative to the repository root
  697. full_path = os.path.join(r.path, p)
  698. tree_path = path_to_tree_path(r.path, full_path)
  699. # Convert to bytes for file operations
  700. full_path_bytes = os.fsencode(full_path)
  701. try:
  702. index_sha = index[tree_path].sha
  703. except KeyError as exc:
  704. raise Error(f"{p} did not match any files") from exc
  705. if not cached:
  706. try:
  707. st = os.lstat(full_path_bytes)
  708. except OSError:
  709. pass
  710. else:
  711. try:
  712. blob = blob_from_path_and_stat(full_path_bytes, st)
  713. # Apply checkin normalization to compare apples to apples
  714. if blob_normalizer is not None:
  715. blob = blob_normalizer.checkin_normalize(blob, tree_path)
  716. except OSError:
  717. pass
  718. else:
  719. try:
  720. committed_sha = tree_lookup_path(
  721. r.__getitem__, r[r.head()].tree, tree_path
  722. )[1]
  723. except KeyError:
  724. committed_sha = None
  725. if blob.id != index_sha and index_sha != committed_sha:
  726. raise Error(
  727. "file has staged content differing "
  728. f"from both the file and head: {p}"
  729. )
  730. if index_sha != committed_sha:
  731. raise Error(f"file has staged changes: {p}")
  732. os.remove(full_path_bytes)
  733. del index[tree_path]
  734. index.write()
  735. rm = remove
  736. def mv(
  737. repo: Union[str, os.PathLike, BaseRepo],
  738. source: Union[str, bytes, os.PathLike],
  739. destination: Union[str, bytes, os.PathLike],
  740. force: bool = False,
  741. ) -> None:
  742. """Move or rename a file, directory, or symlink.
  743. Args:
  744. repo: Path to the repository
  745. source: Path to move from
  746. destination: Path to move to
  747. force: Force move even if destination exists
  748. Raises:
  749. Error: If source doesn't exist, is not tracked, or destination already exists (without force)
  750. """
  751. with open_repo_closing(repo) as r:
  752. index = r.open_index()
  753. # Handle paths - convert to string if necessary
  754. if isinstance(source, bytes):
  755. source = source.decode(sys.getfilesystemencoding())
  756. elif hasattr(source, "__fspath__"):
  757. source = os.fspath(source)
  758. else:
  759. source = str(source)
  760. if isinstance(destination, bytes):
  761. destination = destination.decode(sys.getfilesystemencoding())
  762. elif hasattr(destination, "__fspath__"):
  763. destination = os.fspath(destination)
  764. else:
  765. destination = str(destination)
  766. # Get full paths
  767. if os.path.isabs(source):
  768. source_full_path = source
  769. else:
  770. # Treat relative paths as relative to the repository root
  771. source_full_path = os.path.join(r.path, source)
  772. if os.path.isabs(destination):
  773. destination_full_path = destination
  774. else:
  775. # Treat relative paths as relative to the repository root
  776. destination_full_path = os.path.join(r.path, destination)
  777. # Check if destination is a directory
  778. if os.path.isdir(destination_full_path):
  779. # Move source into destination directory
  780. basename = os.path.basename(source_full_path)
  781. destination_full_path = os.path.join(destination_full_path, basename)
  782. # Convert to tree paths for index
  783. source_tree_path = path_to_tree_path(r.path, source_full_path)
  784. destination_tree_path = path_to_tree_path(r.path, destination_full_path)
  785. # Check if source exists in index
  786. if source_tree_path not in index:
  787. raise Error(f"source '{source}' is not under version control")
  788. # Check if source exists in filesystem
  789. if not os.path.exists(source_full_path):
  790. raise Error(f"source '{source}' does not exist")
  791. # Check if destination already exists
  792. if os.path.exists(destination_full_path) and not force:
  793. raise Error(f"destination '{destination}' already exists (use -f to force)")
  794. # Check if destination is already in index
  795. if destination_tree_path in index and not force:
  796. raise Error(
  797. f"destination '{destination}' already exists in index (use -f to force)"
  798. )
  799. # Get the index entry for the source
  800. source_entry = index[source_tree_path]
  801. # Convert to bytes for file operations
  802. source_full_path_bytes = os.fsencode(source_full_path)
  803. destination_full_path_bytes = os.fsencode(destination_full_path)
  804. # Create parent directory for destination if needed
  805. dest_dir = os.path.dirname(destination_full_path_bytes)
  806. if dest_dir and not os.path.exists(dest_dir):
  807. os.makedirs(dest_dir)
  808. # Move the file in the filesystem
  809. if os.path.exists(destination_full_path_bytes) and force:
  810. os.remove(destination_full_path_bytes)
  811. os.rename(source_full_path_bytes, destination_full_path_bytes)
  812. # Update the index
  813. del index[source_tree_path]
  814. index[destination_tree_path] = source_entry
  815. index.write()
  816. move = mv
  817. def commit_decode(commit, contents, default_encoding=DEFAULT_ENCODING):
  818. if commit.encoding:
  819. encoding = commit.encoding.decode("ascii")
  820. else:
  821. encoding = default_encoding
  822. return contents.decode(encoding, "replace")
  823. def commit_encode(commit, contents, default_encoding=DEFAULT_ENCODING):
  824. if commit.encoding:
  825. encoding = commit.encoding.decode("ascii")
  826. else:
  827. encoding = default_encoding
  828. return contents.encode(encoding)
  829. def print_commit(commit, decode, outstream=sys.stdout) -> None:
  830. """Write a human-readable commit log entry.
  831. Args:
  832. commit: A `Commit` object
  833. outstream: A stream file to write to
  834. """
  835. outstream.write("-" * 50 + "\n")
  836. outstream.write("commit: " + commit.id.decode("ascii") + "\n")
  837. if len(commit.parents) > 1:
  838. outstream.write(
  839. "merge: "
  840. + "...".join([c.decode("ascii") for c in commit.parents[1:]])
  841. + "\n"
  842. )
  843. outstream.write("Author: " + decode(commit.author) + "\n")
  844. if commit.author != commit.committer:
  845. outstream.write("Committer: " + decode(commit.committer) + "\n")
  846. time_tuple = time.gmtime(commit.author_time + commit.author_timezone)
  847. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  848. timezone_str = format_timezone(commit.author_timezone).decode("ascii")
  849. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  850. if commit.message:
  851. outstream.write("\n")
  852. outstream.write(decode(commit.message) + "\n")
  853. outstream.write("\n")
  854. def print_tag(tag, decode, outstream=sys.stdout) -> None:
  855. """Write a human-readable tag.
  856. Args:
  857. tag: A `Tag` object
  858. decode: Function for decoding bytes to unicode string
  859. outstream: A stream to write to
  860. """
  861. outstream.write("Tagger: " + decode(tag.tagger) + "\n")
  862. time_tuple = time.gmtime(tag.tag_time + tag.tag_timezone)
  863. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  864. timezone_str = format_timezone(tag.tag_timezone).decode("ascii")
  865. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  866. outstream.write("\n")
  867. outstream.write(decode(tag.message))
  868. outstream.write("\n")
  869. def show_blob(repo, blob, decode, outstream=sys.stdout) -> None:
  870. """Write a blob to a stream.
  871. Args:
  872. repo: A `Repo` object
  873. blob: A `Blob` object
  874. decode: Function for decoding bytes to unicode string
  875. outstream: A stream file to write to
  876. """
  877. outstream.write(decode(blob.data))
  878. def show_commit(repo, commit, decode, outstream=sys.stdout) -> None:
  879. """Show a commit to a stream.
  880. Args:
  881. repo: A `Repo` object
  882. commit: A `Commit` object
  883. decode: Function for decoding bytes to unicode string
  884. outstream: Stream to write to
  885. """
  886. print_commit(commit, decode=decode, outstream=outstream)
  887. if commit.parents:
  888. parent_commit = repo[commit.parents[0]]
  889. base_tree = parent_commit.tree
  890. else:
  891. base_tree = None
  892. diffstream = BytesIO()
  893. write_tree_diff(diffstream, repo.object_store, base_tree, commit.tree)
  894. diffstream.seek(0)
  895. outstream.write(commit_decode(commit, diffstream.getvalue()))
  896. def show_tree(repo, tree, decode, outstream=sys.stdout) -> None:
  897. """Print a tree to a stream.
  898. Args:
  899. repo: A `Repo` object
  900. tree: A `Tree` object
  901. decode: Function for decoding bytes to unicode string
  902. outstream: Stream to write to
  903. """
  904. for n in tree:
  905. outstream.write(decode(n) + "\n")
  906. def show_tag(repo, tag, decode, outstream=sys.stdout) -> None:
  907. """Print a tag to a stream.
  908. Args:
  909. repo: A `Repo` object
  910. tag: A `Tag` object
  911. decode: Function for decoding bytes to unicode string
  912. outstream: Stream to write to
  913. """
  914. print_tag(tag, decode, outstream)
  915. show_object(repo, repo[tag.object[1]], decode, outstream)
  916. def show_object(repo, obj, decode, outstream):
  917. return {
  918. b"tree": show_tree,
  919. b"blob": show_blob,
  920. b"commit": show_commit,
  921. b"tag": show_tag,
  922. }[obj.type_name](repo, obj, decode, outstream)
  923. def print_name_status(changes):
  924. """Print a simple status summary, listing changed files."""
  925. for change in changes:
  926. if not change:
  927. continue
  928. if isinstance(change, list):
  929. change = change[0]
  930. if change.type == CHANGE_ADD:
  931. path1 = change.new.path
  932. path2 = ""
  933. kind = "A"
  934. elif change.type == CHANGE_DELETE:
  935. path1 = change.old.path
  936. path2 = ""
  937. kind = "D"
  938. elif change.type == CHANGE_MODIFY:
  939. path1 = change.new.path
  940. path2 = ""
  941. kind = "M"
  942. elif change.type in RENAME_CHANGE_TYPES:
  943. path1 = change.old.path
  944. path2 = change.new.path
  945. if change.type == CHANGE_RENAME:
  946. kind = "R"
  947. elif change.type == CHANGE_COPY:
  948. kind = "C"
  949. yield "%-8s%-20s%-20s" % (kind, path1, path2) # noqa: UP031
  950. def log(
  951. repo=".",
  952. paths=None,
  953. outstream=sys.stdout,
  954. max_entries=None,
  955. reverse=False,
  956. name_status=False,
  957. ) -> None:
  958. """Write commit logs.
  959. Args:
  960. repo: Path to repository
  961. paths: Optional set of specific paths to print entries for
  962. outstream: Stream to write log output to
  963. reverse: Reverse order in which entries are printed
  964. name_status: Print name status
  965. max_entries: Optional maximum number of entries to display
  966. """
  967. with open_repo_closing(repo) as r:
  968. try:
  969. include = [r.head()]
  970. except KeyError:
  971. include = []
  972. walker = r.get_walker(
  973. include=include, max_entries=max_entries, paths=paths, reverse=reverse
  974. )
  975. for entry in walker:
  976. def decode(x):
  977. return commit_decode(entry.commit, x)
  978. print_commit(entry.commit, decode, outstream)
  979. if name_status:
  980. outstream.writelines(
  981. [line + "\n" for line in print_name_status(entry.changes())]
  982. )
  983. # TODO(jelmer): better default for encoding?
  984. def show(
  985. repo=".",
  986. objects=None,
  987. outstream=sys.stdout,
  988. default_encoding=DEFAULT_ENCODING,
  989. ) -> None:
  990. """Print the changes in a commit.
  991. Args:
  992. repo: Path to repository
  993. objects: Objects to show (defaults to [HEAD])
  994. outstream: Stream to write to
  995. default_encoding: Default encoding to use if none is set in the
  996. commit
  997. """
  998. if objects is None:
  999. objects = ["HEAD"]
  1000. if not isinstance(objects, list):
  1001. objects = [objects]
  1002. with open_repo_closing(repo) as r:
  1003. for objectish in objects:
  1004. o = parse_object(r, objectish)
  1005. if isinstance(o, Commit):
  1006. def decode(x):
  1007. return commit_decode(o, x, default_encoding)
  1008. else:
  1009. def decode(x):
  1010. return x.decode(default_encoding)
  1011. show_object(r, o, decode, outstream)
  1012. def diff_tree(repo, old_tree, new_tree, outstream=default_bytes_out_stream) -> None:
  1013. """Compares the content and mode of blobs found via two tree objects.
  1014. Args:
  1015. repo: Path to repository
  1016. old_tree: Id of old tree
  1017. new_tree: Id of new tree
  1018. outstream: Stream to write to
  1019. """
  1020. with open_repo_closing(repo) as r:
  1021. write_tree_diff(outstream, r.object_store, old_tree, new_tree)
  1022. def diff(
  1023. repo=".",
  1024. commit=None,
  1025. commit2=None,
  1026. staged=False,
  1027. paths=None,
  1028. outstream=default_bytes_out_stream,
  1029. ) -> None:
  1030. """Show diff.
  1031. Args:
  1032. repo: Path to repository
  1033. commit: First commit to compare. If staged is True, compare
  1034. index to this commit. If staged is False, compare working tree
  1035. to this commit. If None, defaults to HEAD for staged and index
  1036. for unstaged.
  1037. commit2: Second commit to compare against first commit. If provided,
  1038. show diff between commit and commit2 (ignoring staged flag).
  1039. staged: If True, show staged changes (index vs commit).
  1040. If False, show unstaged changes (working tree vs commit/index).
  1041. Ignored if commit2 is provided.
  1042. paths: Optional list of paths to limit diff
  1043. outstream: Stream to write to
  1044. """
  1045. from . import diff as diff_module
  1046. from .objectspec import parse_commit
  1047. with open_repo_closing(repo) as r:
  1048. # Normalize paths to bytes
  1049. if paths is not None and paths: # Check if paths is not empty
  1050. byte_paths = []
  1051. for p in paths:
  1052. if isinstance(p, str):
  1053. byte_paths.append(p.encode("utf-8"))
  1054. else:
  1055. byte_paths.append(p)
  1056. paths = byte_paths
  1057. elif paths == []: # Convert empty list to None
  1058. paths = None
  1059. # Resolve commit refs to SHAs if provided
  1060. if commit is not None:
  1061. from .objects import Commit
  1062. if isinstance(commit, Commit):
  1063. # Already a Commit object
  1064. commit_sha = commit.id
  1065. commit_obj = commit
  1066. else:
  1067. # parse_commit handles both refs and SHAs, and always returns a Commit object
  1068. commit_obj = parse_commit(r, commit)
  1069. commit_sha = commit_obj.id
  1070. else:
  1071. commit_sha = None
  1072. commit_obj = None
  1073. if commit2 is not None:
  1074. # Compare two commits
  1075. from .objects import Commit
  1076. from .patch import write_object_diff
  1077. if isinstance(commit2, Commit):
  1078. commit2_obj = commit2
  1079. else:
  1080. commit2_obj = parse_commit(r, commit2)
  1081. # Get trees from commits
  1082. old_tree = commit_obj.tree if commit_obj else None
  1083. new_tree = commit2_obj.tree
  1084. # Use tree_changes to get the changes and apply path filtering
  1085. changes = r.object_store.tree_changes(old_tree, new_tree)
  1086. for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
  1087. # Skip if paths are specified and this change doesn't match
  1088. if paths:
  1089. path_to_check = newpath or oldpath
  1090. if not any(
  1091. path_to_check == p or path_to_check.startswith(p + b"/")
  1092. for p in paths
  1093. ):
  1094. continue
  1095. write_object_diff(
  1096. outstream,
  1097. r.object_store,
  1098. (oldpath, oldmode, oldsha),
  1099. (newpath, newmode, newsha),
  1100. )
  1101. elif staged:
  1102. # Show staged changes (index vs commit)
  1103. diff_module.diff_index_to_tree(r, outstream, commit_sha, paths)
  1104. elif commit is not None:
  1105. # Compare working tree to a specific commit
  1106. assert (
  1107. commit_sha is not None
  1108. ) # mypy: commit_sha is set when commit is not None
  1109. diff_module.diff_working_tree_to_tree(r, outstream, commit_sha, paths)
  1110. else:
  1111. # Compare working tree to index
  1112. diff_module.diff_working_tree_to_index(r, outstream, paths)
  1113. def rev_list(repo, commits, outstream=sys.stdout) -> None:
  1114. """Lists commit objects in reverse chronological order.
  1115. Args:
  1116. repo: Path to repository
  1117. commits: Commits over which to iterate
  1118. outstream: Stream to write to
  1119. """
  1120. with open_repo_closing(repo) as r:
  1121. for entry in r.get_walker(include=[r[c].id for c in commits]):
  1122. outstream.write(entry.commit.id + b"\n")
  1123. def _canonical_part(url: str) -> str:
  1124. name = url.rsplit("/", 1)[-1]
  1125. if name.endswith(".git"):
  1126. name = name[:-4]
  1127. return name
  1128. def submodule_add(repo, url, path=None, name=None) -> None:
  1129. """Add a new submodule.
  1130. Args:
  1131. repo: Path to repository
  1132. url: URL of repository to add as submodule
  1133. path: Path where submodule should live
  1134. name: Name for the submodule
  1135. """
  1136. with open_repo_closing(repo) as r:
  1137. if path is None:
  1138. path = os.path.relpath(_canonical_part(url), r.path)
  1139. if name is None:
  1140. name = path
  1141. # TODO(jelmer): Move this logic to dulwich.submodule
  1142. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1143. try:
  1144. config = ConfigFile.from_path(gitmodules_path)
  1145. except FileNotFoundError:
  1146. config = ConfigFile()
  1147. config.path = gitmodules_path
  1148. config.set(("submodule", name), "url", url)
  1149. config.set(("submodule", name), "path", path)
  1150. config.write_to_path()
  1151. def submodule_init(repo) -> None:
  1152. """Initialize submodules.
  1153. Args:
  1154. repo: Path to repository
  1155. """
  1156. with open_repo_closing(repo) as r:
  1157. config = r.get_config()
  1158. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1159. for path, url, name in read_submodules(gitmodules_path):
  1160. config.set((b"submodule", name), b"active", True)
  1161. config.set((b"submodule", name), b"url", url)
  1162. config.write_to_path()
  1163. def submodule_list(repo):
  1164. """List submodules.
  1165. Args:
  1166. repo: Path to repository
  1167. """
  1168. from .submodule import iter_cached_submodules
  1169. with open_repo_closing(repo) as r:
  1170. for path, sha in iter_cached_submodules(r.object_store, r[r.head()].tree):
  1171. yield path, sha.decode(DEFAULT_ENCODING)
  1172. def submodule_update(repo, paths=None, init=False, force=False, errstream=None) -> None:
  1173. """Update submodules.
  1174. Args:
  1175. repo: Path to repository
  1176. paths: Optional list of specific submodule paths to update. If None, updates all.
  1177. init: If True, initialize submodules first
  1178. force: Force update even if local changes exist
  1179. """
  1180. from .client import get_transport_and_path
  1181. from .index import build_index_from_tree
  1182. from .submodule import iter_cached_submodules
  1183. with open_repo_closing(repo) as r:
  1184. if init:
  1185. submodule_init(r)
  1186. config = r.get_config()
  1187. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1188. # Get list of submodules to update
  1189. submodules_to_update = []
  1190. for path, sha in iter_cached_submodules(r.object_store, r[r.head()].tree):
  1191. path_str = (
  1192. path.decode(DEFAULT_ENCODING) if isinstance(path, bytes) else path
  1193. )
  1194. if paths is None or path_str in paths:
  1195. submodules_to_update.append((path, sha))
  1196. # Read submodule configuration
  1197. for path, target_sha in submodules_to_update:
  1198. path_str = (
  1199. path.decode(DEFAULT_ENCODING) if isinstance(path, bytes) else path
  1200. )
  1201. # Find the submodule name from .gitmodules
  1202. submodule_name = None
  1203. for sm_path, sm_url, sm_name in read_submodules(gitmodules_path):
  1204. if sm_path == path:
  1205. submodule_name = sm_name
  1206. break
  1207. if not submodule_name:
  1208. continue
  1209. # Get the URL from config
  1210. section = (
  1211. b"submodule",
  1212. submodule_name
  1213. if isinstance(submodule_name, bytes)
  1214. else submodule_name.encode(),
  1215. )
  1216. try:
  1217. url = config.get(section, b"url")
  1218. if isinstance(url, bytes):
  1219. url = url.decode(DEFAULT_ENCODING)
  1220. except KeyError:
  1221. # URL not in config, skip this submodule
  1222. continue
  1223. # Get or create the submodule repository paths
  1224. submodule_path = os.path.join(r.path, path_str)
  1225. submodule_git_dir = os.path.join(r.path, ".git", "modules", path_str)
  1226. # Clone or fetch the submodule
  1227. if not os.path.exists(submodule_git_dir):
  1228. # Clone the submodule as bare repository
  1229. os.makedirs(os.path.dirname(submodule_git_dir), exist_ok=True)
  1230. # Clone to the git directory
  1231. sub_repo = clone(url, submodule_git_dir, bare=True, checkout=False)
  1232. sub_repo.close()
  1233. # Create the submodule directory if it doesn't exist
  1234. if not os.path.exists(submodule_path):
  1235. os.makedirs(submodule_path)
  1236. # Create .git file in the submodule directory
  1237. depth = path_str.count("/") + 1
  1238. relative_git_dir = "../" * depth + ".git/modules/" + path_str
  1239. git_file_path = os.path.join(submodule_path, ".git")
  1240. with open(git_file_path, "w") as f:
  1241. f.write(f"gitdir: {relative_git_dir}\n")
  1242. # Set up working directory configuration
  1243. with open_repo_closing(submodule_git_dir) as sub_repo:
  1244. sub_config = sub_repo.get_config()
  1245. sub_config.set(
  1246. (b"core",),
  1247. b"worktree",
  1248. os.path.abspath(submodule_path).encode(),
  1249. )
  1250. sub_config.write_to_path()
  1251. # Checkout the target commit
  1252. sub_repo.refs[b"HEAD"] = target_sha
  1253. # Build the index and checkout files
  1254. tree = sub_repo[target_sha]
  1255. if hasattr(tree, "tree"): # If it's a commit, get the tree
  1256. tree_id = tree.tree
  1257. else:
  1258. tree_id = target_sha
  1259. build_index_from_tree(
  1260. submodule_path,
  1261. sub_repo.index_path(),
  1262. sub_repo.object_store,
  1263. tree_id,
  1264. )
  1265. else:
  1266. # Fetch and checkout in existing submodule
  1267. with open_repo_closing(submodule_git_dir) as sub_repo:
  1268. # Fetch from remote
  1269. client, path_segments = get_transport_and_path(url)
  1270. client.fetch(path_segments, sub_repo)
  1271. # Update to the target commit
  1272. sub_repo.refs[b"HEAD"] = target_sha
  1273. # Reset the working directory
  1274. reset(sub_repo, "hard", target_sha)
  1275. def tag_create(
  1276. repo,
  1277. tag: Union[str, bytes],
  1278. author: Optional[Union[str, bytes]] = None,
  1279. message: Optional[Union[str, bytes]] = None,
  1280. annotated=False,
  1281. objectish: Union[str, bytes] = "HEAD",
  1282. tag_time=None,
  1283. tag_timezone=None,
  1284. sign: bool = False,
  1285. encoding: str = DEFAULT_ENCODING,
  1286. ) -> None:
  1287. """Creates a tag in git via dulwich calls.
  1288. Args:
  1289. repo: Path to repository
  1290. tag: tag string
  1291. author: tag author (optional, if annotated is set)
  1292. message: tag message (optional)
  1293. annotated: whether to create an annotated tag
  1294. objectish: object the tag should point at, defaults to HEAD
  1295. tag_time: Optional time for annotated tag
  1296. tag_timezone: Optional timezone for annotated tag
  1297. sign: GPG Sign the tag (bool, defaults to False,
  1298. pass True to use default GPG key,
  1299. pass a str containing Key ID to use a specific GPG key)
  1300. """
  1301. with open_repo_closing(repo) as r:
  1302. object = parse_object(r, objectish)
  1303. if isinstance(tag, str):
  1304. tag = tag.encode(encoding)
  1305. if annotated:
  1306. # Create the tag object
  1307. tag_obj = Tag()
  1308. if author is None:
  1309. author = get_user_identity(r.get_config_stack())
  1310. elif isinstance(author, str):
  1311. author = author.encode(encoding)
  1312. else:
  1313. assert isinstance(author, bytes)
  1314. tag_obj.tagger = author
  1315. if isinstance(message, str):
  1316. message = message.encode(encoding)
  1317. elif isinstance(message, bytes):
  1318. pass
  1319. else:
  1320. message = b""
  1321. tag_obj.message = message + "\n".encode(encoding)
  1322. tag_obj.name = tag
  1323. tag_obj.object = (type(object), object.id)
  1324. if tag_time is None:
  1325. tag_time = int(time.time())
  1326. tag_obj.tag_time = tag_time
  1327. if tag_timezone is None:
  1328. tag_timezone = get_user_timezones()[1]
  1329. elif isinstance(tag_timezone, str):
  1330. tag_timezone = parse_timezone(tag_timezone.encode())
  1331. tag_obj.tag_timezone = tag_timezone
  1332. # Check if we should sign the tag
  1333. should_sign = sign
  1334. if sign is None:
  1335. # Check tag.gpgSign configuration when sign is not explicitly set
  1336. config = r.get_config_stack()
  1337. try:
  1338. should_sign = config.get_boolean((b"tag",), b"gpgSign")
  1339. except KeyError:
  1340. should_sign = False # Default to not signing if no config
  1341. if should_sign:
  1342. keyid = sign if isinstance(sign, str) else None
  1343. # If sign is True but no keyid specified, check user.signingKey config
  1344. if should_sign is True and keyid is None:
  1345. config = r.get_config_stack()
  1346. try:
  1347. keyid = config.get((b"user",), b"signingKey").decode("ascii")
  1348. except KeyError:
  1349. # No user.signingKey configured, will use default GPG key
  1350. pass
  1351. tag_obj.sign(keyid)
  1352. r.object_store.add_object(tag_obj)
  1353. tag_id = tag_obj.id
  1354. else:
  1355. tag_id = object.id
  1356. r.refs[_make_tag_ref(tag)] = tag_id
  1357. def tag_list(repo, outstream=sys.stdout):
  1358. """List all tags.
  1359. Args:
  1360. repo: Path to repository
  1361. outstream: Stream to write tags to
  1362. """
  1363. with open_repo_closing(repo) as r:
  1364. tags = sorted(r.refs.as_dict(b"refs/tags"))
  1365. return tags
  1366. def tag_delete(repo, name) -> None:
  1367. """Remove a tag.
  1368. Args:
  1369. repo: Path to repository
  1370. name: Name of tag to remove
  1371. """
  1372. with open_repo_closing(repo) as r:
  1373. if isinstance(name, bytes):
  1374. names = [name]
  1375. elif isinstance(name, list):
  1376. names = name
  1377. else:
  1378. raise Error(f"Unexpected tag name type {name!r}")
  1379. for name in names:
  1380. del r.refs[_make_tag_ref(name)]
  1381. def _make_notes_ref(name: bytes) -> bytes:
  1382. """Make a notes ref name."""
  1383. if name.startswith(b"refs/notes/"):
  1384. return name
  1385. return LOCAL_NOTES_PREFIX + name
  1386. def notes_add(
  1387. repo, object_sha, note, ref=b"commits", author=None, committer=None, message=None
  1388. ):
  1389. """Add or update a note for an object.
  1390. Args:
  1391. repo: Path to repository
  1392. object_sha: SHA of the object to annotate
  1393. note: Note content
  1394. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  1395. author: Author identity (defaults to committer)
  1396. committer: Committer identity (defaults to config)
  1397. message: Commit message for the notes update
  1398. Returns:
  1399. SHA of the new notes commit
  1400. """
  1401. with open_repo_closing(repo) as r:
  1402. # Parse the object to get its SHA
  1403. obj = parse_object(r, object_sha)
  1404. object_sha = obj.id
  1405. if isinstance(note, str):
  1406. note = note.encode(DEFAULT_ENCODING)
  1407. if isinstance(ref, str):
  1408. ref = ref.encode(DEFAULT_ENCODING)
  1409. notes_ref = _make_notes_ref(ref)
  1410. config = r.get_config_stack()
  1411. return r.notes.set_note(
  1412. object_sha,
  1413. note,
  1414. notes_ref,
  1415. author=author,
  1416. committer=committer,
  1417. message=message,
  1418. config=config,
  1419. )
  1420. def notes_remove(
  1421. repo, object_sha, ref=b"commits", author=None, committer=None, message=None
  1422. ):
  1423. """Remove a note for an object.
  1424. Args:
  1425. repo: Path to repository
  1426. object_sha: SHA of the object to remove notes from
  1427. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  1428. author: Author identity (defaults to committer)
  1429. committer: Committer identity (defaults to config)
  1430. message: Commit message for the notes removal
  1431. Returns:
  1432. SHA of the new notes commit, or None if no note existed
  1433. """
  1434. with open_repo_closing(repo) as r:
  1435. # Parse the object to get its SHA
  1436. obj = parse_object(r, object_sha)
  1437. object_sha = obj.id
  1438. if isinstance(ref, str):
  1439. ref = ref.encode(DEFAULT_ENCODING)
  1440. notes_ref = _make_notes_ref(ref)
  1441. config = r.get_config_stack()
  1442. return r.notes.remove_note(
  1443. object_sha,
  1444. notes_ref,
  1445. author=author,
  1446. committer=committer,
  1447. message=message,
  1448. config=config,
  1449. )
  1450. def notes_show(repo, object_sha, ref=b"commits"):
  1451. """Show the note for an object.
  1452. Args:
  1453. repo: Path to repository
  1454. object_sha: SHA of the object
  1455. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  1456. Returns:
  1457. Note content as bytes, or None if no note exists
  1458. """
  1459. with open_repo_closing(repo) as r:
  1460. # Parse the object to get its SHA
  1461. obj = parse_object(r, object_sha)
  1462. object_sha = obj.id
  1463. if isinstance(ref, str):
  1464. ref = ref.encode(DEFAULT_ENCODING)
  1465. notes_ref = _make_notes_ref(ref)
  1466. config = r.get_config_stack()
  1467. return r.notes.get_note(object_sha, notes_ref, config=config)
  1468. def notes_list(repo, ref=b"commits"):
  1469. """List all notes in a notes ref.
  1470. Args:
  1471. repo: Path to repository
  1472. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  1473. Returns:
  1474. List of tuples of (object_sha, note_content)
  1475. """
  1476. with open_repo_closing(repo) as r:
  1477. if isinstance(ref, str):
  1478. ref = ref.encode(DEFAULT_ENCODING)
  1479. notes_ref = _make_notes_ref(ref)
  1480. config = r.get_config_stack()
  1481. return r.notes.list_notes(notes_ref, config=config)
  1482. def reset(repo, mode, treeish: Union[str, bytes, Commit, Tree, Tag] = "HEAD") -> None:
  1483. """Reset current HEAD to the specified state.
  1484. Args:
  1485. repo: Path to repository
  1486. mode: Mode ("hard", "soft", "mixed")
  1487. treeish: Treeish to reset to
  1488. """
  1489. with open_repo_closing(repo) as r:
  1490. # Parse the target tree
  1491. tree = parse_tree(r, treeish)
  1492. # Only parse as commit if treeish is not a Tree object
  1493. if isinstance(treeish, Tree):
  1494. # For Tree objects, we can't determine the commit, skip updating HEAD
  1495. target_commit = None
  1496. else:
  1497. target_commit = parse_commit(r, treeish)
  1498. # Update HEAD to point to the target commit
  1499. if target_commit is not None:
  1500. r.refs[b"HEAD"] = target_commit.id
  1501. if mode == "soft":
  1502. # Soft reset: only update HEAD, leave index and working tree unchanged
  1503. return
  1504. elif mode == "mixed":
  1505. # Mixed reset: update HEAD and index, but leave working tree unchanged
  1506. from .index import IndexEntry
  1507. from .object_store import iter_tree_contents
  1508. # Open the index
  1509. index = r.open_index()
  1510. # Clear the current index
  1511. index.clear()
  1512. # Populate index from the target tree
  1513. for entry in iter_tree_contents(r.object_store, tree.id):
  1514. # Create an IndexEntry from the tree entry
  1515. # Use zeros for filesystem-specific fields since we're not touching the working tree
  1516. index_entry = IndexEntry(
  1517. ctime=(0, 0),
  1518. mtime=(0, 0),
  1519. dev=0,
  1520. ino=0,
  1521. mode=entry.mode,
  1522. uid=0,
  1523. gid=0,
  1524. size=0, # Size will be 0 since we're not reading from disk
  1525. sha=entry.sha,
  1526. flags=0,
  1527. )
  1528. index[entry.path] = index_entry
  1529. # Write the updated index
  1530. index.write()
  1531. elif mode == "hard":
  1532. # Hard reset: update HEAD, index, and working tree
  1533. # Get current HEAD tree for comparison
  1534. try:
  1535. current_head = r.refs[b"HEAD"]
  1536. current_tree = r[current_head].tree
  1537. except KeyError:
  1538. current_tree = None
  1539. # Get configuration for working directory update
  1540. config = r.get_config()
  1541. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  1542. # Import validation functions
  1543. from .index import (
  1544. validate_path_element_default,
  1545. validate_path_element_hfs,
  1546. validate_path_element_ntfs,
  1547. )
  1548. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  1549. validate_path_element = validate_path_element_ntfs
  1550. elif config.get_boolean(
  1551. b"core", b"core.protectHFS", sys.platform == "darwin"
  1552. ):
  1553. validate_path_element = validate_path_element_hfs
  1554. else:
  1555. validate_path_element = validate_path_element_default
  1556. if config.get_boolean(b"core", b"symlinks", True):
  1557. # Import symlink function
  1558. from .index import symlink
  1559. symlink_fn = symlink
  1560. else:
  1561. def symlink_fn( # type: ignore
  1562. source, target, target_is_directory=False, *, dir_fd=None
  1563. ) -> None:
  1564. mode = "w" + ("b" if isinstance(source, bytes) else "")
  1565. with open(target, mode) as f:
  1566. f.write(source)
  1567. # Update working tree and index
  1568. blob_normalizer = r.get_blob_normalizer()
  1569. update_working_tree(
  1570. r,
  1571. current_tree,
  1572. tree.id,
  1573. honor_filemode=honor_filemode,
  1574. validate_path_element=validate_path_element,
  1575. symlink_fn=symlink_fn,
  1576. force_remove_untracked=True,
  1577. blob_normalizer=blob_normalizer,
  1578. )
  1579. else:
  1580. raise Error(f"Invalid reset mode: {mode}")
  1581. def get_remote_repo(
  1582. repo: Repo, remote_location: Optional[Union[str, bytes]] = None
  1583. ) -> tuple[Optional[str], str]:
  1584. config = repo.get_config()
  1585. if remote_location is None:
  1586. remote_location = get_branch_remote(repo)
  1587. if isinstance(remote_location, str):
  1588. encoded_location = remote_location.encode()
  1589. else:
  1590. encoded_location = remote_location
  1591. section = (b"remote", encoded_location)
  1592. remote_name: Optional[str] = None
  1593. if config.has_section(section):
  1594. remote_name = encoded_location.decode()
  1595. encoded_location = config.get(section, "url")
  1596. else:
  1597. remote_name = None
  1598. return (remote_name, encoded_location.decode())
  1599. def push(
  1600. repo,
  1601. remote_location=None,
  1602. refspecs=None,
  1603. outstream=default_bytes_out_stream,
  1604. errstream=default_bytes_err_stream,
  1605. force=False,
  1606. **kwargs,
  1607. ):
  1608. """Remote push with dulwich via dulwich.client.
  1609. Args:
  1610. repo: Path to repository
  1611. remote_location: Location of the remote
  1612. refspecs: Refs to push to remote
  1613. outstream: A stream file to write output
  1614. errstream: A stream file to write errors
  1615. force: Force overwriting refs
  1616. """
  1617. # Open the repo
  1618. with open_repo_closing(repo) as r:
  1619. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  1620. # Check if mirror mode is enabled
  1621. mirror_mode = False
  1622. if remote_name:
  1623. try:
  1624. mirror_mode = r.get_config_stack().get_boolean(
  1625. (b"remote", remote_name.encode()), b"mirror"
  1626. )
  1627. except KeyError:
  1628. pass
  1629. if mirror_mode:
  1630. # Mirror mode: push all refs and delete non-existent ones
  1631. refspecs = []
  1632. for ref in r.refs.keys():
  1633. # Push all refs to the same name on remote
  1634. refspecs.append(ref + b":" + ref)
  1635. elif refspecs is None:
  1636. refspecs = [active_branch(r)]
  1637. # Get the client and path
  1638. client, path = get_transport_and_path(
  1639. remote_location, config=r.get_config_stack(), **kwargs
  1640. )
  1641. selected_refs = []
  1642. remote_changed_refs = {}
  1643. def update_refs(refs):
  1644. selected_refs.extend(parse_reftuples(r.refs, refs, refspecs, force=force))
  1645. new_refs = {}
  1646. # In mirror mode, delete remote refs that don't exist locally
  1647. if mirror_mode:
  1648. local_refs = set(r.refs.keys())
  1649. for remote_ref in refs.keys():
  1650. if remote_ref not in local_refs:
  1651. new_refs[remote_ref] = ZERO_SHA
  1652. remote_changed_refs[remote_ref] = None
  1653. # TODO: Handle selected_refs == {None: None}
  1654. for lh, rh, force_ref in selected_refs:
  1655. if lh is None:
  1656. new_refs[rh] = ZERO_SHA
  1657. remote_changed_refs[rh] = None
  1658. else:
  1659. try:
  1660. localsha = r.refs[lh]
  1661. except KeyError as exc:
  1662. raise Error(f"No valid ref {lh} in local repository") from exc
  1663. if not force_ref and rh in refs:
  1664. check_diverged(r, refs[rh], localsha)
  1665. new_refs[rh] = localsha
  1666. remote_changed_refs[rh] = localsha
  1667. return new_refs
  1668. err_encoding = getattr(errstream, "encoding", None) or DEFAULT_ENCODING
  1669. remote_location = client.get_url(path)
  1670. try:
  1671. result = client.send_pack(
  1672. path,
  1673. update_refs,
  1674. generate_pack_data=r.generate_pack_data,
  1675. progress=errstream.write,
  1676. )
  1677. except SendPackError as exc:
  1678. raise Error(
  1679. "Push to " + remote_location + " failed -> " + exc.args[0].decode(),
  1680. ) from exc
  1681. else:
  1682. errstream.write(
  1683. b"Push to " + remote_location.encode(err_encoding) + b" successful.\n"
  1684. )
  1685. for ref, error in (result.ref_status or {}).items():
  1686. if error is not None:
  1687. errstream.write(
  1688. b"Push of ref %s failed: %s\n" % (ref, error.encode(err_encoding))
  1689. )
  1690. else:
  1691. errstream.write(b"Ref %s updated\n" % ref)
  1692. if remote_name is not None:
  1693. _import_remote_refs(r.refs, remote_name, remote_changed_refs)
  1694. return result
  1695. # Trigger auto GC if needed
  1696. from .gc import maybe_auto_gc
  1697. with open_repo_closing(repo) as r:
  1698. maybe_auto_gc(r)
  1699. def pull(
  1700. repo,
  1701. remote_location=None,
  1702. refspecs=None,
  1703. outstream=default_bytes_out_stream,
  1704. errstream=default_bytes_err_stream,
  1705. fast_forward=True,
  1706. ff_only=False,
  1707. force=False,
  1708. filter_spec=None,
  1709. protocol_version=None,
  1710. **kwargs,
  1711. ) -> None:
  1712. """Pull from remote via dulwich.client.
  1713. Args:
  1714. repo: Path to repository
  1715. remote_location: Location of the remote
  1716. refspecs: refspecs to fetch. Can be a bytestring, a string, or a list of
  1717. bytestring/string.
  1718. outstream: A stream file to write to output
  1719. errstream: A stream file to write to errors
  1720. fast_forward: If True, raise an exception when fast-forward is not possible
  1721. ff_only: If True, only allow fast-forward merges. Raises DivergedBranches
  1722. when branches have diverged rather than performing a merge.
  1723. filter_spec: A git-rev-list-style object filter spec, as an ASCII string.
  1724. Only used if the server supports the Git protocol-v2 'filter'
  1725. feature, and ignored otherwise.
  1726. protocol_version: desired Git protocol version. By default the highest
  1727. mutually supported protocol version will be used
  1728. """
  1729. # Open the repo
  1730. with open_repo_closing(repo) as r:
  1731. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  1732. selected_refs = []
  1733. if refspecs is None:
  1734. refspecs = [b"HEAD"]
  1735. def determine_wants(remote_refs, *args, **kwargs):
  1736. selected_refs.extend(
  1737. parse_reftuples(remote_refs, r.refs, refspecs, force=force)
  1738. )
  1739. return [
  1740. remote_refs[lh]
  1741. for (lh, rh, force_ref) in selected_refs
  1742. if remote_refs[lh] not in r.object_store
  1743. ]
  1744. client, path = get_transport_and_path(
  1745. remote_location, config=r.get_config_stack(), **kwargs
  1746. )
  1747. if filter_spec:
  1748. filter_spec = filter_spec.encode("ascii")
  1749. fetch_result = client.fetch(
  1750. path,
  1751. r,
  1752. progress=errstream.write,
  1753. determine_wants=determine_wants,
  1754. filter_spec=filter_spec,
  1755. protocol_version=protocol_version,
  1756. )
  1757. # Store the old HEAD tree before making changes
  1758. try:
  1759. old_head = r.refs[b"HEAD"]
  1760. old_tree_id = r[old_head].tree
  1761. except KeyError:
  1762. old_tree_id = None
  1763. merged = False
  1764. for lh, rh, force_ref in selected_refs:
  1765. if not force_ref and rh in r.refs:
  1766. try:
  1767. check_diverged(r, r.refs.follow(rh)[1], fetch_result.refs[lh])
  1768. except DivergedBranches as exc:
  1769. if ff_only or fast_forward:
  1770. raise
  1771. else:
  1772. # Perform merge
  1773. merge_result, conflicts = _do_merge(r, fetch_result.refs[lh])
  1774. if conflicts:
  1775. raise Error(
  1776. f"Merge conflicts occurred: {conflicts}"
  1777. ) from exc
  1778. merged = True
  1779. # Skip updating ref since merge already updated HEAD
  1780. continue
  1781. r.refs[rh] = fetch_result.refs[lh]
  1782. # Only update HEAD if we didn't perform a merge
  1783. if selected_refs and not merged:
  1784. r[b"HEAD"] = fetch_result.refs[selected_refs[0][1]]
  1785. # Update working tree to match the new HEAD
  1786. # Skip if merge was performed as merge already updates the working tree
  1787. if not merged and old_tree_id is not None:
  1788. new_tree_id = r[b"HEAD"].tree
  1789. blob_normalizer = r.get_blob_normalizer()
  1790. update_working_tree(
  1791. r, old_tree_id, new_tree_id, blob_normalizer=blob_normalizer
  1792. )
  1793. if remote_name is not None:
  1794. _import_remote_refs(r.refs, remote_name, fetch_result.refs)
  1795. # Trigger auto GC if needed
  1796. from .gc import maybe_auto_gc
  1797. with open_repo_closing(repo) as r:
  1798. maybe_auto_gc(r)
  1799. def status(repo=".", ignored=False, untracked_files="normal"):
  1800. """Returns staged, unstaged, and untracked changes relative to the HEAD.
  1801. Args:
  1802. repo: Path to repository or repository object
  1803. ignored: Whether to include ignored files in untracked
  1804. untracked_files: How to handle untracked files, defaults to "all":
  1805. "no": do not return untracked files
  1806. "normal": return untracked directories, not their contents
  1807. "all": include all files in untracked directories
  1808. Using untracked_files="no" can be faster than "all" when the worktree
  1809. contains many untracked files/directories.
  1810. Using untracked_files="normal" provides a good balance, only showing
  1811. directories that are entirely untracked without listing all their contents.
  1812. Returns: GitStatus tuple,
  1813. staged - dict with lists of staged paths (diff index/HEAD)
  1814. unstaged - list of unstaged paths (diff index/working-tree)
  1815. untracked - list of untracked, un-ignored & non-.git paths
  1816. """
  1817. with open_repo_closing(repo) as r:
  1818. # 1. Get status of staged
  1819. tracked_changes = get_tree_changes(r)
  1820. # 2. Get status of unstaged
  1821. index = r.open_index()
  1822. normalizer = r.get_blob_normalizer()
  1823. filter_callback = normalizer.checkin_normalize
  1824. unstaged_changes = list(get_unstaged_changes(index, r.path, filter_callback))
  1825. untracked_paths = get_untracked_paths(
  1826. r.path,
  1827. r.path,
  1828. index,
  1829. exclude_ignored=not ignored,
  1830. untracked_files=untracked_files,
  1831. )
  1832. if sys.platform == "win32":
  1833. untracked_changes = [
  1834. path.replace(os.path.sep, "/") for path in untracked_paths
  1835. ]
  1836. else:
  1837. untracked_changes = list(untracked_paths)
  1838. return GitStatus(tracked_changes, unstaged_changes, untracked_changes)
  1839. def _walk_working_dir_paths(frompath, basepath, prune_dirnames=None):
  1840. """Get path, is_dir for files in working dir from frompath.
  1841. Args:
  1842. frompath: Path to begin walk
  1843. basepath: Path to compare to
  1844. prune_dirnames: Optional callback to prune dirnames during os.walk
  1845. dirnames will be set to result of prune_dirnames(dirpath, dirnames)
  1846. """
  1847. for dirpath, dirnames, filenames in os.walk(frompath):
  1848. # Skip .git and below.
  1849. if ".git" in dirnames:
  1850. dirnames.remove(".git")
  1851. if dirpath != basepath:
  1852. continue
  1853. if ".git" in filenames:
  1854. filenames.remove(".git")
  1855. if dirpath != basepath:
  1856. continue
  1857. if dirpath != frompath:
  1858. yield dirpath, True
  1859. for filename in filenames:
  1860. filepath = os.path.join(dirpath, filename)
  1861. yield filepath, False
  1862. if prune_dirnames:
  1863. dirnames[:] = prune_dirnames(dirpath, dirnames)
  1864. def get_untracked_paths(
  1865. frompath, basepath, index, exclude_ignored=False, untracked_files="all"
  1866. ):
  1867. """Get untracked paths.
  1868. Args:
  1869. frompath: Path to walk
  1870. basepath: Path to compare to
  1871. index: Index to check against
  1872. exclude_ignored: Whether to exclude ignored paths
  1873. untracked_files: How to handle untracked files:
  1874. - "no": return an empty list
  1875. - "all": return all files in untracked directories
  1876. - "normal": return untracked directories without listing their contents
  1877. Note: ignored directories will never be walked for performance reasons.
  1878. If exclude_ignored is False, only the path to an ignored directory will
  1879. be yielded, no files inside the directory will be returned
  1880. """
  1881. if untracked_files not in ("no", "all", "normal"):
  1882. raise ValueError("untracked_files must be one of (no, all, normal)")
  1883. if untracked_files == "no":
  1884. return
  1885. with open_repo_closing(basepath) as r:
  1886. ignore_manager = IgnoreFilterManager.from_repo(r)
  1887. ignored_dirs = []
  1888. # List to store untracked directories found during traversal
  1889. untracked_dir_list = []
  1890. def prune_dirnames(dirpath, dirnames):
  1891. for i in range(len(dirnames) - 1, -1, -1):
  1892. path = os.path.join(dirpath, dirnames[i])
  1893. ip = os.path.join(os.path.relpath(path, basepath), "")
  1894. # Check if directory is ignored
  1895. if ignore_manager.is_ignored(ip):
  1896. if not exclude_ignored:
  1897. ignored_dirs.append(
  1898. os.path.join(os.path.relpath(path, frompath), "")
  1899. )
  1900. del dirnames[i]
  1901. continue
  1902. # For "normal" mode, check if the directory is entirely untracked
  1903. if untracked_files == "normal":
  1904. # Convert directory path to tree path for index lookup
  1905. dir_tree_path = path_to_tree_path(basepath, path)
  1906. # Check if any file in this directory is tracked
  1907. dir_prefix = dir_tree_path + b"/" if dir_tree_path else b""
  1908. has_tracked_files = any(name.startswith(dir_prefix) for name in index)
  1909. if not has_tracked_files:
  1910. # This directory is entirely untracked
  1911. # Check if it should be excluded due to ignore rules
  1912. is_ignored = ignore_manager.is_ignored(
  1913. os.path.relpath(path, basepath)
  1914. )
  1915. if not exclude_ignored or not is_ignored:
  1916. rel_path = os.path.join(os.path.relpath(path, frompath), "")
  1917. untracked_dir_list.append(rel_path)
  1918. del dirnames[i]
  1919. return dirnames
  1920. # For "all" mode, use the original behavior
  1921. if untracked_files == "all":
  1922. for ap, is_dir in _walk_working_dir_paths(
  1923. frompath, basepath, prune_dirnames=prune_dirnames
  1924. ):
  1925. if not is_dir:
  1926. ip = path_to_tree_path(basepath, ap)
  1927. if ip not in index:
  1928. if not exclude_ignored or not ignore_manager.is_ignored(
  1929. os.path.relpath(ap, basepath)
  1930. ):
  1931. yield os.path.relpath(ap, frompath)
  1932. else: # "normal" mode
  1933. # Walk directories, handling both files and directories
  1934. for ap, is_dir in _walk_working_dir_paths(
  1935. frompath, basepath, prune_dirnames=prune_dirnames
  1936. ):
  1937. # This part won't be reached for pruned directories
  1938. if is_dir:
  1939. # Check if this directory is entirely untracked
  1940. dir_tree_path = path_to_tree_path(basepath, ap)
  1941. dir_prefix = dir_tree_path + b"/" if dir_tree_path else b""
  1942. has_tracked_files = any(name.startswith(dir_prefix) for name in index)
  1943. if not has_tracked_files:
  1944. if not exclude_ignored or not ignore_manager.is_ignored(
  1945. os.path.relpath(ap, basepath)
  1946. ):
  1947. yield os.path.join(os.path.relpath(ap, frompath), "")
  1948. else:
  1949. # Check individual files in directories that contain tracked files
  1950. ip = path_to_tree_path(basepath, ap)
  1951. if ip not in index:
  1952. if not exclude_ignored or not ignore_manager.is_ignored(
  1953. os.path.relpath(ap, basepath)
  1954. ):
  1955. yield os.path.relpath(ap, frompath)
  1956. # Yield any untracked directories found during pruning
  1957. yield from untracked_dir_list
  1958. yield from ignored_dirs
  1959. def get_tree_changes(repo):
  1960. """Return add/delete/modify changes to tree by comparing index to HEAD.
  1961. Args:
  1962. repo: repo path or object
  1963. Returns: dict with lists for each type of change
  1964. """
  1965. with open_repo_closing(repo) as r:
  1966. index = r.open_index()
  1967. # Compares the Index to the HEAD & determines changes
  1968. # Iterate through the changes and report add/delete/modify
  1969. # TODO: call out to dulwich.diff_tree somehow.
  1970. tracked_changes = {
  1971. "add": [],
  1972. "delete": [],
  1973. "modify": [],
  1974. }
  1975. try:
  1976. tree_id = r[b"HEAD"].tree
  1977. except KeyError:
  1978. tree_id = None
  1979. for change in index.changes_from_tree(r.object_store, tree_id):
  1980. if not change[0][0]:
  1981. tracked_changes["add"].append(change[0][1])
  1982. elif not change[0][1]:
  1983. tracked_changes["delete"].append(change[0][0])
  1984. elif change[0][0] == change[0][1]:
  1985. tracked_changes["modify"].append(change[0][0])
  1986. else:
  1987. raise NotImplementedError("git mv ops not yet supported")
  1988. return tracked_changes
  1989. def daemon(path=".", address=None, port=None) -> None:
  1990. """Run a daemon serving Git requests over TCP/IP.
  1991. Args:
  1992. path: Path to the directory to serve.
  1993. address: Optional address to listen on (defaults to ::)
  1994. port: Optional port to listen on (defaults to TCP_GIT_PORT)
  1995. """
  1996. # TODO(jelmer): Support git-daemon-export-ok and --export-all.
  1997. backend = FileSystemBackend(path)
  1998. server = TCPGitServer(backend, address, port)
  1999. server.serve_forever()
  2000. def web_daemon(path=".", address=None, port=None) -> None:
  2001. """Run a daemon serving Git requests over HTTP.
  2002. Args:
  2003. path: Path to the directory to serve
  2004. address: Optional address to listen on (defaults to ::)
  2005. port: Optional port to listen on (defaults to 80)
  2006. """
  2007. from .web import (
  2008. WSGIRequestHandlerLogger,
  2009. WSGIServerLogger,
  2010. make_server,
  2011. make_wsgi_chain,
  2012. )
  2013. backend = FileSystemBackend(path)
  2014. app = make_wsgi_chain(backend)
  2015. server = make_server(
  2016. address,
  2017. port,
  2018. app,
  2019. handler_class=WSGIRequestHandlerLogger,
  2020. server_class=WSGIServerLogger,
  2021. )
  2022. server.serve_forever()
  2023. def upload_pack(path=".", inf=None, outf=None) -> int:
  2024. """Upload a pack file after negotiating its contents using smart protocol.
  2025. Args:
  2026. path: Path to the repository
  2027. inf: Input stream to communicate with client
  2028. outf: Output stream to communicate with client
  2029. """
  2030. if outf is None:
  2031. outf = getattr(sys.stdout, "buffer", sys.stdout)
  2032. if inf is None:
  2033. inf = getattr(sys.stdin, "buffer", sys.stdin)
  2034. path = os.path.expanduser(path)
  2035. backend = FileSystemBackend(path)
  2036. def send_fn(data) -> None:
  2037. outf.write(data)
  2038. outf.flush()
  2039. proto = Protocol(inf.read, send_fn)
  2040. handler = UploadPackHandler(backend, [path], proto)
  2041. # FIXME: Catch exceptions and write a single-line summary to outf.
  2042. handler.handle()
  2043. return 0
  2044. def receive_pack(path=".", inf=None, outf=None) -> int:
  2045. """Receive a pack file after negotiating its contents using smart protocol.
  2046. Args:
  2047. path: Path to the repository
  2048. inf: Input stream to communicate with client
  2049. outf: Output stream to communicate with client
  2050. """
  2051. if outf is None:
  2052. outf = getattr(sys.stdout, "buffer", sys.stdout)
  2053. if inf is None:
  2054. inf = getattr(sys.stdin, "buffer", sys.stdin)
  2055. path = os.path.expanduser(path)
  2056. backend = FileSystemBackend(path)
  2057. def send_fn(data) -> None:
  2058. outf.write(data)
  2059. outf.flush()
  2060. proto = Protocol(inf.read, send_fn)
  2061. handler = ReceivePackHandler(backend, [path], proto)
  2062. # FIXME: Catch exceptions and write a single-line summary to outf.
  2063. handler.handle()
  2064. return 0
  2065. def _make_branch_ref(name: Union[str, bytes]) -> Ref:
  2066. if isinstance(name, str):
  2067. name = name.encode(DEFAULT_ENCODING)
  2068. return LOCAL_BRANCH_PREFIX + name
  2069. def _make_tag_ref(name: Union[str, bytes]) -> Ref:
  2070. if isinstance(name, str):
  2071. name = name.encode(DEFAULT_ENCODING)
  2072. return LOCAL_TAG_PREFIX + name
  2073. def branch_delete(repo, name) -> None:
  2074. """Delete a branch.
  2075. Args:
  2076. repo: Path to the repository
  2077. name: Name of the branch
  2078. """
  2079. with open_repo_closing(repo) as r:
  2080. if isinstance(name, list):
  2081. names = name
  2082. else:
  2083. names = [name]
  2084. for name in names:
  2085. del r.refs[_make_branch_ref(name)]
  2086. def branch_create(repo, name, objectish=None, force=False) -> None:
  2087. """Create a branch.
  2088. Args:
  2089. repo: Path to the repository
  2090. name: Name of the new branch
  2091. objectish: Target object to point new branch at (defaults to HEAD)
  2092. force: Force creation of branch, even if it already exists
  2093. """
  2094. with open_repo_closing(repo) as r:
  2095. if objectish is None:
  2096. objectish = "HEAD"
  2097. # Try to expand branch shorthand before parsing
  2098. original_objectish = objectish
  2099. objectish_bytes = (
  2100. objectish.encode(DEFAULT_ENCODING)
  2101. if isinstance(objectish, str)
  2102. else objectish
  2103. )
  2104. if b"refs/remotes/" + objectish_bytes in r.refs:
  2105. objectish = b"refs/remotes/" + objectish_bytes
  2106. elif b"refs/heads/" + objectish_bytes in r.refs:
  2107. objectish = b"refs/heads/" + objectish_bytes
  2108. object = parse_object(r, objectish)
  2109. refname = _make_branch_ref(name)
  2110. ref_message = (
  2111. b"branch: Created from " + original_objectish.encode(DEFAULT_ENCODING)
  2112. if isinstance(original_objectish, str)
  2113. else b"branch: Created from " + original_objectish
  2114. )
  2115. if force:
  2116. r.refs.set_if_equals(refname, None, object.id, message=ref_message)
  2117. else:
  2118. if not r.refs.add_if_new(refname, object.id, message=ref_message):
  2119. raise Error(f"Branch with name {name} already exists.")
  2120. # Check if we should set up tracking
  2121. config = r.get_config_stack()
  2122. try:
  2123. auto_setup_merge = config.get((b"branch",), b"autoSetupMerge").decode()
  2124. except KeyError:
  2125. auto_setup_merge = "true" # Default value
  2126. # Determine if the objectish refers to a remote-tracking branch
  2127. objectish_ref = None
  2128. if original_objectish != "HEAD":
  2129. # Try to resolve objectish as a ref
  2130. objectish_bytes = (
  2131. original_objectish.encode(DEFAULT_ENCODING)
  2132. if isinstance(original_objectish, str)
  2133. else original_objectish
  2134. )
  2135. if objectish_bytes in r.refs:
  2136. objectish_ref = objectish_bytes
  2137. elif b"refs/remotes/" + objectish_bytes in r.refs:
  2138. objectish_ref = b"refs/remotes/" + objectish_bytes
  2139. elif b"refs/heads/" + objectish_bytes in r.refs:
  2140. objectish_ref = b"refs/heads/" + objectish_bytes
  2141. else:
  2142. # HEAD might point to a remote-tracking branch
  2143. head_ref = r.refs.follow(b"HEAD")[0][1]
  2144. if head_ref.startswith(b"refs/remotes/"):
  2145. objectish_ref = head_ref
  2146. # Set up tracking if appropriate
  2147. if objectish_ref and (
  2148. (auto_setup_merge == "always")
  2149. or (
  2150. auto_setup_merge == "true"
  2151. and objectish_ref.startswith(b"refs/remotes/")
  2152. )
  2153. ):
  2154. # Extract remote name and branch from the ref
  2155. if objectish_ref.startswith(b"refs/remotes/"):
  2156. parts = objectish_ref[len(b"refs/remotes/") :].split(b"/", 1)
  2157. if len(parts) == 2:
  2158. remote_name = parts[0]
  2159. remote_branch = b"refs/heads/" + parts[1]
  2160. # Set up tracking
  2161. config = r.get_config()
  2162. branch_name_bytes = (
  2163. name.encode(DEFAULT_ENCODING) if isinstance(name, str) else name
  2164. )
  2165. config.set((b"branch", branch_name_bytes), b"remote", remote_name)
  2166. config.set((b"branch", branch_name_bytes), b"merge", remote_branch)
  2167. config.write_to_path()
  2168. def branch_list(repo):
  2169. """List all branches.
  2170. Args:
  2171. repo: Path to the repository
  2172. Returns:
  2173. List of branch names (without refs/heads/ prefix)
  2174. """
  2175. with open_repo_closing(repo) as r:
  2176. branches = list(r.refs.keys(base=LOCAL_BRANCH_PREFIX))
  2177. # Check for branch.sort configuration
  2178. config = r.get_config_stack()
  2179. try:
  2180. sort_key = config.get((b"branch",), b"sort").decode()
  2181. except KeyError:
  2182. # Default is refname (alphabetical)
  2183. sort_key = "refname"
  2184. # Parse sort key
  2185. reverse = False
  2186. if sort_key.startswith("-"):
  2187. reverse = True
  2188. sort_key = sort_key[1:]
  2189. # Apply sorting
  2190. if sort_key == "refname":
  2191. # Simple alphabetical sort (default)
  2192. branches.sort(reverse=reverse)
  2193. elif sort_key in ("committerdate", "authordate"):
  2194. # Sort by date
  2195. def get_commit_date(branch_name):
  2196. ref = LOCAL_BRANCH_PREFIX + branch_name
  2197. sha = r.refs[ref]
  2198. commit = r.object_store[sha]
  2199. if sort_key == "committerdate":
  2200. return commit.commit_time
  2201. else: # authordate
  2202. return commit.author_time
  2203. # Sort branches by date
  2204. # Note: Python's sort naturally orders smaller values first (ascending)
  2205. # For dates, this means oldest first by default
  2206. # Use a stable sort with branch name as secondary key for consistent ordering
  2207. if reverse:
  2208. # For reverse sort, we want newest dates first but alphabetical names second
  2209. branches.sort(key=lambda b: (-get_commit_date(b), b))
  2210. else:
  2211. branches.sort(key=lambda b: (get_commit_date(b), b))
  2212. else:
  2213. # Unknown sort key, fall back to default
  2214. branches.sort()
  2215. return branches
  2216. def active_branch(repo):
  2217. """Return the active branch in the repository, if any.
  2218. Args:
  2219. repo: Repository to open
  2220. Returns:
  2221. branch name
  2222. Raises:
  2223. KeyError: if the repository does not have a working tree
  2224. IndexError: if HEAD is floating
  2225. """
  2226. with open_repo_closing(repo) as r:
  2227. active_ref = r.refs.follow(b"HEAD")[0][1]
  2228. if not active_ref.startswith(LOCAL_BRANCH_PREFIX):
  2229. raise ValueError(active_ref)
  2230. return active_ref[len(LOCAL_BRANCH_PREFIX) :]
  2231. def get_branch_remote(repo):
  2232. """Return the active branch's remote name, if any.
  2233. Args:
  2234. repo: Repository to open
  2235. Returns:
  2236. remote name
  2237. Raises:
  2238. KeyError: if the repository does not have a working tree
  2239. """
  2240. with open_repo_closing(repo) as r:
  2241. branch_name = active_branch(r.path)
  2242. config = r.get_config()
  2243. try:
  2244. remote_name = config.get((b"branch", branch_name), b"remote")
  2245. except KeyError:
  2246. remote_name = b"origin"
  2247. return remote_name
  2248. def get_branch_merge(repo, branch_name=None):
  2249. """Return the branch's merge reference (upstream branch), if any.
  2250. Args:
  2251. repo: Repository to open
  2252. branch_name: Name of the branch (defaults to active branch)
  2253. Returns:
  2254. merge reference name (e.g. b"refs/heads/main")
  2255. Raises:
  2256. KeyError: if the branch does not have a merge configuration
  2257. """
  2258. with open_repo_closing(repo) as r:
  2259. if branch_name is None:
  2260. branch_name = active_branch(r.path)
  2261. config = r.get_config()
  2262. return config.get((b"branch", branch_name), b"merge")
  2263. def set_branch_tracking(repo, branch_name, remote_name, remote_ref):
  2264. """Set up branch tracking configuration.
  2265. Args:
  2266. repo: Repository to open
  2267. branch_name: Name of the local branch
  2268. remote_name: Name of the remote (e.g. b"origin")
  2269. remote_ref: Remote reference to track (e.g. b"refs/heads/main")
  2270. """
  2271. with open_repo_closing(repo) as r:
  2272. config = r.get_config()
  2273. config.set((b"branch", branch_name), b"remote", remote_name)
  2274. config.set((b"branch", branch_name), b"merge", remote_ref)
  2275. config.write_to_path()
  2276. def fetch(
  2277. repo,
  2278. remote_location=None,
  2279. outstream=sys.stdout,
  2280. errstream=default_bytes_err_stream,
  2281. message=None,
  2282. depth=None,
  2283. prune=False,
  2284. prune_tags=False,
  2285. force=False,
  2286. **kwargs,
  2287. ):
  2288. """Fetch objects from a remote server.
  2289. Args:
  2290. repo: Path to the repository
  2291. remote_location: String identifying a remote server
  2292. outstream: Output stream (defaults to stdout)
  2293. errstream: Error stream (defaults to stderr)
  2294. message: Reflog message (defaults to b"fetch: from <remote_name>")
  2295. depth: Depth to fetch at
  2296. prune: Prune remote removed refs
  2297. prune_tags: Prune reomte removed tags
  2298. Returns:
  2299. Dictionary with refs on the remote
  2300. """
  2301. with open_repo_closing(repo) as r:
  2302. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  2303. if message is None:
  2304. message = b"fetch: from " + remote_location.encode(DEFAULT_ENCODING)
  2305. client, path = get_transport_and_path(
  2306. remote_location, config=r.get_config_stack(), **kwargs
  2307. )
  2308. fetch_result = client.fetch(path, r, progress=errstream.write, depth=depth)
  2309. if remote_name is not None:
  2310. _import_remote_refs(
  2311. r.refs,
  2312. remote_name,
  2313. fetch_result.refs,
  2314. message,
  2315. prune=prune,
  2316. prune_tags=prune_tags,
  2317. )
  2318. # Trigger auto GC if needed
  2319. from .gc import maybe_auto_gc
  2320. with open_repo_closing(repo) as r:
  2321. maybe_auto_gc(r)
  2322. return fetch_result
  2323. def for_each_ref(
  2324. repo: Union[Repo, str] = ".",
  2325. pattern: Optional[Union[str, bytes]] = None,
  2326. ) -> list[tuple[bytes, bytes, bytes]]:
  2327. """Iterate over all refs that match the (optional) pattern.
  2328. Args:
  2329. repo: Path to the repository
  2330. pattern: Optional glob (7) patterns to filter the refs with
  2331. Returns: List of bytes tuples with: (sha, object_type, ref_name)
  2332. """
  2333. if isinstance(pattern, str):
  2334. pattern = os.fsencode(pattern)
  2335. with open_repo_closing(repo) as r:
  2336. refs = r.get_refs()
  2337. if pattern:
  2338. matching_refs: dict[bytes, bytes] = {}
  2339. pattern_parts = pattern.split(b"/")
  2340. for ref, sha in refs.items():
  2341. matches = False
  2342. # git for-each-ref uses glob (7) style patterns, but fnmatch
  2343. # is greedy and also matches slashes, unlike glob.glob.
  2344. # We have to check parts of the pattern individually.
  2345. # See https://github.com/python/cpython/issues/72904
  2346. ref_parts = ref.split(b"/")
  2347. if len(ref_parts) > len(pattern_parts):
  2348. continue
  2349. for pat, ref_part in zip(pattern_parts, ref_parts):
  2350. matches = fnmatch.fnmatchcase(ref_part, pat)
  2351. if not matches:
  2352. break
  2353. if matches:
  2354. matching_refs[ref] = sha
  2355. refs = matching_refs
  2356. ret: list[tuple[bytes, bytes, bytes]] = [
  2357. (sha, r.get_object(sha).type_name, ref)
  2358. for ref, sha in sorted(
  2359. refs.items(),
  2360. key=lambda ref_sha: ref_sha[0],
  2361. )
  2362. if ref != b"HEAD"
  2363. ]
  2364. return ret
  2365. def ls_remote(remote, config: Optional[Config] = None, **kwargs):
  2366. """List the refs in a remote.
  2367. Args:
  2368. remote: Remote repository location
  2369. config: Configuration to use
  2370. Returns:
  2371. LsRemoteResult object with refs and symrefs
  2372. """
  2373. if config is None:
  2374. config = StackedConfig.default()
  2375. client, host_path = get_transport_and_path(remote, config=config, **kwargs)
  2376. return client.get_refs(host_path)
  2377. def repack(repo) -> None:
  2378. """Repack loose files in a repository.
  2379. Currently this only packs loose objects.
  2380. Args:
  2381. repo: Path to the repository
  2382. """
  2383. with open_repo_closing(repo) as r:
  2384. r.object_store.pack_loose_objects()
  2385. def pack_objects(
  2386. repo,
  2387. object_ids,
  2388. packf,
  2389. idxf,
  2390. delta_window_size=None,
  2391. deltify=None,
  2392. reuse_deltas=True,
  2393. pack_index_version=None,
  2394. ) -> None:
  2395. """Pack objects into a file.
  2396. Args:
  2397. repo: Path to the repository
  2398. object_ids: List of object ids to write
  2399. packf: File-like object to write to
  2400. idxf: File-like object to write to (can be None)
  2401. delta_window_size: Sliding window size for searching for deltas;
  2402. Set to None for default window size.
  2403. deltify: Whether to deltify objects
  2404. reuse_deltas: Allow reuse of existing deltas while deltifying
  2405. pack_index_version: Pack index version to use (1, 2, or 3). If None, uses default version.
  2406. """
  2407. with open_repo_closing(repo) as r:
  2408. entries, data_sum = write_pack_from_container(
  2409. packf.write,
  2410. r.object_store,
  2411. [(oid, None) for oid in object_ids],
  2412. deltify=deltify,
  2413. delta_window_size=delta_window_size,
  2414. reuse_deltas=reuse_deltas,
  2415. )
  2416. if idxf is not None:
  2417. entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
  2418. write_pack_index(idxf, entries, data_sum, version=pack_index_version)
  2419. def ls_tree(
  2420. repo,
  2421. treeish: Union[str, bytes, Commit, Tree, Tag] = b"HEAD",
  2422. outstream=sys.stdout,
  2423. recursive=False,
  2424. name_only=False,
  2425. ) -> None:
  2426. """List contents of a tree.
  2427. Args:
  2428. repo: Path to the repository
  2429. treeish: Tree id to list
  2430. outstream: Output stream (defaults to stdout)
  2431. recursive: Whether to recursively list files
  2432. name_only: Only print item name
  2433. """
  2434. def list_tree(store, treeid, base) -> None:
  2435. for name, mode, sha in store[treeid].iteritems():
  2436. if base:
  2437. name = posixpath.join(base, name)
  2438. if name_only:
  2439. outstream.write(name + b"\n")
  2440. else:
  2441. outstream.write(pretty_format_tree_entry(name, mode, sha))
  2442. if stat.S_ISDIR(mode) and recursive:
  2443. list_tree(store, sha, name)
  2444. with open_repo_closing(repo) as r:
  2445. tree = parse_tree(r, treeish)
  2446. list_tree(r.object_store, tree.id, "")
  2447. def remote_add(repo, name: Union[bytes, str], url: Union[bytes, str]) -> None:
  2448. """Add a remote.
  2449. Args:
  2450. repo: Path to the repository
  2451. name: Remote name
  2452. url: Remote URL
  2453. """
  2454. if not isinstance(name, bytes):
  2455. name = name.encode(DEFAULT_ENCODING)
  2456. if not isinstance(url, bytes):
  2457. url = url.encode(DEFAULT_ENCODING)
  2458. with open_repo_closing(repo) as r:
  2459. c = r.get_config()
  2460. section = (b"remote", name)
  2461. if c.has_section(section):
  2462. raise RemoteExists(section)
  2463. c.set(section, b"url", url)
  2464. c.write_to_path()
  2465. def remote_remove(repo: Repo, name: Union[bytes, str]) -> None:
  2466. """Remove a remote.
  2467. Args:
  2468. repo: Path to the repository
  2469. name: Remote name
  2470. """
  2471. if not isinstance(name, bytes):
  2472. name = name.encode(DEFAULT_ENCODING)
  2473. with open_repo_closing(repo) as r:
  2474. c = r.get_config()
  2475. section = (b"remote", name)
  2476. del c[section]
  2477. c.write_to_path()
  2478. def _quote_path(path: str) -> str:
  2479. """Quote a path using C-style quoting similar to git's core.quotePath.
  2480. Args:
  2481. path: Path to quote
  2482. Returns:
  2483. Quoted path string
  2484. """
  2485. # Check if path needs quoting (non-ASCII or special characters)
  2486. needs_quoting = False
  2487. for char in path:
  2488. if ord(char) > 127 or char in '"\\':
  2489. needs_quoting = True
  2490. break
  2491. if not needs_quoting:
  2492. return path
  2493. # Apply C-style quoting
  2494. quoted = '"'
  2495. for char in path:
  2496. if ord(char) > 127:
  2497. # Non-ASCII character, encode as octal escape
  2498. utf8_bytes = char.encode("utf-8")
  2499. for byte in utf8_bytes:
  2500. quoted += f"\\{byte:03o}"
  2501. elif char == '"':
  2502. quoted += '\\"'
  2503. elif char == "\\":
  2504. quoted += "\\\\"
  2505. else:
  2506. quoted += char
  2507. quoted += '"'
  2508. return quoted
  2509. def check_ignore(repo, paths, no_index=False, quote_path=True):
  2510. r"""Debug gitignore files.
  2511. Args:
  2512. repo: Path to the repository
  2513. paths: List of paths to check for
  2514. no_index: Don't check index
  2515. quote_path: If True, quote non-ASCII characters in returned paths using
  2516. C-style octal escapes (e.g. "тест.txt" becomes "\\321\\202\\320\\265\\321\\201\\321\\202.txt").
  2517. If False, return raw unicode paths.
  2518. Returns: List of ignored files
  2519. """
  2520. with open_repo_closing(repo) as r:
  2521. index = r.open_index()
  2522. ignore_manager = IgnoreFilterManager.from_repo(r)
  2523. for original_path in paths:
  2524. if not no_index and path_to_tree_path(r.path, original_path) in index:
  2525. continue
  2526. # Preserve whether the original path had a trailing slash
  2527. had_trailing_slash = original_path.endswith(("/", os.path.sep))
  2528. if os.path.isabs(original_path):
  2529. path = os.path.relpath(original_path, r.path)
  2530. # Normalize Windows paths to use forward slashes
  2531. if os.path.sep != "/":
  2532. path = path.replace(os.path.sep, "/")
  2533. else:
  2534. path = original_path
  2535. # Restore trailing slash if it was in the original
  2536. if had_trailing_slash and not path.endswith("/"):
  2537. path = path + "/"
  2538. # For directories, check with trailing slash to get correct ignore behavior
  2539. test_path = path
  2540. path_without_slash = path.rstrip("/")
  2541. is_directory = os.path.isdir(os.path.join(r.path, path_without_slash))
  2542. # If this is a directory path, ensure we test it correctly
  2543. if is_directory and not path.endswith("/"):
  2544. test_path = path + "/"
  2545. if ignore_manager.is_ignored(test_path):
  2546. # Return relative path (like git does) when absolute path was provided
  2547. if os.path.isabs(original_path):
  2548. output_path = path
  2549. else:
  2550. output_path = original_path
  2551. yield _quote_path(output_path) if quote_path else output_path
  2552. def update_head(repo, target, detached=False, new_branch=None) -> None:
  2553. """Update HEAD to point at a new branch/commit.
  2554. Note that this does not actually update the working tree.
  2555. Args:
  2556. repo: Path to the repository
  2557. detached: Create a detached head
  2558. target: Branch or committish to switch to
  2559. new_branch: New branch to create
  2560. """
  2561. with open_repo_closing(repo) as r:
  2562. if new_branch is not None:
  2563. to_set = _make_branch_ref(new_branch)
  2564. else:
  2565. to_set = b"HEAD"
  2566. if detached:
  2567. # TODO(jelmer): Provide some way so that the actual ref gets
  2568. # updated rather than what it points to, so the delete isn't
  2569. # necessary.
  2570. del r.refs[to_set]
  2571. r.refs[to_set] = parse_commit(r, target).id
  2572. else:
  2573. r.refs.set_symbolic_ref(to_set, parse_ref(r, target))
  2574. if new_branch is not None:
  2575. r.refs.set_symbolic_ref(b"HEAD", to_set)
  2576. def checkout(
  2577. repo,
  2578. target: Union[str, bytes, Commit, Tag],
  2579. force: bool = False,
  2580. new_branch: Optional[Union[bytes, str]] = None,
  2581. ) -> None:
  2582. """Switch to a branch or commit, updating both HEAD and the working tree.
  2583. This is similar to 'git checkout', allowing you to switch to a branch,
  2584. tag, or specific commit. Unlike update_head, this function also updates
  2585. the working tree to match the target.
  2586. Args:
  2587. repo: Path to repository or repository object
  2588. target: Branch name, tag, or commit SHA to checkout
  2589. force: Force checkout even if there are local changes
  2590. new_branch: Create a new branch at target (like git checkout -b)
  2591. Raises:
  2592. CheckoutError: If checkout cannot be performed due to conflicts
  2593. KeyError: If the target reference cannot be found
  2594. """
  2595. with open_repo_closing(repo) as r:
  2596. # Store the original target for later reference checks
  2597. original_target = target
  2598. if isinstance(target, str):
  2599. target_bytes = target.encode(DEFAULT_ENCODING)
  2600. elif isinstance(target, bytes):
  2601. target_bytes = target
  2602. else:
  2603. # For Commit/Tag objects, we'll use their SHA
  2604. target_bytes = target.id
  2605. if isinstance(new_branch, str):
  2606. new_branch = new_branch.encode(DEFAULT_ENCODING)
  2607. # Parse the target to get the commit
  2608. target_commit = parse_commit(r, original_target)
  2609. target_tree_id = target_commit.tree
  2610. # Get current HEAD tree for comparison
  2611. try:
  2612. current_head = r.refs[b"HEAD"]
  2613. current_tree_id = r[current_head].tree
  2614. except KeyError:
  2615. # No HEAD yet (empty repo)
  2616. current_tree_id = None
  2617. # Check for uncommitted changes if not forcing
  2618. if not force and current_tree_id is not None:
  2619. status_report = status(r)
  2620. changes = []
  2621. # staged is a dict with 'add', 'delete', 'modify' keys
  2622. if isinstance(status_report.staged, dict):
  2623. changes.extend(status_report.staged.get("add", []))
  2624. changes.extend(status_report.staged.get("delete", []))
  2625. changes.extend(status_report.staged.get("modify", []))
  2626. # unstaged is a list
  2627. changes.extend(status_report.unstaged)
  2628. if changes:
  2629. # Check if any changes would conflict with checkout
  2630. target_tree = r[target_tree_id]
  2631. for change in changes:
  2632. if isinstance(change, str):
  2633. change = change.encode(DEFAULT_ENCODING)
  2634. try:
  2635. target_tree.lookup_path(r.object_store.__getitem__, change)
  2636. # File exists in target tree - would overwrite local changes
  2637. raise CheckoutError(
  2638. f"Your local changes to '{change.decode()}' would be "
  2639. "overwritten by checkout. Please commit or stash before switching."
  2640. )
  2641. except KeyError:
  2642. # File doesn't exist in target tree - change can be preserved
  2643. pass
  2644. # Get configuration for working directory update
  2645. config = r.get_config()
  2646. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  2647. # Import validation functions
  2648. from .index import validate_path_element_default, validate_path_element_ntfs
  2649. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  2650. validate_path_element = validate_path_element_ntfs
  2651. else:
  2652. validate_path_element = validate_path_element_default
  2653. if config.get_boolean(b"core", b"symlinks", True):
  2654. # Import symlink function
  2655. from .index import symlink
  2656. symlink_fn = symlink
  2657. else:
  2658. def symlink_fn(source, target) -> None: # type: ignore
  2659. mode = "w" + ("b" if isinstance(source, bytes) else "")
  2660. with open(target, mode) as f:
  2661. f.write(source)
  2662. # Get blob normalizer for line ending conversion
  2663. blob_normalizer = r.get_blob_normalizer()
  2664. # Update working tree
  2665. update_working_tree(
  2666. r,
  2667. current_tree_id,
  2668. target_tree_id,
  2669. honor_filemode=honor_filemode,
  2670. validate_path_element=validate_path_element,
  2671. symlink_fn=symlink_fn,
  2672. force_remove_untracked=force,
  2673. blob_normalizer=blob_normalizer,
  2674. )
  2675. # Update HEAD
  2676. if new_branch:
  2677. # Create new branch and switch to it
  2678. branch_create(r, new_branch, objectish=target_commit.id.decode("ascii"))
  2679. update_head(r, new_branch)
  2680. # Set up tracking if creating from a remote branch
  2681. from .refs import LOCAL_REMOTE_PREFIX, parse_remote_ref
  2682. if isinstance(original_target, bytes) and target_bytes.startswith(
  2683. LOCAL_REMOTE_PREFIX
  2684. ):
  2685. try:
  2686. remote_name, branch_name = parse_remote_ref(target_bytes)
  2687. # Set tracking to refs/heads/<branch> on the remote
  2688. set_branch_tracking(
  2689. r, new_branch, remote_name, b"refs/heads/" + branch_name
  2690. )
  2691. except ValueError:
  2692. # Invalid remote ref format, skip tracking setup
  2693. pass
  2694. else:
  2695. # Check if target is a branch name (with or without refs/heads/ prefix)
  2696. branch_ref = None
  2697. if (
  2698. isinstance(original_target, (str, bytes))
  2699. and target_bytes in r.refs.keys()
  2700. ):
  2701. if target_bytes.startswith(LOCAL_BRANCH_PREFIX):
  2702. branch_ref = target_bytes
  2703. else:
  2704. # Try adding refs/heads/ prefix
  2705. potential_branch = (
  2706. _make_branch_ref(target_bytes)
  2707. if isinstance(original_target, (str, bytes))
  2708. else None
  2709. )
  2710. if potential_branch in r.refs.keys():
  2711. branch_ref = potential_branch
  2712. if branch_ref:
  2713. # It's a branch - update HEAD symbolically
  2714. update_head(r, branch_ref)
  2715. else:
  2716. # It's a tag, other ref, or commit SHA - detached HEAD
  2717. update_head(r, target_commit.id.decode("ascii"), detached=True)
  2718. def reset_file(
  2719. repo,
  2720. file_path: str,
  2721. target: Union[str, bytes, Commit, Tree, Tag] = b"HEAD",
  2722. symlink_fn=None,
  2723. ) -> None:
  2724. """Reset the file to specific commit or branch.
  2725. Args:
  2726. repo: dulwich Repo object
  2727. file_path: file to reset, relative to the repository path
  2728. target: branch or commit or b'HEAD' to reset
  2729. """
  2730. tree = parse_tree(repo, treeish=target)
  2731. tree_path = _fs_to_tree_path(file_path)
  2732. file_entry = tree.lookup_path(repo.object_store.__getitem__, tree_path)
  2733. full_path = os.path.join(os.fsencode(repo.path), tree_path)
  2734. blob = repo.object_store[file_entry[1]]
  2735. mode = file_entry[0]
  2736. build_file_from_blob(blob, mode, full_path, symlink_fn=symlink_fn)
  2737. @replace_me(since="0.22.9", remove_in="0.24.0")
  2738. def checkout_branch(repo, target: Union[bytes, str], force: bool = False) -> None:
  2739. """Switch branches or restore working tree files.
  2740. This is now a wrapper around the general checkout() function.
  2741. Preserved for backward compatibility.
  2742. Args:
  2743. repo: dulwich Repo object
  2744. target: branch name or commit sha to checkout
  2745. force: true or not to force checkout
  2746. """
  2747. # Simply delegate to the new checkout function
  2748. return checkout(repo, target, force=force)
  2749. def sparse_checkout(
  2750. repo, patterns=None, force: bool = False, cone: Union[bool, None] = None
  2751. ):
  2752. """Perform a sparse checkout in the repository (either 'full' or 'cone mode').
  2753. Perform sparse checkout in either 'cone' (directory-based) mode or
  2754. 'full pattern' (.gitignore) mode, depending on the ``cone`` parameter.
  2755. If ``cone`` is ``None``, the mode is inferred from the repository's
  2756. ``core.sparseCheckoutCone`` config setting.
  2757. Steps:
  2758. 1) If ``patterns`` is provided, write them to ``.git/info/sparse-checkout``.
  2759. 2) Determine which paths in the index are included vs. excluded.
  2760. - If ``cone=True``, use "cone-compatible" directory-based logic.
  2761. - If ``cone=False``, use standard .gitignore-style matching.
  2762. 3) Update the index's skip-worktree bits and add/remove files in
  2763. the working tree accordingly.
  2764. 4) If ``force=False``, refuse to remove files that have local modifications.
  2765. Args:
  2766. repo: Path to the repository or a Repo object.
  2767. patterns: Optional list of sparse-checkout patterns to write.
  2768. force: Whether to force removal of locally modified files (default False).
  2769. cone: Boolean indicating cone mode (True/False). If None, read from config.
  2770. Returns:
  2771. None
  2772. """
  2773. with open_repo_closing(repo) as repo_obj:
  2774. # --- 0) Possibly infer 'cone' from config ---
  2775. if cone is None:
  2776. cone = repo_obj.infer_cone_mode()
  2777. # --- 1) Read or write patterns ---
  2778. if patterns is None:
  2779. lines = repo_obj.get_sparse_checkout_patterns()
  2780. if lines is None:
  2781. raise Error("No sparse checkout patterns found.")
  2782. else:
  2783. lines = patterns
  2784. repo_obj.set_sparse_checkout_patterns(patterns)
  2785. # --- 2) Determine the set of included paths ---
  2786. included_paths = determine_included_paths(repo_obj, lines, cone)
  2787. # --- 3) Apply those results to the index & working tree ---
  2788. try:
  2789. apply_included_paths(repo_obj, included_paths, force=force)
  2790. except SparseCheckoutConflictError as exc:
  2791. raise CheckoutError(*exc.args) from exc
  2792. def cone_mode_init(repo):
  2793. """Initialize a repository to use sparse checkout in 'cone' mode.
  2794. Sets ``core.sparseCheckout`` and ``core.sparseCheckoutCone`` in the config.
  2795. Writes an initial ``.git/info/sparse-checkout`` file that includes only
  2796. top-level files (and excludes all subdirectories), e.g. ``["/*", "!/*/"]``.
  2797. Then performs a sparse checkout to update the working tree accordingly.
  2798. If no directories are specified, then only top-level files are included:
  2799. https://git-scm.com/docs/git-sparse-checkout#_internalscone_mode_handling
  2800. Args:
  2801. repo: Path to the repository or a Repo object.
  2802. Returns:
  2803. None
  2804. """
  2805. with open_repo_closing(repo) as repo_obj:
  2806. repo_obj.configure_for_cone_mode()
  2807. patterns = ["/*", "!/*/"] # root-level files only
  2808. sparse_checkout(repo_obj, patterns, force=True, cone=True)
  2809. def cone_mode_set(repo, dirs, force=False):
  2810. """Overwrite the existing 'cone-mode' sparse patterns with a new set of directories.
  2811. Ensures ``core.sparseCheckout`` and ``core.sparseCheckoutCone`` are enabled.
  2812. Writes new patterns so that only the specified directories (and top-level files)
  2813. remain in the working tree, and applies the sparse checkout update.
  2814. Args:
  2815. repo: Path to the repository or a Repo object.
  2816. dirs: List of directory names to include.
  2817. force: Whether to forcibly discard local modifications (default False).
  2818. Returns:
  2819. None
  2820. """
  2821. with open_repo_closing(repo) as repo_obj:
  2822. repo_obj.configure_for_cone_mode()
  2823. repo_obj.set_cone_mode_patterns(dirs=dirs)
  2824. new_patterns = repo_obj.get_sparse_checkout_patterns()
  2825. # Finally, apply the patterns and update the working tree
  2826. sparse_checkout(repo_obj, new_patterns, force=force, cone=True)
  2827. def cone_mode_add(repo, dirs, force=False):
  2828. """Add new directories to the existing 'cone-mode' sparse-checkout patterns.
  2829. Reads the current patterns from ``.git/info/sparse-checkout``, adds pattern
  2830. lines to include the specified directories, and then performs a sparse
  2831. checkout to update the working tree accordingly.
  2832. Args:
  2833. repo: Path to the repository or a Repo object.
  2834. dirs: List of directory names to add to the sparse-checkout.
  2835. force: Whether to forcibly discard local modifications (default False).
  2836. Returns:
  2837. None
  2838. """
  2839. with open_repo_closing(repo) as repo_obj:
  2840. repo_obj.configure_for_cone_mode()
  2841. # Do not pass base patterns as dirs
  2842. base_patterns = ["/*", "!/*/"]
  2843. existing_dirs = [
  2844. pat.strip("/")
  2845. for pat in repo_obj.get_sparse_checkout_patterns()
  2846. if pat not in base_patterns
  2847. ]
  2848. added_dirs = existing_dirs + (dirs or [])
  2849. repo_obj.set_cone_mode_patterns(dirs=added_dirs)
  2850. new_patterns = repo_obj.get_sparse_checkout_patterns()
  2851. sparse_checkout(repo_obj, patterns=new_patterns, force=force, cone=True)
  2852. def check_mailmap(repo, contact):
  2853. """Check canonical name and email of contact.
  2854. Args:
  2855. repo: Path to the repository
  2856. contact: Contact name and/or email
  2857. Returns: Canonical contact data
  2858. """
  2859. with open_repo_closing(repo) as r:
  2860. from .mailmap import Mailmap
  2861. try:
  2862. mailmap = Mailmap.from_path(os.path.join(r.path, ".mailmap"))
  2863. except FileNotFoundError:
  2864. mailmap = Mailmap()
  2865. return mailmap.lookup(contact)
  2866. def fsck(repo):
  2867. """Check a repository.
  2868. Args:
  2869. repo: A path to the repository
  2870. Returns: Iterator over errors/warnings
  2871. """
  2872. with open_repo_closing(repo) as r:
  2873. # TODO(jelmer): check pack files
  2874. # TODO(jelmer): check graph
  2875. # TODO(jelmer): check refs
  2876. for sha in r.object_store:
  2877. o = r.object_store[sha]
  2878. try:
  2879. o.check()
  2880. except Exception as e:
  2881. yield (sha, e)
  2882. def stash_list(repo):
  2883. """List all stashes in a repository."""
  2884. with open_repo_closing(repo) as r:
  2885. from .stash import Stash
  2886. stash = Stash.from_repo(r)
  2887. return enumerate(list(stash.stashes()))
  2888. def stash_push(repo) -> None:
  2889. """Push a new stash onto the stack."""
  2890. with open_repo_closing(repo) as r:
  2891. from .stash import Stash
  2892. stash = Stash.from_repo(r)
  2893. stash.push()
  2894. def stash_pop(repo) -> None:
  2895. """Pop a stash from the stack."""
  2896. with open_repo_closing(repo) as r:
  2897. from .stash import Stash
  2898. stash = Stash.from_repo(r)
  2899. stash.pop(0)
  2900. def stash_drop(repo, index) -> None:
  2901. """Drop a stash from the stack."""
  2902. with open_repo_closing(repo) as r:
  2903. from .stash import Stash
  2904. stash = Stash.from_repo(r)
  2905. stash.drop(index)
  2906. def ls_files(repo):
  2907. """List all files in an index."""
  2908. with open_repo_closing(repo) as r:
  2909. return sorted(r.open_index())
  2910. def find_unique_abbrev(object_store, object_id, min_length=7):
  2911. """Find the shortest unique abbreviation for an object ID.
  2912. Args:
  2913. object_store: Object store to search in
  2914. object_id: The full object ID to abbreviate
  2915. min_length: Minimum length of abbreviation (default 7)
  2916. Returns:
  2917. The shortest unique prefix of the object ID (at least min_length chars)
  2918. """
  2919. if isinstance(object_id, bytes):
  2920. hex_id = object_id.decode("ascii")
  2921. else:
  2922. hex_id = object_id
  2923. # Start with minimum length
  2924. for length in range(min_length, len(hex_id) + 1):
  2925. prefix = hex_id[:length]
  2926. matches = 0
  2927. # Check if this prefix is unique
  2928. for obj_id in object_store:
  2929. if obj_id.decode("ascii").startswith(prefix):
  2930. matches += 1
  2931. if matches > 1:
  2932. # Not unique, need more characters
  2933. break
  2934. if matches == 1:
  2935. # Found unique prefix
  2936. return prefix
  2937. # If we get here, return the full ID
  2938. return hex_id
  2939. def describe(repo, abbrev=None):
  2940. """Describe the repository version.
  2941. Args:
  2942. repo: git repository
  2943. abbrev: number of characters of commit to take, default is 7
  2944. Returns: a string description of the current git revision
  2945. Examples: "gabcdefh", "v0.1" or "v0.1-5-gabcdefh".
  2946. """
  2947. abbrev_slice = slice(0, abbrev if abbrev is not None else 7)
  2948. # Get the repository
  2949. with open_repo_closing(repo) as r:
  2950. # Get a list of all tags
  2951. refs = r.get_refs()
  2952. tags = {}
  2953. for key, value in refs.items():
  2954. key = key.decode()
  2955. obj = r.get_object(value)
  2956. if "tags" not in key:
  2957. continue
  2958. _, tag = key.rsplit("/", 1)
  2959. try:
  2960. # Annotated tag case
  2961. commit = obj.object
  2962. commit = r.get_object(commit[1])
  2963. except AttributeError:
  2964. # Lightweight tag case - obj is already the commit
  2965. commit = obj
  2966. tags[tag] = [
  2967. datetime.datetime(*time.gmtime(commit.commit_time)[:6]),
  2968. commit.id.decode("ascii"),
  2969. ]
  2970. sorted_tags = sorted(tags.items(), key=lambda tag: tag[1][0], reverse=True)
  2971. # Get the latest commit
  2972. latest_commit = r[r.head()]
  2973. # If there are no tags, return the latest commit
  2974. if len(sorted_tags) == 0:
  2975. if abbrev is not None:
  2976. return "g{}".format(latest_commit.id.decode("ascii")[abbrev_slice])
  2977. return f"g{find_unique_abbrev(r.object_store, latest_commit.id)}"
  2978. # We're now 0 commits from the top
  2979. commit_count = 0
  2980. # Walk through all commits
  2981. walker = r.get_walker()
  2982. for entry in walker:
  2983. # Check if tag
  2984. commit_id = entry.commit.id.decode("ascii")
  2985. for tag in sorted_tags:
  2986. tag_name = tag[0]
  2987. tag_commit = tag[1][1]
  2988. if commit_id == tag_commit:
  2989. if commit_count == 0:
  2990. return tag_name
  2991. else:
  2992. if abbrev is not None:
  2993. abbrev_hash = latest_commit.id.decode("ascii")[abbrev_slice]
  2994. else:
  2995. abbrev_hash = find_unique_abbrev(
  2996. r.object_store, latest_commit.id
  2997. )
  2998. return f"{tag_name}-{commit_count}-g{abbrev_hash}"
  2999. commit_count += 1
  3000. # Return plain commit if no parent tag can be found
  3001. if abbrev is not None:
  3002. return "g{}".format(latest_commit.id.decode("ascii")[abbrev_slice])
  3003. return f"g{find_unique_abbrev(r.object_store, latest_commit.id)}"
  3004. def get_object_by_path(
  3005. repo, path, committish: Optional[Union[str, bytes, Commit, Tag]] = None
  3006. ):
  3007. """Get an object by path.
  3008. Args:
  3009. repo: A path to the repository
  3010. path: Path to look up
  3011. committish: Commit to look up path in
  3012. Returns: A `ShaFile` object
  3013. """
  3014. if committish is None:
  3015. committish = "HEAD"
  3016. # Get the repository
  3017. with open_repo_closing(repo) as r:
  3018. commit = parse_commit(r, committish)
  3019. base_tree = commit.tree
  3020. if not isinstance(path, bytes):
  3021. path = commit_encode(commit, path)
  3022. (mode, sha) = tree_lookup_path(r.object_store.__getitem__, base_tree, path)
  3023. return r[sha]
  3024. def write_tree(repo):
  3025. """Write a tree object from the index.
  3026. Args:
  3027. repo: Repository for which to write tree
  3028. Returns: tree id for the tree that was written
  3029. """
  3030. with open_repo_closing(repo) as r:
  3031. return r.open_index().commit(r.object_store)
  3032. def _do_merge(
  3033. r,
  3034. merge_commit_id,
  3035. no_commit=False,
  3036. no_ff=False,
  3037. message=None,
  3038. author=None,
  3039. committer=None,
  3040. ):
  3041. """Internal merge implementation that operates on an open repository.
  3042. Args:
  3043. r: Open repository object
  3044. merge_commit_id: SHA of commit to merge
  3045. no_commit: If True, do not create a merge commit
  3046. no_ff: If True, force creation of a merge commit
  3047. message: Optional merge commit message
  3048. author: Optional author for merge commit
  3049. committer: Optional committer for merge commit
  3050. Returns:
  3051. Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None
  3052. if no_commit=True or there were conflicts
  3053. """
  3054. from .graph import find_merge_base
  3055. from .merge import three_way_merge
  3056. # Get HEAD commit
  3057. try:
  3058. head_commit_id = r.refs[b"HEAD"]
  3059. except KeyError:
  3060. raise Error("No HEAD reference found")
  3061. head_commit = r[head_commit_id]
  3062. merge_commit = r[merge_commit_id]
  3063. # Check if fast-forward is possible
  3064. merge_bases = find_merge_base(r, [head_commit_id, merge_commit_id])
  3065. if not merge_bases:
  3066. raise Error("No common ancestor found")
  3067. # Use the first merge base
  3068. base_commit_id = merge_bases[0]
  3069. # Check if we're trying to merge the same commit
  3070. if head_commit_id == merge_commit_id:
  3071. # Already up to date
  3072. return (None, [])
  3073. # Check for fast-forward
  3074. if base_commit_id == head_commit_id and not no_ff:
  3075. # Fast-forward merge
  3076. r.refs[b"HEAD"] = merge_commit_id
  3077. # Update the working directory
  3078. update_working_tree(r, head_commit.tree, merge_commit.tree)
  3079. return (merge_commit_id, [])
  3080. if base_commit_id == merge_commit_id:
  3081. # Already up to date
  3082. return (None, [])
  3083. # Perform three-way merge
  3084. base_commit = r[base_commit_id]
  3085. merged_tree, conflicts = three_way_merge(
  3086. r.object_store, base_commit, head_commit, merge_commit
  3087. )
  3088. # Add merged tree to object store
  3089. r.object_store.add_object(merged_tree)
  3090. # Update index and working directory
  3091. update_working_tree(r, head_commit.tree, merged_tree.id)
  3092. if conflicts or no_commit:
  3093. # Don't create a commit if there are conflicts or no_commit is True
  3094. return (None, conflicts)
  3095. # Create merge commit
  3096. merge_commit_obj = Commit()
  3097. merge_commit_obj.tree = merged_tree.id
  3098. merge_commit_obj.parents = [head_commit_id, merge_commit_id]
  3099. # Set author/committer
  3100. if author is None:
  3101. author = get_user_identity(r.get_config_stack())
  3102. if committer is None:
  3103. committer = author
  3104. merge_commit_obj.author = author
  3105. merge_commit_obj.committer = committer
  3106. # Set timestamps
  3107. timestamp = int(time.time())
  3108. timezone = 0 # UTC
  3109. merge_commit_obj.author_time = timestamp
  3110. merge_commit_obj.author_timezone = timezone
  3111. merge_commit_obj.commit_time = timestamp
  3112. merge_commit_obj.commit_timezone = timezone
  3113. # Set commit message
  3114. if message is None:
  3115. message = f"Merge commit '{merge_commit_id.decode()[:7]}'\n"
  3116. merge_commit_obj.message = message.encode() if isinstance(message, str) else message
  3117. # Add commit to object store
  3118. r.object_store.add_object(merge_commit_obj)
  3119. # Update HEAD
  3120. r.refs[b"HEAD"] = merge_commit_obj.id
  3121. return (merge_commit_obj.id, [])
  3122. def merge(
  3123. repo,
  3124. committish: Union[str, bytes, Commit, Tag],
  3125. no_commit=False,
  3126. no_ff=False,
  3127. message=None,
  3128. author=None,
  3129. committer=None,
  3130. ):
  3131. """Merge a commit into the current branch.
  3132. Args:
  3133. repo: Repository to merge into
  3134. committish: Commit to merge
  3135. no_commit: If True, do not create a merge commit
  3136. no_ff: If True, force creation of a merge commit
  3137. message: Optional merge commit message
  3138. author: Optional author for merge commit
  3139. committer: Optional committer for merge commit
  3140. Returns:
  3141. Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None
  3142. if no_commit=True or there were conflicts
  3143. Raises:
  3144. Error: If there is no HEAD reference or commit cannot be found
  3145. """
  3146. with open_repo_closing(repo) as r:
  3147. # Parse the commit to merge
  3148. try:
  3149. merge_commit_id = parse_commit(r, committish).id
  3150. except KeyError:
  3151. raise Error(
  3152. f"Cannot find commit '{committish.decode() if isinstance(committish, bytes) else committish}'"
  3153. )
  3154. result = _do_merge(
  3155. r, merge_commit_id, no_commit, no_ff, message, author, committer
  3156. )
  3157. # Trigger auto GC if needed
  3158. from .gc import maybe_auto_gc
  3159. maybe_auto_gc(r)
  3160. return result
  3161. def unpack_objects(pack_path, target="."):
  3162. """Unpack objects from a pack file into the repository.
  3163. Args:
  3164. pack_path: Path to the pack file to unpack
  3165. target: Path to the repository to unpack into
  3166. Returns:
  3167. Number of objects unpacked
  3168. """
  3169. from .pack import Pack
  3170. with open_repo_closing(target) as r:
  3171. pack_basename = os.path.splitext(pack_path)[0]
  3172. with Pack(pack_basename) as pack:
  3173. count = 0
  3174. for unpacked in pack.iter_unpacked():
  3175. obj = unpacked.sha_file()
  3176. r.object_store.add_object(obj)
  3177. count += 1
  3178. return count
  3179. def merge_tree(
  3180. repo,
  3181. base_tree: Optional[Union[str, bytes, Tree, Commit, Tag]],
  3182. our_tree: Union[str, bytes, Tree, Commit, Tag],
  3183. their_tree: Union[str, bytes, Tree, Commit, Tag],
  3184. ):
  3185. """Perform a three-way tree merge without touching the working directory.
  3186. This is similar to git merge-tree, performing a merge at the tree level
  3187. without creating commits or updating any references.
  3188. Args:
  3189. repo: Repository containing the trees
  3190. base_tree: Tree-ish of the common ancestor (or None for no common ancestor)
  3191. our_tree: Tree-ish of our side of the merge
  3192. their_tree: Tree-ish of their side of the merge
  3193. Returns:
  3194. tuple: A tuple of (merged_tree_id, conflicts) where:
  3195. - merged_tree_id is the SHA-1 of the merged tree
  3196. - conflicts is a list of paths (as bytes) that had conflicts
  3197. Raises:
  3198. KeyError: If any of the tree-ish arguments cannot be resolved
  3199. """
  3200. from .merge import Merger
  3201. with open_repo_closing(repo) as r:
  3202. # Resolve tree-ish arguments to actual trees
  3203. base = parse_tree(r, base_tree) if base_tree else None
  3204. ours = parse_tree(r, our_tree)
  3205. theirs = parse_tree(r, their_tree)
  3206. # Perform the merge
  3207. merger = Merger(r.object_store)
  3208. merged_tree, conflicts = merger.merge_trees(base, ours, theirs)
  3209. # Add the merged tree to the object store
  3210. r.object_store.add_object(merged_tree)
  3211. return merged_tree.id, conflicts
  3212. def cherry_pick(
  3213. repo,
  3214. committish: Union[str, bytes, Commit, Tag, None],
  3215. no_commit=False,
  3216. continue_=False,
  3217. abort=False,
  3218. ):
  3219. r"""Cherry-pick a commit onto the current branch.
  3220. Args:
  3221. repo: Repository to cherry-pick into
  3222. committish: Commit to cherry-pick (can be None only when ``continue_`` or abort is True)
  3223. no_commit: If True, do not create a commit after applying changes
  3224. ``continue_``: Continue an in-progress cherry-pick after resolving conflicts
  3225. abort: Abort an in-progress cherry-pick
  3226. Returns:
  3227. The SHA of the newly created commit, or None if no_commit=True or there were conflicts
  3228. Raises:
  3229. Error: If there is no HEAD reference, commit cannot be found, or operation fails
  3230. """
  3231. from .merge import three_way_merge
  3232. # Validate that committish is provided when needed
  3233. if not (continue_ or abort) and committish is None:
  3234. raise ValueError("committish is required when not using --continue or --abort")
  3235. with open_repo_closing(repo) as r:
  3236. # Handle abort
  3237. if abort:
  3238. # Clean up any cherry-pick state
  3239. try:
  3240. os.remove(os.path.join(r.controldir(), "CHERRY_PICK_HEAD"))
  3241. except FileNotFoundError:
  3242. pass
  3243. try:
  3244. os.remove(os.path.join(r.controldir(), "MERGE_MSG"))
  3245. except FileNotFoundError:
  3246. pass
  3247. # Reset index to HEAD
  3248. r.reset_index(r[b"HEAD"].tree)
  3249. return None
  3250. # Handle continue
  3251. if continue_:
  3252. # Check if there's a cherry-pick in progress
  3253. cherry_pick_head_path = os.path.join(r.controldir(), "CHERRY_PICK_HEAD")
  3254. try:
  3255. with open(cherry_pick_head_path, "rb") as f:
  3256. cherry_pick_commit_id = f.read().strip()
  3257. cherry_pick_commit = r[cherry_pick_commit_id]
  3258. except FileNotFoundError:
  3259. raise Error("No cherry-pick in progress")
  3260. # Check for unresolved conflicts
  3261. conflicts = list(r.open_index().conflicts())
  3262. if conflicts:
  3263. raise Error("Unresolved conflicts remain")
  3264. # Create the commit
  3265. tree_id = r.open_index().commit(r.object_store)
  3266. # Read saved message if any
  3267. merge_msg_path = os.path.join(r.controldir(), "MERGE_MSG")
  3268. try:
  3269. with open(merge_msg_path, "rb") as f:
  3270. message = f.read()
  3271. except FileNotFoundError:
  3272. message = cherry_pick_commit.message
  3273. new_commit = r.do_commit(
  3274. message=message,
  3275. tree=tree_id,
  3276. author=cherry_pick_commit.author,
  3277. author_timestamp=cherry_pick_commit.author_time,
  3278. author_timezone=cherry_pick_commit.author_timezone,
  3279. )
  3280. # Clean up state files
  3281. try:
  3282. os.remove(cherry_pick_head_path)
  3283. except FileNotFoundError:
  3284. pass
  3285. try:
  3286. os.remove(merge_msg_path)
  3287. except FileNotFoundError:
  3288. pass
  3289. return new_commit
  3290. # Normal cherry-pick operation
  3291. # Get current HEAD
  3292. try:
  3293. head_commit = r[b"HEAD"]
  3294. except KeyError:
  3295. raise Error("No HEAD reference found")
  3296. # Parse the commit to cherry-pick
  3297. # committish cannot be None here due to validation above
  3298. assert committish is not None
  3299. try:
  3300. cherry_pick_commit = parse_commit(r, committish)
  3301. except KeyError:
  3302. raise Error(
  3303. f"Cannot find commit '{committish.decode() if isinstance(committish, bytes) else committish}'"
  3304. )
  3305. # Check if commit has parents
  3306. if not cherry_pick_commit.parents:
  3307. raise Error("Cannot cherry-pick root commit")
  3308. # Get parent of cherry-pick commit
  3309. parent_commit = r[cherry_pick_commit.parents[0]]
  3310. # Perform three-way merge
  3311. try:
  3312. merged_tree, conflicts = three_way_merge(
  3313. r.object_store, parent_commit, head_commit, cherry_pick_commit
  3314. )
  3315. except Exception as e:
  3316. raise Error(f"Cherry-pick failed: {e}")
  3317. # Add merged tree to object store
  3318. r.object_store.add_object(merged_tree)
  3319. # Update working tree and index
  3320. # Reset index to match merged tree
  3321. r.reset_index(merged_tree.id)
  3322. # Update working tree from the new index
  3323. update_working_tree(r, head_commit.tree, merged_tree.id)
  3324. if conflicts:
  3325. # Save state for later continuation
  3326. with open(os.path.join(r.controldir(), "CHERRY_PICK_HEAD"), "wb") as f:
  3327. f.write(cherry_pick_commit.id + b"\n")
  3328. # Save commit message
  3329. with open(os.path.join(r.controldir(), "MERGE_MSG"), "wb") as f:
  3330. f.write(cherry_pick_commit.message)
  3331. raise Error(
  3332. f"Conflicts in: {', '.join(c.decode('utf-8', 'replace') for c in conflicts)}\n"
  3333. f"Fix conflicts and run 'dulwich cherry-pick --continue'"
  3334. )
  3335. if no_commit:
  3336. return None
  3337. # Create the commit
  3338. new_commit = r.do_commit(
  3339. message=cherry_pick_commit.message,
  3340. tree=merged_tree.id,
  3341. author=cherry_pick_commit.author,
  3342. author_timestamp=cherry_pick_commit.author_time,
  3343. author_timezone=cherry_pick_commit.author_timezone,
  3344. )
  3345. return new_commit
  3346. def revert(
  3347. repo,
  3348. commits: Union[str, bytes, Commit, Tag, list[Union[str, bytes, Commit, Tag]]],
  3349. no_commit=False,
  3350. message=None,
  3351. author=None,
  3352. committer=None,
  3353. ):
  3354. """Revert one or more commits.
  3355. This creates a new commit that undoes the changes introduced by the
  3356. specified commits. Unlike reset, revert creates a new commit that
  3357. preserves history.
  3358. Args:
  3359. repo: Path to repository or repository object
  3360. commits: List of commit-ish (SHA, ref, etc.) to revert, or a single commit-ish
  3361. no_commit: If True, apply changes to index/working tree but don't commit
  3362. message: Optional commit message (default: "Revert <original subject>")
  3363. author: Optional author for revert commit
  3364. committer: Optional committer for revert commit
  3365. Returns:
  3366. SHA1 of the new revert commit, or None if no_commit=True
  3367. Raises:
  3368. Error: If revert fails due to conflicts or other issues
  3369. """
  3370. from .merge import three_way_merge
  3371. # Normalize commits to a list
  3372. if isinstance(commits, (str, bytes, Commit, Tag)):
  3373. commits = [commits]
  3374. with open_repo_closing(repo) as r:
  3375. # Convert string refs to bytes
  3376. commits_to_revert = []
  3377. for commit_ref in commits:
  3378. if isinstance(commit_ref, str):
  3379. commit_ref = commit_ref.encode("utf-8")
  3380. commit = parse_commit(r, commit_ref)
  3381. commits_to_revert.append(commit)
  3382. # Get current HEAD
  3383. try:
  3384. head_commit_id = r.refs[b"HEAD"]
  3385. except KeyError:
  3386. raise Error("No HEAD reference found")
  3387. head_commit = r[head_commit_id]
  3388. current_tree = head_commit.tree
  3389. # Process commits in order
  3390. for commit_to_revert in commits_to_revert:
  3391. # For revert, we want to apply the inverse of the commit
  3392. # This means using the commit's tree as "base" and its parent as "theirs"
  3393. if not commit_to_revert.parents:
  3394. raise Error(
  3395. f"Cannot revert commit {commit_to_revert.id.decode() if isinstance(commit_to_revert.id, bytes) else commit_to_revert.id} - it has no parents"
  3396. )
  3397. # For simplicity, we only handle commits with one parent (no merge commits)
  3398. if len(commit_to_revert.parents) > 1:
  3399. raise Error(
  3400. f"Cannot revert merge commit {commit_to_revert.id.decode() if isinstance(commit_to_revert.id, bytes) else commit_to_revert.id} - not yet implemented"
  3401. )
  3402. parent_commit = r[commit_to_revert.parents[0]]
  3403. # Perform three-way merge:
  3404. # - base: the commit we're reverting (what we want to remove)
  3405. # - ours: current HEAD (what we have now)
  3406. # - theirs: parent of commit being reverted (what we want to go back to)
  3407. merged_tree, conflicts = three_way_merge(
  3408. r.object_store,
  3409. commit_to_revert, # base
  3410. r[head_commit_id], # ours
  3411. parent_commit, # theirs
  3412. )
  3413. if conflicts:
  3414. # Update working tree with conflicts
  3415. update_working_tree(r, current_tree, merged_tree.id)
  3416. conflicted_paths = [c.decode("utf-8", "replace") for c in conflicts]
  3417. raise Error(f"Conflicts while reverting: {', '.join(conflicted_paths)}")
  3418. # Add merged tree to object store
  3419. r.object_store.add_object(merged_tree)
  3420. # Update working tree
  3421. update_working_tree(r, current_tree, merged_tree.id)
  3422. current_tree = merged_tree.id
  3423. if not no_commit:
  3424. # Create revert commit
  3425. revert_commit = Commit()
  3426. revert_commit.tree = merged_tree.id
  3427. revert_commit.parents = [head_commit_id]
  3428. # Set author/committer
  3429. if author is None:
  3430. author = get_user_identity(r.get_config_stack())
  3431. if committer is None:
  3432. committer = author
  3433. revert_commit.author = author
  3434. revert_commit.committer = committer
  3435. # Set timestamps
  3436. timestamp = int(time.time())
  3437. timezone = 0 # UTC
  3438. revert_commit.author_time = timestamp
  3439. revert_commit.author_timezone = timezone
  3440. revert_commit.commit_time = timestamp
  3441. revert_commit.commit_timezone = timezone
  3442. # Set message
  3443. if message is None:
  3444. # Extract original commit subject
  3445. original_message = commit_to_revert.message
  3446. if isinstance(original_message, bytes):
  3447. original_message = original_message.decode("utf-8", "replace")
  3448. subject = original_message.split("\n")[0]
  3449. message = f'Revert "{subject}"\n\nThis reverts commit {commit_to_revert.id.decode("ascii")}.'.encode()
  3450. elif isinstance(message, str):
  3451. message = message.encode("utf-8")
  3452. revert_commit.message = message
  3453. # Add commit to object store
  3454. r.object_store.add_object(revert_commit)
  3455. # Update HEAD
  3456. r.refs[b"HEAD"] = revert_commit.id
  3457. head_commit_id = revert_commit.id
  3458. return head_commit_id if not no_commit else None
  3459. def gc(
  3460. repo,
  3461. auto: bool = False,
  3462. aggressive: bool = False,
  3463. prune: bool = True,
  3464. grace_period: Optional[int] = 1209600, # 2 weeks default
  3465. dry_run: bool = False,
  3466. progress=None,
  3467. ):
  3468. """Run garbage collection on a repository.
  3469. Args:
  3470. repo: Path to the repository or a Repo object
  3471. auto: If True, only run gc if needed
  3472. aggressive: If True, use more aggressive settings
  3473. prune: If True, prune unreachable objects
  3474. grace_period: Grace period in seconds for pruning (default 2 weeks)
  3475. dry_run: If True, only report what would be done
  3476. progress: Optional progress callback
  3477. Returns:
  3478. GCStats object with garbage collection statistics
  3479. """
  3480. from .gc import garbage_collect
  3481. with open_repo_closing(repo) as r:
  3482. return garbage_collect(
  3483. r,
  3484. auto=auto,
  3485. aggressive=aggressive,
  3486. prune=prune,
  3487. grace_period=grace_period,
  3488. dry_run=dry_run,
  3489. progress=progress,
  3490. )
  3491. def prune(
  3492. repo,
  3493. grace_period: Optional[int] = None,
  3494. dry_run: bool = False,
  3495. progress=None,
  3496. ):
  3497. """Prune/clean up a repository's object store.
  3498. This removes temporary files that were left behind by interrupted
  3499. pack operations.
  3500. Args:
  3501. repo: Path to the repository or a Repo object
  3502. grace_period: Grace period in seconds for removing temporary files
  3503. (default 2 weeks)
  3504. dry_run: If True, only report what would be done
  3505. progress: Optional progress callback
  3506. """
  3507. with open_repo_closing(repo) as r:
  3508. if progress:
  3509. progress("Pruning temporary files")
  3510. if not dry_run:
  3511. r.object_store.prune(grace_period=grace_period)
  3512. def count_objects(repo=".", verbose=False) -> CountObjectsResult:
  3513. """Count unpacked objects and their disk usage.
  3514. Args:
  3515. repo: Path to repository or repository object
  3516. verbose: Whether to return verbose information
  3517. Returns:
  3518. CountObjectsResult object with detailed statistics
  3519. """
  3520. with open_repo_closing(repo) as r:
  3521. object_store = r.object_store
  3522. # Count loose objects
  3523. loose_count = 0
  3524. loose_size = 0
  3525. for sha in object_store._iter_loose_objects():
  3526. loose_count += 1
  3527. path = object_store._get_shafile_path(sha)
  3528. try:
  3529. stat_info = os.stat(path)
  3530. # Git uses disk usage, not file size. st_blocks is always in
  3531. # 512-byte blocks per POSIX standard
  3532. if hasattr(stat_info, "st_blocks"):
  3533. # Available on Linux and macOS
  3534. loose_size += stat_info.st_blocks * 512 # type: ignore
  3535. else:
  3536. # Fallback for Windows
  3537. loose_size += stat_info.st_size
  3538. except FileNotFoundError:
  3539. # Object may have been removed between iteration and stat
  3540. pass
  3541. if not verbose:
  3542. return CountObjectsResult(count=loose_count, size=loose_size)
  3543. # Count pack information
  3544. pack_count = len(object_store.packs)
  3545. in_pack_count = 0
  3546. pack_size = 0
  3547. for pack in object_store.packs:
  3548. in_pack_count += len(pack)
  3549. # Get pack file size
  3550. pack_path = pack._data_path
  3551. try:
  3552. pack_size += os.path.getsize(pack_path)
  3553. except FileNotFoundError:
  3554. pass
  3555. # Get index file size
  3556. idx_path = pack._idx_path
  3557. try:
  3558. pack_size += os.path.getsize(idx_path)
  3559. except FileNotFoundError:
  3560. pass
  3561. return CountObjectsResult(
  3562. count=loose_count,
  3563. size=loose_size,
  3564. in_pack=in_pack_count,
  3565. packs=pack_count,
  3566. size_pack=pack_size,
  3567. )
  3568. def rebase(
  3569. repo: Union[Repo, str],
  3570. upstream: Union[bytes, str],
  3571. onto: Optional[Union[bytes, str]] = None,
  3572. branch: Optional[Union[bytes, str]] = None,
  3573. abort: bool = False,
  3574. continue_rebase: bool = False,
  3575. skip: bool = False,
  3576. ) -> list[bytes]:
  3577. """Rebase commits onto another branch.
  3578. Args:
  3579. repo: Repository to rebase in
  3580. upstream: Upstream branch/commit to rebase onto
  3581. onto: Specific commit to rebase onto (defaults to upstream)
  3582. branch: Branch to rebase (defaults to current branch)
  3583. abort: Abort an in-progress rebase
  3584. continue_rebase: Continue an in-progress rebase
  3585. skip: Skip current commit and continue rebase
  3586. Returns:
  3587. List of new commit SHAs created by rebase
  3588. Raises:
  3589. Error: If rebase fails or conflicts occur
  3590. """
  3591. from .rebase import RebaseConflict, RebaseError, Rebaser
  3592. with open_repo_closing(repo) as r:
  3593. rebaser = Rebaser(r)
  3594. if abort:
  3595. try:
  3596. rebaser.abort()
  3597. return []
  3598. except RebaseError as e:
  3599. raise Error(str(e))
  3600. if continue_rebase:
  3601. try:
  3602. result = rebaser.continue_()
  3603. if result is None:
  3604. # Rebase complete
  3605. return []
  3606. elif isinstance(result, tuple) and result[1]:
  3607. # Still have conflicts
  3608. raise Error(
  3609. f"Conflicts in: {', '.join(f.decode('utf-8', 'replace') for f in result[1])}"
  3610. )
  3611. except RebaseError as e:
  3612. raise Error(str(e))
  3613. # Convert string refs to bytes
  3614. if isinstance(upstream, str):
  3615. upstream = upstream.encode("utf-8")
  3616. if isinstance(onto, str):
  3617. onto = onto.encode("utf-8") if onto else None
  3618. if isinstance(branch, str):
  3619. branch = branch.encode("utf-8") if branch else None
  3620. try:
  3621. # Start rebase
  3622. rebaser.start(upstream, onto, branch)
  3623. # Continue rebase automatically
  3624. result = rebaser.continue_()
  3625. if result is not None:
  3626. # Conflicts
  3627. raise RebaseConflict(result[1])
  3628. # Return the SHAs of the rebased commits
  3629. return [c.id for c in rebaser._done]
  3630. except RebaseConflict as e:
  3631. raise Error(str(e))
  3632. except RebaseError as e:
  3633. raise Error(str(e))
  3634. def annotate(repo, path, committish: Optional[Union[str, bytes, Commit, Tag]] = None):
  3635. """Annotate the history of a file.
  3636. :param repo: Path to the repository
  3637. :param path: Path to annotate
  3638. :param committish: Commit id to find path in
  3639. :return: List of ((Commit, TreeChange), line) tuples
  3640. """
  3641. if committish is None:
  3642. committish = "HEAD"
  3643. from dulwich.annotate import annotate_lines
  3644. with open_repo_closing(repo) as r:
  3645. commit_id = parse_commit(r, committish).id
  3646. # Ensure path is bytes
  3647. if isinstance(path, str):
  3648. path = path.encode()
  3649. return annotate_lines(r.object_store, commit_id, path)
  3650. blame = annotate
  3651. def filter_branch(
  3652. repo=".",
  3653. branch="HEAD",
  3654. *,
  3655. filter_fn=None,
  3656. filter_author=None,
  3657. filter_committer=None,
  3658. filter_message=None,
  3659. tree_filter=None,
  3660. index_filter=None,
  3661. parent_filter=None,
  3662. commit_filter=None,
  3663. subdirectory_filter=None,
  3664. prune_empty=False,
  3665. tag_name_filter=None,
  3666. force=False,
  3667. keep_original=True,
  3668. refs=None,
  3669. ):
  3670. """Rewrite branch history by creating new commits with filtered properties.
  3671. This is similar to git filter-branch, allowing you to rewrite commit
  3672. history by modifying trees, parents, author, committer, or commit messages.
  3673. Args:
  3674. repo: Path to repository
  3675. branch: Branch to rewrite (defaults to HEAD)
  3676. filter_fn: Optional callable that takes a Commit object and returns
  3677. a dict of updated fields (author, committer, message, etc.)
  3678. filter_author: Optional callable that takes author bytes and returns
  3679. updated author bytes or None to keep unchanged
  3680. filter_committer: Optional callable that takes committer bytes and returns
  3681. updated committer bytes or None to keep unchanged
  3682. filter_message: Optional callable that takes commit message bytes
  3683. and returns updated message bytes
  3684. tree_filter: Optional callable that takes (tree_sha, temp_dir) and returns
  3685. new tree SHA after modifying working directory
  3686. index_filter: Optional callable that takes (tree_sha, temp_index_path) and
  3687. returns new tree SHA after modifying index
  3688. parent_filter: Optional callable that takes parent list and returns
  3689. modified parent list
  3690. commit_filter: Optional callable that takes (Commit, tree_sha) and returns
  3691. new commit SHA or None to skip commit
  3692. subdirectory_filter: Optional subdirectory path to extract as new root
  3693. prune_empty: Whether to prune commits that become empty
  3694. tag_name_filter: Optional callable to rename tags
  3695. force: Force operation even if branch has been filtered before
  3696. keep_original: Keep original refs under refs/original/
  3697. refs: List of refs to rewrite (defaults to [branch])
  3698. Returns:
  3699. Dict mapping old commit SHAs to new commit SHAs
  3700. Raises:
  3701. Error: If branch is already filtered and force is False
  3702. """
  3703. from .filter_branch import CommitFilter, filter_refs
  3704. with open_repo_closing(repo) as r:
  3705. # Parse branch/committish
  3706. if isinstance(branch, str):
  3707. branch = branch.encode()
  3708. # Determine which refs to process
  3709. if refs is None:
  3710. if branch == b"HEAD":
  3711. # Resolve HEAD to actual branch
  3712. try:
  3713. resolved = r.refs.follow(b"HEAD")
  3714. if resolved and resolved[0]:
  3715. # resolved is a list of (refname, sha) tuples
  3716. resolved_ref = resolved[0][-1]
  3717. if resolved_ref and resolved_ref != b"HEAD":
  3718. refs = [resolved_ref]
  3719. else:
  3720. # HEAD points directly to a commit
  3721. refs = [b"HEAD"]
  3722. else:
  3723. refs = [b"HEAD"]
  3724. except SymrefLoop:
  3725. refs = [b"HEAD"]
  3726. else:
  3727. # Convert branch name to full ref if needed
  3728. if not branch.startswith(b"refs/"):
  3729. branch = b"refs/heads/" + branch
  3730. refs = [branch]
  3731. # Convert subdirectory filter to bytes if needed
  3732. if subdirectory_filter and isinstance(subdirectory_filter, str):
  3733. subdirectory_filter = subdirectory_filter.encode()
  3734. # Create commit filter
  3735. commit_filter = CommitFilter(
  3736. r.object_store,
  3737. filter_fn=filter_fn,
  3738. filter_author=filter_author,
  3739. filter_committer=filter_committer,
  3740. filter_message=filter_message,
  3741. tree_filter=tree_filter,
  3742. index_filter=index_filter,
  3743. parent_filter=parent_filter,
  3744. commit_filter=commit_filter,
  3745. subdirectory_filter=subdirectory_filter,
  3746. prune_empty=prune_empty,
  3747. tag_name_filter=tag_name_filter,
  3748. )
  3749. # Tag callback for renaming tags
  3750. def rename_tag(old_ref, new_ref):
  3751. # Copy tag to new name
  3752. r.refs[new_ref] = r.refs[old_ref]
  3753. # Delete old tag
  3754. del r.refs[old_ref]
  3755. # Filter refs
  3756. try:
  3757. return filter_refs(
  3758. r.refs,
  3759. r.object_store,
  3760. refs,
  3761. commit_filter,
  3762. keep_original=keep_original,
  3763. force=force,
  3764. tag_callback=rename_tag if tag_name_filter else None,
  3765. )
  3766. except ValueError as e:
  3767. raise Error(str(e)) from e
  3768. def format_patch(
  3769. repo=".",
  3770. committish=None,
  3771. outstream=sys.stdout,
  3772. outdir=None,
  3773. n=1,
  3774. stdout=False,
  3775. version=None,
  3776. ) -> list[str]:
  3777. """Generate patches suitable for git am.
  3778. Args:
  3779. repo: Path to repository
  3780. committish: Commit-ish or commit range to generate patches for.
  3781. Can be a single commit id, or a tuple of (start, end) commit ids
  3782. for a range. If None, formats the last n commits from HEAD.
  3783. outstream: Stream to write to if stdout=True
  3784. outdir: Directory to write patch files to (default: current directory)
  3785. n: Number of patches to generate if committish is None
  3786. stdout: Write patches to stdout instead of files
  3787. version: Version string to include in patches (default: Dulwich version)
  3788. Returns:
  3789. List of patch filenames that were created (empty if stdout=True)
  3790. """
  3791. if outdir is None:
  3792. outdir = "."
  3793. filenames = []
  3794. with open_repo_closing(repo) as r:
  3795. # Determine which commits to format
  3796. commits_to_format = []
  3797. if committish is None:
  3798. # Get the last n commits from HEAD
  3799. try:
  3800. walker = r.get_walker()
  3801. for entry in walker:
  3802. commits_to_format.append(entry.commit)
  3803. if len(commits_to_format) >= n:
  3804. break
  3805. commits_to_format.reverse()
  3806. except KeyError:
  3807. # No HEAD or empty repository
  3808. pass
  3809. elif isinstance(committish, tuple):
  3810. # Handle commit range (start, end)
  3811. start_id, end_id = committish
  3812. # Walk from end back to start
  3813. walker = r.get_walker(include=[end_id], exclude=[start_id])
  3814. for entry in walker:
  3815. commits_to_format.append(entry.commit)
  3816. commits_to_format.reverse()
  3817. else:
  3818. # Single commit
  3819. commit = r.object_store[committish]
  3820. commits_to_format.append(commit)
  3821. # Generate patches
  3822. total = len(commits_to_format)
  3823. for i, commit in enumerate(commits_to_format, 1):
  3824. # Get the parent
  3825. if commit.parents:
  3826. parent_id = commit.parents[0]
  3827. parent = r.object_store[parent_id]
  3828. else:
  3829. parent = None
  3830. # Generate the diff
  3831. from io import BytesIO
  3832. diff_content = BytesIO()
  3833. if parent:
  3834. write_tree_diff(
  3835. diff_content,
  3836. r.object_store,
  3837. parent.tree,
  3838. commit.tree,
  3839. )
  3840. else:
  3841. # Initial commit - diff against empty tree
  3842. write_tree_diff(
  3843. diff_content,
  3844. r.object_store,
  3845. None,
  3846. commit.tree,
  3847. )
  3848. # Generate patch with commit metadata
  3849. if stdout:
  3850. write_commit_patch(
  3851. outstream.buffer if hasattr(outstream, "buffer") else outstream,
  3852. commit,
  3853. diff_content.getvalue(),
  3854. (i, total),
  3855. version=version,
  3856. )
  3857. else:
  3858. # Generate filename
  3859. from .patch import get_summary
  3860. summary = get_summary(commit)
  3861. filename = os.path.join(outdir, f"{i:04d}-{summary}.patch")
  3862. with open(filename, "wb") as f:
  3863. write_commit_patch(
  3864. f,
  3865. commit,
  3866. diff_content.getvalue(),
  3867. (i, total),
  3868. version=version,
  3869. )
  3870. filenames.append(filename)
  3871. return filenames
  3872. def bisect_start(
  3873. repo=".",
  3874. bad: Optional[Union[str, bytes, Commit, Tag]] = None,
  3875. good: Optional[
  3876. Union[str, bytes, Commit, Tag, list[Union[str, bytes, Commit, Tag]]]
  3877. ] = None,
  3878. paths=None,
  3879. no_checkout=False,
  3880. term_bad="bad",
  3881. term_good="good",
  3882. ):
  3883. """Start a new bisect session.
  3884. Args:
  3885. repo: Path to repository or a Repo object
  3886. bad: The bad commit (defaults to HEAD)
  3887. good: List of good commits or a single good commit
  3888. paths: Optional paths to limit bisect to
  3889. no_checkout: If True, don't checkout commits during bisect
  3890. term_bad: Term to use for bad commits (default: "bad")
  3891. term_good: Term to use for good commits (default: "good")
  3892. """
  3893. with open_repo_closing(repo) as r:
  3894. state = BisectState(r)
  3895. # Convert single good commit to list
  3896. if good is not None and not isinstance(good, list):
  3897. good = [good]
  3898. # Parse commits
  3899. bad_sha = parse_commit(r, bad).id if bad else None
  3900. good_shas = [parse_commit(r, g).id for g in good] if good else None
  3901. state.start(bad_sha, good_shas, paths, no_checkout, term_bad, term_good)
  3902. # Return the next commit to test if we have both good and bad
  3903. if bad_sha and good_shas:
  3904. next_sha = state._find_next_commit()
  3905. if next_sha and not no_checkout:
  3906. # Checkout the next commit
  3907. old_tree = r[r.head()].tree if r.head() else None
  3908. r.refs[b"HEAD"] = next_sha
  3909. commit = r[next_sha]
  3910. update_working_tree(r, old_tree, commit.tree)
  3911. return next_sha
  3912. def bisect_bad(repo=".", rev: Optional[Union[str, bytes, Commit, Tag]] = None):
  3913. """Mark a commit as bad.
  3914. Args:
  3915. repo: Path to repository or a Repo object
  3916. rev: Commit to mark as bad (defaults to HEAD)
  3917. Returns:
  3918. The SHA of the next commit to test, or None if bisect is complete
  3919. """
  3920. with open_repo_closing(repo) as r:
  3921. state = BisectState(r)
  3922. rev_sha = parse_commit(r, rev).id if rev else None
  3923. next_sha = state.mark_bad(rev_sha)
  3924. if next_sha:
  3925. # Checkout the next commit
  3926. old_tree = r[r.head()].tree if r.head() else None
  3927. r.refs[b"HEAD"] = next_sha
  3928. commit = r[next_sha]
  3929. update_working_tree(r, old_tree, commit.tree)
  3930. return next_sha
  3931. def bisect_good(repo=".", rev: Optional[Union[str, bytes, Commit, Tag]] = None):
  3932. """Mark a commit as good.
  3933. Args:
  3934. repo: Path to repository or a Repo object
  3935. rev: Commit to mark as good (defaults to HEAD)
  3936. Returns:
  3937. The SHA of the next commit to test, or None if bisect is complete
  3938. """
  3939. with open_repo_closing(repo) as r:
  3940. state = BisectState(r)
  3941. rev_sha = parse_commit(r, rev).id if rev else None
  3942. next_sha = state.mark_good(rev_sha)
  3943. if next_sha:
  3944. # Checkout the next commit
  3945. old_tree = r[r.head()].tree if r.head() else None
  3946. r.refs[b"HEAD"] = next_sha
  3947. commit = r[next_sha]
  3948. update_working_tree(r, old_tree, commit.tree)
  3949. return next_sha
  3950. def bisect_skip(
  3951. repo=".",
  3952. revs: Optional[
  3953. Union[str, bytes, Commit, Tag, list[Union[str, bytes, Commit, Tag]]]
  3954. ] = None,
  3955. ):
  3956. """Skip one or more commits.
  3957. Args:
  3958. repo: Path to repository or a Repo object
  3959. revs: List of commits to skip (defaults to [HEAD])
  3960. Returns:
  3961. The SHA of the next commit to test, or None if bisect is complete
  3962. """
  3963. with open_repo_closing(repo) as r:
  3964. state = BisectState(r)
  3965. if revs is None:
  3966. rev_shas = None
  3967. else:
  3968. # Convert single rev to list
  3969. if not isinstance(revs, list):
  3970. revs = [revs]
  3971. rev_shas = [parse_commit(r, rev).id for rev in revs]
  3972. next_sha = state.skip(rev_shas)
  3973. if next_sha:
  3974. # Checkout the next commit
  3975. old_tree = r[r.head()].tree if r.head() else None
  3976. r.refs[b"HEAD"] = next_sha
  3977. commit = r[next_sha]
  3978. update_working_tree(r, old_tree, commit.tree)
  3979. return next_sha
  3980. def bisect_reset(repo=".", commit: Optional[Union[str, bytes, Commit, Tag]] = None):
  3981. """Reset bisect state and return to original branch/commit.
  3982. Args:
  3983. repo: Path to repository or a Repo object
  3984. commit: Optional commit to reset to (defaults to original branch/commit)
  3985. """
  3986. with open_repo_closing(repo) as r:
  3987. state = BisectState(r)
  3988. # Get old tree before reset
  3989. try:
  3990. old_tree = r[r.head()].tree
  3991. except KeyError:
  3992. old_tree = None
  3993. commit_sha = parse_commit(r, commit).id if commit else None
  3994. state.reset(commit_sha)
  3995. # Update working tree to new HEAD
  3996. try:
  3997. new_head = r.head()
  3998. if new_head:
  3999. new_commit = r[new_head]
  4000. update_working_tree(r, old_tree, new_commit.tree)
  4001. except KeyError:
  4002. # No HEAD after reset
  4003. pass
  4004. def bisect_log(repo="."):
  4005. """Get the bisect log.
  4006. Args:
  4007. repo: Path to repository or a Repo object
  4008. Returns:
  4009. The bisect log as a string
  4010. """
  4011. with open_repo_closing(repo) as r:
  4012. state = BisectState(r)
  4013. return state.get_log()
  4014. def bisect_replay(repo, log_file):
  4015. """Replay a bisect log.
  4016. Args:
  4017. repo: Path to repository or a Repo object
  4018. log_file: Path to the log file or file-like object
  4019. """
  4020. with open_repo_closing(repo) as r:
  4021. state = BisectState(r)
  4022. if isinstance(log_file, str):
  4023. with open(log_file) as f:
  4024. log_content = f.read()
  4025. else:
  4026. log_content = log_file.read()
  4027. state.replay(log_content)
  4028. def reflog(repo=".", ref=b"HEAD", all=False):
  4029. """Show reflog entries for a reference or all references.
  4030. Args:
  4031. repo: Path to repository or a Repo object
  4032. ref: Reference name (defaults to HEAD)
  4033. all: If True, show reflogs for all refs (ignores ref parameter)
  4034. Yields:
  4035. If all=False: ReflogEntry objects
  4036. If all=True: Tuples of (ref_name, ReflogEntry) for all refs with reflogs
  4037. """
  4038. import os
  4039. from .reflog import iter_reflogs
  4040. if isinstance(ref, str):
  4041. ref = ref.encode("utf-8")
  4042. with open_repo_closing(repo) as r:
  4043. if not all:
  4044. yield from r.read_reflog(ref)
  4045. else:
  4046. logs_dir = os.path.join(r.controldir(), "logs")
  4047. # Use iter_reflogs to discover all reflogs
  4048. for ref_bytes in iter_reflogs(logs_dir):
  4049. # Read the reflog entries for this ref
  4050. for entry in r.read_reflog(ref_bytes):
  4051. yield (ref_bytes, entry)