porcelain.py 260 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669
  1. # e 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 published 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. * var
  64. * write_commit_graph
  65. * status
  66. * shortlog
  67. * symbolic_ref
  68. * worktree{_add,_list,_remove,_prune,_lock,_unlock,_move}
  69. These functions are meant to behave similarly to the git subcommands.
  70. Differences in behaviour are considered bugs.
  71. Note: one of the consequences of this is that paths tend to be
  72. interpreted relative to the current working directory rather than relative
  73. to the repository root.
  74. Functions should generally accept both unicode strings and bytestrings
  75. """
  76. import datetime
  77. import fnmatch
  78. import logging
  79. import os
  80. import posixpath
  81. import stat
  82. import sys
  83. import time
  84. from collections import namedtuple
  85. from collections.abc import Iterable, Iterator, Sequence
  86. from collections.abc import Set as AbstractSet
  87. from contextlib import AbstractContextManager, closing, contextmanager
  88. from dataclasses import dataclass
  89. from io import BytesIO, RawIOBase
  90. from pathlib import Path
  91. from typing import (
  92. IO,
  93. TYPE_CHECKING,
  94. Any,
  95. BinaryIO,
  96. Callable,
  97. Optional,
  98. TextIO,
  99. TypeVar,
  100. Union,
  101. cast,
  102. overload,
  103. )
  104. if sys.version_info >= (3, 12):
  105. from collections.abc import Buffer
  106. from typing import override
  107. else:
  108. from typing_extensions import Buffer, override
  109. if TYPE_CHECKING:
  110. from .filter_branch import CommitData
  111. from .gc import GCStats
  112. from . import replace_me
  113. from .archive import tar_stream
  114. from .bisect import BisectState
  115. from .client import (
  116. FetchPackResult,
  117. LsRemoteResult,
  118. SendPackResult,
  119. get_transport_and_path,
  120. )
  121. from .config import Config, ConfigFile, StackedConfig, read_submodules
  122. from .diff_tree import (
  123. CHANGE_ADD,
  124. CHANGE_COPY,
  125. CHANGE_DELETE,
  126. CHANGE_MODIFY,
  127. CHANGE_RENAME,
  128. RENAME_CHANGE_TYPES,
  129. TreeChange,
  130. tree_changes,
  131. )
  132. from .errors import SendPackError
  133. from .graph import can_fast_forward
  134. from .ignore import IgnoreFilterManager
  135. from .index import (
  136. ConflictedIndexEntry,
  137. Index,
  138. IndexEntry,
  139. _fs_to_tree_path,
  140. blob_from_path_and_stat,
  141. build_file_from_blob,
  142. build_index_from_tree,
  143. get_unstaged_changes,
  144. index_entry_from_stat,
  145. symlink,
  146. update_working_tree,
  147. validate_path_element_default,
  148. validate_path_element_hfs,
  149. validate_path_element_ntfs,
  150. )
  151. from .object_store import BaseObjectStore, tree_lookup_path
  152. from .objects import (
  153. Blob,
  154. Commit,
  155. Tag,
  156. Tree,
  157. TreeEntry,
  158. format_timezone,
  159. parse_timezone,
  160. pretty_format_tree_entry,
  161. )
  162. from .objectspec import (
  163. parse_commit,
  164. parse_object,
  165. parse_ref,
  166. parse_reftuples,
  167. parse_tree,
  168. )
  169. from .pack import UnpackedObject, write_pack_from_container, write_pack_index
  170. from .patch import (
  171. get_summary,
  172. write_commit_patch,
  173. write_object_diff,
  174. write_tree_diff,
  175. )
  176. from .protocol import ZERO_SHA, Protocol
  177. from .refs import (
  178. LOCAL_BRANCH_PREFIX,
  179. LOCAL_NOTES_PREFIX,
  180. LOCAL_REMOTE_PREFIX,
  181. LOCAL_TAG_PREFIX,
  182. Ref,
  183. SymrefLoop,
  184. _import_remote_refs,
  185. filter_ref_prefix,
  186. shorten_ref_name,
  187. )
  188. from .repo import BaseRepo, Repo, get_user_identity
  189. from .server import (
  190. FileSystemBackend,
  191. ReceivePackHandler,
  192. TCPGitServer,
  193. UploadPackHandler,
  194. )
  195. from .server import update_server_info as server_update_server_info
  196. from .sparse_patterns import (
  197. SparseCheckoutConflictError,
  198. apply_included_paths,
  199. determine_included_paths,
  200. )
  201. # Module level tuple definition for status output
  202. GitStatus = namedtuple("GitStatus", "staged unstaged untracked")
  203. # TypeVar for preserving BaseRepo subclass types
  204. T = TypeVar("T", bound="BaseRepo")
  205. # Type alias for common repository parameter pattern
  206. RepoPath = Union[str, os.PathLike[str], Repo]
  207. @dataclass
  208. class CountObjectsResult:
  209. """Result of counting objects in a repository.
  210. Attributes:
  211. count: Number of loose objects
  212. size: Total size of loose objects in bytes
  213. in_pack: Number of objects in pack files
  214. packs: Number of pack files
  215. size_pack: Total size of pack files in bytes
  216. """
  217. count: int
  218. size: int
  219. in_pack: Optional[int] = None
  220. packs: Optional[int] = None
  221. size_pack: Optional[int] = None
  222. class NoneStream(RawIOBase):
  223. """Fallback if stdout or stderr are unavailable, does nothing."""
  224. def read(self, size: int = -1) -> None:
  225. """Read from stream (returns None as this is a null stream)."""
  226. return None
  227. def readall(self) -> bytes:
  228. """Read all bytes (returns empty bytes).
  229. Returns:
  230. Empty bytes object
  231. """
  232. return b""
  233. @override
  234. def readinto(self, b: Buffer) -> Optional[int]:
  235. return 0
  236. @override
  237. def write(self, b: Buffer) -> Optional[int]:
  238. # All Buffer implementations (bytes, bytearray, memoryview) support len()
  239. return len(b) if b else 0 # type: ignore[arg-type]
  240. default_bytes_out_stream: BinaryIO = cast(
  241. BinaryIO, getattr(sys.stdout, "buffer", None) or NoneStream()
  242. )
  243. default_bytes_err_stream: BinaryIO = cast(
  244. BinaryIO, getattr(sys.stderr, "buffer", None) or NoneStream()
  245. )
  246. DEFAULT_ENCODING = "utf-8"
  247. class Error(Exception):
  248. """Porcelain-based error."""
  249. def __init__(self, msg: str) -> None:
  250. """Initialize Error with message."""
  251. super().__init__(msg)
  252. class RemoteExists(Error):
  253. """Raised when the remote already exists."""
  254. class TimezoneFormatError(Error):
  255. """Raised when the timezone cannot be determined from a given string."""
  256. class CheckoutError(Error):
  257. """Indicates that a checkout cannot be performed."""
  258. def parse_timezone_format(tz_str: str) -> int:
  259. """Parse given string and attempt to return a timezone offset.
  260. Different formats are considered in the following order:
  261. - Git internal format: <unix timestamp> <timezone offset>
  262. - RFC 2822: e.g. Mon, 20 Nov 1995 19:12:08 -0500
  263. - ISO 8601: e.g. 1995-11-20T19:12:08-0500
  264. Args:
  265. tz_str: datetime string
  266. Returns: Timezone offset as integer
  267. Raises:
  268. TimezoneFormatError: if timezone information cannot be extracted
  269. """
  270. import re
  271. # Git internal format
  272. internal_format_pattern = re.compile("^[0-9]+ [+-][0-9]{,4}$")
  273. if re.match(internal_format_pattern, tz_str):
  274. try:
  275. tz_internal = parse_timezone(tz_str.split(" ")[1].encode(DEFAULT_ENCODING))
  276. return tz_internal[0]
  277. except ValueError:
  278. pass
  279. # RFC 2822
  280. import email.utils
  281. rfc_2822 = email.utils.parsedate_tz(tz_str)
  282. if rfc_2822 and rfc_2822[9] is not None:
  283. return rfc_2822[9]
  284. # ISO 8601
  285. # Supported offsets:
  286. # sHHMM, sHH:MM, sHH
  287. iso_8601_pattern = re.compile(
  288. "[0-9] ?([+-])([0-9]{2})(?::(?=[0-9]{2}))?([0-9]{2})?$"
  289. )
  290. match = re.search(iso_8601_pattern, tz_str)
  291. total_secs = 0
  292. if match:
  293. sign, hours, minutes = match.groups()
  294. total_secs += int(hours) * 3600
  295. if minutes:
  296. total_secs += int(minutes) * 60
  297. total_secs = -total_secs if sign == "-" else total_secs
  298. return total_secs
  299. # YYYY.MM.DD, MM/DD/YYYY, DD.MM.YYYY contain no timezone information
  300. raise TimezoneFormatError(tz_str)
  301. def get_user_timezones() -> tuple[int, int]:
  302. """Retrieve local timezone as described in git documentation.
  303. https://raw.githubusercontent.com/git/git/v2.3.0/Documentation/date-formats.txt
  304. Returns: A tuple containing author timezone, committer timezone.
  305. """
  306. local_timezone = time.localtime().tm_gmtoff
  307. if os.environ.get("GIT_AUTHOR_DATE"):
  308. author_timezone = parse_timezone_format(os.environ["GIT_AUTHOR_DATE"])
  309. else:
  310. author_timezone = local_timezone
  311. if os.environ.get("GIT_COMMITTER_DATE"):
  312. commit_timezone = parse_timezone_format(os.environ["GIT_COMMITTER_DATE"])
  313. else:
  314. commit_timezone = local_timezone
  315. return author_timezone, commit_timezone
  316. @overload
  317. def open_repo(path_or_repo: T) -> AbstractContextManager[T]: ...
  318. @overload
  319. def open_repo(
  320. path_or_repo: Union[str, os.PathLike[str]],
  321. ) -> AbstractContextManager[Repo]: ...
  322. def open_repo(
  323. path_or_repo: Union[str, os.PathLike[str], T],
  324. ) -> AbstractContextManager[Union[T, Repo]]:
  325. """Open an argument that can be a repository or a path for a repository."""
  326. if isinstance(path_or_repo, BaseRepo):
  327. return _noop_context_manager(path_or_repo)
  328. return Repo(path_or_repo)
  329. @contextmanager
  330. def _noop_context_manager(obj: T) -> Iterator[T]:
  331. """Context manager that has the same api as closing but does nothing."""
  332. yield obj
  333. @overload
  334. def open_repo_closing(path_or_repo: T) -> AbstractContextManager[T]: ...
  335. @overload
  336. def open_repo_closing(
  337. path_or_repo: Union[str, bytes, os.PathLike[str]],
  338. ) -> AbstractContextManager[Repo]: ...
  339. def open_repo_closing(
  340. path_or_repo: Union[str, bytes, os.PathLike[str], T],
  341. ) -> AbstractContextManager[Union[T, Repo]]:
  342. """Open an argument that can be a repository or a path for a repository.
  343. returns a context manager that will close the repo on exit if the argument
  344. is a path, else does nothing if the argument is a repo.
  345. """
  346. if isinstance(path_or_repo, BaseRepo):
  347. return _noop_context_manager(path_or_repo)
  348. return closing(Repo(path_or_repo))
  349. def path_to_tree_path(
  350. repopath: Union[str, bytes, os.PathLike[str]],
  351. path: Union[str, bytes, os.PathLike[str]],
  352. tree_encoding: str = DEFAULT_ENCODING,
  353. ) -> bytes:
  354. """Convert a path to a path usable in an index, e.g. bytes and relative to the repository root.
  355. Args:
  356. repopath: Repository path, absolute or relative to the cwd
  357. path: A path, absolute or relative to the cwd
  358. tree_encoding: Encoding to use for tree paths
  359. Returns: A path formatted for use in e.g. an index
  360. """
  361. # Resolve might returns a relative path on Windows
  362. # https://bugs.python.org/issue38671
  363. if sys.platform == "win32":
  364. path = os.path.abspath(path)
  365. # Convert bytes paths to str for Path
  366. if isinstance(path, bytes):
  367. path = os.fsdecode(path)
  368. path = Path(path)
  369. resolved_path = path.resolve()
  370. # Resolve and abspath seems to behave differently regarding symlinks,
  371. # as we are doing abspath on the file path, we need to do the same on
  372. # the repo path or they might not match
  373. if sys.platform == "win32":
  374. repopath = os.path.abspath(repopath)
  375. # Convert bytes paths to str for Path
  376. if isinstance(repopath, bytes):
  377. repopath = os.fsdecode(repopath)
  378. repopath = Path(repopath).resolve()
  379. try:
  380. relpath = resolved_path.relative_to(repopath)
  381. except ValueError:
  382. # If path is a symlink that points to a file outside the repo, we
  383. # want the relpath for the link itself, not the resolved target
  384. if path.is_symlink():
  385. parent = path.parent.resolve()
  386. relpath = (parent / path.name).relative_to(repopath)
  387. else:
  388. raise
  389. if sys.platform == "win32":
  390. return str(relpath).replace(os.path.sep, "/").encode(tree_encoding)
  391. else:
  392. return bytes(relpath)
  393. class DivergedBranches(Error):
  394. """Branches have diverged and fast-forward is not possible."""
  395. def __init__(self, current_sha: bytes, new_sha: bytes) -> None:
  396. """Initialize DivergedBranches error with current and new SHA values."""
  397. self.current_sha = current_sha
  398. self.new_sha = new_sha
  399. def check_diverged(repo: BaseRepo, current_sha: bytes, new_sha: bytes) -> None:
  400. """Check if updating to a sha can be done with fast forwarding.
  401. Args:
  402. repo: Repository object
  403. current_sha: Current head sha
  404. new_sha: New head sha
  405. """
  406. try:
  407. can = can_fast_forward(repo, current_sha, new_sha)
  408. except KeyError:
  409. can = False
  410. if not can:
  411. raise DivergedBranches(current_sha, new_sha)
  412. def archive(
  413. repo: Union[str, BaseRepo],
  414. committish: Optional[Union[str, bytes, Commit, Tag]] = None,
  415. outstream: Union[BinaryIO, RawIOBase] = default_bytes_out_stream,
  416. errstream: Union[BinaryIO, RawIOBase] = default_bytes_err_stream,
  417. ) -> None:
  418. """Create an archive.
  419. Args:
  420. repo: Path of repository for which to generate an archive.
  421. committish: Commit SHA1 or ref to use
  422. outstream: Output stream (defaults to stdout)
  423. errstream: Error stream (defaults to stderr)
  424. """
  425. if committish is None:
  426. committish = "HEAD"
  427. with open_repo_closing(repo) as repo_obj:
  428. c = parse_commit(repo_obj, committish)
  429. tree = repo_obj.object_store[c.tree]
  430. assert isinstance(tree, Tree)
  431. for chunk in tar_stream(repo_obj.object_store, tree, c.commit_time):
  432. outstream.write(chunk)
  433. def update_server_info(repo: RepoPath = ".") -> None:
  434. """Update server info files for a repository.
  435. Args:
  436. repo: path to the repository
  437. """
  438. with open_repo_closing(repo) as r:
  439. server_update_server_info(r)
  440. def write_commit_graph(repo: RepoPath = ".", reachable: bool = True) -> None:
  441. """Write a commit graph file for a repository.
  442. Args:
  443. repo: path to the repository or a Repo object
  444. reachable: if True, include all commits reachable from refs.
  445. if False, only include direct ref targets.
  446. """
  447. with open_repo_closing(repo) as r:
  448. # Get all refs
  449. refs = list(r.refs.as_dict().values())
  450. if refs:
  451. r.object_store.write_commit_graph(refs, reachable=reachable)
  452. def symbolic_ref(
  453. repo: RepoPath, ref_name: Union[str, bytes], force: bool = False
  454. ) -> None:
  455. """Set git symbolic ref into HEAD.
  456. Args:
  457. repo: path to the repository
  458. ref_name: short name of the new ref
  459. force: force settings without checking if it exists in refs/heads
  460. """
  461. with open_repo_closing(repo) as repo_obj:
  462. ref_path = _make_branch_ref(ref_name)
  463. if not force and ref_path not in repo_obj.refs.keys():
  464. ref_name_str = (
  465. ref_name.decode("utf-8", "replace")
  466. if isinstance(ref_name, bytes)
  467. else ref_name
  468. )
  469. raise Error(f"fatal: ref `{ref_name_str}` is not a ref")
  470. repo_obj.refs.set_symbolic_ref(b"HEAD", ref_path)
  471. def pack_refs(repo: RepoPath, all: bool = False) -> None:
  472. """Pack loose references into packed-refs file."""
  473. with open_repo_closing(repo) as repo_obj:
  474. repo_obj.refs.pack_refs(all=all)
  475. def _get_variables(repo: RepoPath = ".") -> dict[str, str]:
  476. """Internal function to get all Git logical variables.
  477. Args:
  478. repo: Path to the repository
  479. Returns:
  480. A dictionary of all logical variables with values
  481. """
  482. from .repo import get_user_identity
  483. with open_repo_closing(repo) as repo_obj:
  484. config = repo_obj.get_config_stack()
  485. # Define callbacks for each logical variable
  486. def get_author_ident() -> Optional[str]:
  487. """Get GIT_AUTHOR_IDENT."""
  488. try:
  489. author_identity = get_user_identity(config, kind="AUTHOR")
  490. author_tz, _ = get_user_timezones()
  491. timestamp = int(time.time())
  492. return f"{author_identity.decode('utf-8', 'replace')} {timestamp} {author_tz:+05d}"
  493. except Exception:
  494. return None
  495. def get_committer_ident() -> Optional[str]:
  496. """Get GIT_COMMITTER_IDENT."""
  497. try:
  498. committer_identity = get_user_identity(config, kind="COMMITTER")
  499. _, committer_tz = get_user_timezones()
  500. timestamp = int(time.time())
  501. return f"{committer_identity.decode('utf-8', 'replace')} {timestamp} {committer_tz:+05d}"
  502. except Exception:
  503. return None
  504. def get_editor() -> Optional[str]:
  505. """Get GIT_EDITOR."""
  506. editor = os.environ.get("GIT_EDITOR")
  507. if editor is None:
  508. try:
  509. editor_bytes = config.get(("core",), "editor")
  510. editor = editor_bytes.decode("utf-8", "replace")
  511. except KeyError:
  512. editor = os.environ.get("VISUAL") or os.environ.get("EDITOR")
  513. return editor
  514. def get_sequence_editor() -> Optional[str]:
  515. """Get GIT_SEQUENCE_EDITOR."""
  516. sequence_editor = os.environ.get("GIT_SEQUENCE_EDITOR")
  517. if sequence_editor is None:
  518. try:
  519. seq_editor_bytes = config.get(("sequence",), "editor")
  520. sequence_editor = seq_editor_bytes.decode("utf-8", "replace")
  521. except KeyError:
  522. # Falls back to GIT_EDITOR if not set
  523. sequence_editor = get_editor()
  524. return sequence_editor
  525. def get_pager() -> Optional[str]:
  526. """Get GIT_PAGER."""
  527. pager = os.environ.get("GIT_PAGER")
  528. if pager is None:
  529. try:
  530. pager_bytes = config.get(("core",), "pager")
  531. pager = pager_bytes.decode("utf-8", "replace")
  532. except KeyError:
  533. pager = os.environ.get("PAGER")
  534. return pager
  535. def get_default_branch() -> str:
  536. """Get GIT_DEFAULT_BRANCH."""
  537. try:
  538. default_branch_bytes = config.get(("init",), "defaultBranch")
  539. return default_branch_bytes.decode("utf-8", "replace")
  540. except KeyError:
  541. # Git's default is "master"
  542. return "master"
  543. # Dictionary mapping variable names to their getter callbacks
  544. variable_callbacks: dict[str, Callable[[], Optional[str]]] = {
  545. "GIT_AUTHOR_IDENT": get_author_ident,
  546. "GIT_COMMITTER_IDENT": get_committer_ident,
  547. "GIT_EDITOR": get_editor,
  548. "GIT_SEQUENCE_EDITOR": get_sequence_editor,
  549. "GIT_PAGER": get_pager,
  550. "GIT_DEFAULT_BRANCH": get_default_branch,
  551. }
  552. # Build the variables dictionary by calling callbacks
  553. variables: dict[str, str] = {}
  554. for var_name, callback in variable_callbacks.items():
  555. value = callback()
  556. if value is not None:
  557. variables[var_name] = value
  558. return variables
  559. def var_list(repo: RepoPath = ".") -> dict[str, str]:
  560. """List all Git logical variables.
  561. Args:
  562. repo: Path to the repository
  563. Returns:
  564. A dictionary of all logical variables with their values
  565. """
  566. return _get_variables(repo)
  567. def var(repo: RepoPath = ".", variable: str = "GIT_AUTHOR_IDENT") -> str:
  568. """Get the value of a specific Git logical variable.
  569. Args:
  570. repo: Path to the repository
  571. variable: The variable to query (e.g., 'GIT_AUTHOR_IDENT')
  572. Returns:
  573. The value of the requested variable as a string
  574. Raises:
  575. KeyError: If the requested variable has no value
  576. """
  577. variables = _get_variables(repo)
  578. if variable in variables:
  579. return variables[variable]
  580. else:
  581. raise KeyError(f"Variable {variable} has no value")
  582. def commit(
  583. repo: RepoPath = ".",
  584. message: Optional[Union[str, bytes, Callable[[Any, Commit], bytes]]] = None,
  585. author: Optional[bytes] = None,
  586. author_timezone: Optional[int] = None,
  587. committer: Optional[bytes] = None,
  588. commit_timezone: Optional[int] = None,
  589. encoding: Optional[bytes] = None,
  590. no_verify: bool = False,
  591. signoff: Optional[bool] = None,
  592. all: bool = False,
  593. amend: bool = False,
  594. sign: Optional[bool] = None,
  595. ) -> bytes:
  596. """Create a new commit.
  597. Args:
  598. repo: Path to repository
  599. message: Optional commit message (string/bytes or callable that takes
  600. (repo, commit) and returns bytes)
  601. author: Optional author name and email
  602. author_timezone: Author timestamp timezone
  603. committer: Optional committer name and email
  604. commit_timezone: Commit timestamp timezone
  605. encoding: Encoding to use for commit message
  606. no_verify: Skip pre-commit and commit-msg hooks
  607. signoff: Add Signed-off-by line to commit message. If None, uses format.signoff config.
  608. all: Automatically stage all tracked files that have been modified
  609. amend: Replace the tip of the current branch by creating a new commit
  610. sign: GPG sign the commit. If None, uses commit.gpgsign config.
  611. If True, signs with default GPG key. If False, does not sign.
  612. Returns: SHA1 of the new commit
  613. """
  614. encoding_str = encoding.decode("ascii") if encoding else DEFAULT_ENCODING
  615. if isinstance(message, str):
  616. message = message.encode(encoding_str)
  617. if isinstance(author, str):
  618. author = author.encode(encoding_str)
  619. if isinstance(committer, str):
  620. committer = committer.encode(encoding_str)
  621. local_timezone = get_user_timezones()
  622. if author_timezone is None:
  623. author_timezone = local_timezone[0]
  624. if commit_timezone is None:
  625. commit_timezone = local_timezone[1]
  626. with open_repo_closing(repo) as r:
  627. # Handle amend logic
  628. merge_heads = None
  629. if amend:
  630. try:
  631. head_commit = r[r.head()]
  632. assert isinstance(head_commit, Commit)
  633. except KeyError:
  634. raise ValueError("Cannot amend: no existing commit found")
  635. # If message not provided, use the message from the current HEAD
  636. if message is None:
  637. message = head_commit.message
  638. # If author not provided, use the author from the current HEAD
  639. if author is None:
  640. author = head_commit.author
  641. if author_timezone is None:
  642. author_timezone = head_commit.author_timezone
  643. # Use the parent(s) of the current HEAD as our parent(s)
  644. merge_heads = list(head_commit.parents)
  645. # If -a flag is used, stage all modified tracked files
  646. if all:
  647. index = r.open_index()
  648. normalizer = r.get_blob_normalizer()
  649. # Create a wrapper that handles the bytes -> Blob conversion
  650. if normalizer is not None:
  651. def filter_callback(data: bytes, path: bytes) -> bytes:
  652. from dulwich.objects import Blob
  653. blob = Blob()
  654. blob.data = data
  655. normalized_blob = normalizer.checkin_normalize(blob, path)
  656. data_bytes: bytes = normalized_blob.data
  657. return data_bytes
  658. else:
  659. filter_callback = None
  660. unstaged_changes = list(
  661. get_unstaged_changes(index, r.path, filter_callback)
  662. )
  663. if unstaged_changes:
  664. # Convert bytes paths to strings for add function
  665. modified_files: list[Union[str, bytes, os.PathLike[str]]] = []
  666. for path in unstaged_changes:
  667. if isinstance(path, bytes):
  668. modified_files.append(path.decode())
  669. else:
  670. modified_files.append(path)
  671. add(r, paths=modified_files)
  672. # For amend, create dangling commit to avoid adding current HEAD as parent
  673. if amend:
  674. commit_sha = r.get_worktree().commit(
  675. message=message,
  676. author=author,
  677. author_timezone=author_timezone,
  678. committer=committer,
  679. commit_timezone=commit_timezone,
  680. encoding=encoding,
  681. no_verify=no_verify,
  682. sign=sign,
  683. merge_heads=merge_heads,
  684. ref=None,
  685. )
  686. # Update HEAD to point to the new commit
  687. r.refs[b"HEAD"] = commit_sha
  688. return commit_sha
  689. else:
  690. return r.get_worktree().commit(
  691. message=message,
  692. author=author,
  693. author_timezone=author_timezone,
  694. committer=committer,
  695. commit_timezone=commit_timezone,
  696. encoding=encoding,
  697. no_verify=no_verify,
  698. sign=sign,
  699. merge_heads=merge_heads,
  700. )
  701. def commit_tree(
  702. repo: RepoPath,
  703. tree: bytes,
  704. message: Optional[Union[str, bytes]] = None,
  705. author: Optional[bytes] = None,
  706. committer: Optional[bytes] = None,
  707. ) -> bytes:
  708. """Create a new commit object.
  709. Args:
  710. repo: Path to repository
  711. tree: An existing tree object
  712. message: Commit message
  713. author: Optional author name and email
  714. committer: Optional committer name and email
  715. """
  716. with open_repo_closing(repo) as r:
  717. if isinstance(message, str):
  718. message = message.encode(DEFAULT_ENCODING)
  719. return r.get_worktree().commit(
  720. message=message, tree=tree, committer=committer, author=author
  721. )
  722. def init(
  723. path: Union[str, os.PathLike[str]] = ".",
  724. *,
  725. bare: bool = False,
  726. symlinks: Optional[bool] = None,
  727. ) -> Repo:
  728. """Create a new git repository.
  729. Args:
  730. path: Path to repository.
  731. bare: Whether to create a bare repository.
  732. symlinks: Whether to create actual symlinks (defaults to autodetect)
  733. Returns: A Repo instance
  734. """
  735. if not os.path.exists(path):
  736. os.mkdir(path)
  737. if bare:
  738. return Repo.init_bare(path)
  739. else:
  740. return Repo.init(path, symlinks=symlinks)
  741. def clone(
  742. source: Union[str, bytes, Repo],
  743. target: Optional[Union[str, os.PathLike[str]]] = None,
  744. bare: bool = False,
  745. checkout: Optional[bool] = None,
  746. errstream: Union[BinaryIO, RawIOBase] = default_bytes_err_stream,
  747. outstream: Optional[BinaryIO] = None,
  748. origin: Optional[str] = "origin",
  749. depth: Optional[int] = None,
  750. branch: Optional[Union[str, bytes]] = None,
  751. config: Optional[Config] = None,
  752. filter_spec: Optional[str] = None,
  753. protocol_version: Optional[int] = None,
  754. recurse_submodules: bool = False,
  755. **kwargs: Union[Union[str, bytes], Sequence[Union[str, bytes]]],
  756. ) -> Repo:
  757. """Clone a local or remote git repository.
  758. Args:
  759. source: Path or URL for source repository
  760. target: Path to target repository (optional)
  761. bare: Whether or not to create a bare repository
  762. checkout: Whether or not to check-out HEAD after cloning
  763. errstream: Optional stream to write progress to
  764. outstream: Optional stream to write progress to (deprecated)
  765. origin: Name of remote from the repository used to clone
  766. depth: Depth to fetch at
  767. branch: Optional branch or tag to be used as HEAD in the new repository
  768. instead of the cloned repository's HEAD.
  769. config: Configuration to use
  770. filter_spec: A git-rev-list-style object filter spec, as an ASCII string.
  771. Only used if the server supports the Git protocol-v2 'filter'
  772. feature, and ignored otherwise.
  773. protocol_version: desired Git protocol version. By default the highest
  774. mutually supported protocol version will be used.
  775. recurse_submodules: Whether to initialize and clone submodules
  776. **kwargs: Additional keyword arguments including refspecs to fetch.
  777. Can be a bytestring, a string, or a list of bytestring/string.
  778. Returns: The new repository
  779. """
  780. if outstream is not None:
  781. import warnings
  782. warnings.warn(
  783. "outstream= has been deprecated in favour of errstream=.",
  784. DeprecationWarning,
  785. stacklevel=3,
  786. )
  787. # TODO(jelmer): Capture logging output and stream to errstream
  788. if config is None:
  789. config = StackedConfig.default()
  790. if checkout is None:
  791. checkout = not bare
  792. if checkout and bare:
  793. raise Error("checkout and bare are incompatible")
  794. if target is None:
  795. if isinstance(source, Repo):
  796. raise ValueError("target must be specified when cloning from a Repo object")
  797. elif isinstance(source, bytes):
  798. target = source.split(b"/")[-1].decode()
  799. else:
  800. target = source.split("/")[-1]
  801. if isinstance(branch, str):
  802. branch = branch.encode(DEFAULT_ENCODING)
  803. mkdir = not os.path.exists(target)
  804. if isinstance(source, Repo):
  805. # For direct repo cloning, use LocalGitClient
  806. from .client import GitClient, LocalGitClient
  807. client: GitClient = LocalGitClient(config=config)
  808. path = source.path
  809. else:
  810. source_str = source.decode() if isinstance(source, bytes) else source
  811. (client, path) = get_transport_and_path(source_str, config=config, **kwargs) # type: ignore[arg-type]
  812. filter_spec_bytes: Optional[bytes] = None
  813. if filter_spec:
  814. filter_spec_bytes = filter_spec.encode("ascii")
  815. repo = client.clone(
  816. path,
  817. str(target), # Convert PathLike to str
  818. mkdir=mkdir,
  819. bare=bare,
  820. origin=origin,
  821. checkout=checkout,
  822. branch=branch.decode() if branch else None, # Convert bytes to str
  823. progress=lambda data: (errstream.write(data), None)[1],
  824. depth=depth,
  825. filter_spec=filter_spec_bytes,
  826. protocol_version=protocol_version,
  827. )
  828. # Initialize and update submodules if requested
  829. if recurse_submodules and not bare:
  830. try:
  831. submodule_init(repo)
  832. submodule_update(repo, init=True)
  833. except FileNotFoundError as e:
  834. # .gitmodules file doesn't exist - no submodules to process
  835. logging.debug("No .gitmodules file found: %s", e)
  836. except KeyError as e:
  837. # Submodule configuration missing
  838. logging.warning("Submodule configuration error: %s", e)
  839. if errstream:
  840. errstream.write(
  841. f"Warning: Submodule configuration error: {e}\n".encode()
  842. )
  843. return repo
  844. def add(
  845. repo: Union[str, os.PathLike[str], Repo] = ".",
  846. paths: Optional[
  847. Union[
  848. Sequence[Union[str, bytes, os.PathLike[str]]], str, bytes, os.PathLike[str]
  849. ]
  850. ] = None,
  851. ) -> tuple[list[str], set[str]]:
  852. """Add files to the staging area.
  853. Args:
  854. repo: Repository for the files
  855. paths: Paths to add. If None, stages all untracked and modified files from the
  856. current working directory (mimicking 'git add .' behavior).
  857. Returns: Tuple with set of added files and ignored files
  858. If the repository contains ignored directories, the returned set will
  859. contain the path to an ignored directory (with trailing slash). Individual
  860. files within ignored directories will not be returned.
  861. Note: When paths=None, this function adds all untracked and modified files
  862. from the entire repository, mimicking 'git add -A' behavior.
  863. """
  864. ignored = set()
  865. with open_repo_closing(repo) as r:
  866. repo_path = Path(r.path).resolve()
  867. ignore_manager = IgnoreFilterManager.from_repo(r)
  868. # Get unstaged changes once for the entire operation
  869. index = r.open_index()
  870. normalizer = r.get_blob_normalizer()
  871. if normalizer is not None:
  872. def filter_callback(data: bytes, path: bytes) -> bytes:
  873. from dulwich.objects import Blob
  874. blob = Blob()
  875. blob.data = data
  876. normalized_blob = normalizer.checkin_normalize(blob, path)
  877. data_bytes: bytes = normalized_blob.data
  878. return data_bytes
  879. else:
  880. filter_callback = None
  881. # Check if core.preloadIndex is enabled
  882. config = r.get_config_stack()
  883. preload_index = config.get_boolean(b"core", b"preloadIndex", False)
  884. all_unstaged_paths = list(
  885. get_unstaged_changes(index, r.path, filter_callback, preload_index)
  886. )
  887. if not paths:
  888. # When no paths specified, add all untracked and modified files from repo root
  889. paths = [str(repo_path)]
  890. relpaths = []
  891. if isinstance(paths, (str, bytes, os.PathLike)):
  892. paths = [paths]
  893. for p in paths:
  894. # Handle bytes paths by decoding them
  895. if isinstance(p, bytes):
  896. p = p.decode("utf-8")
  897. path = Path(p)
  898. if not path.is_absolute():
  899. # Make relative paths relative to the repo directory
  900. path = repo_path / path
  901. # Don't resolve symlinks completely - only resolve the parent directory
  902. # to avoid issues when symlinks point outside the repository
  903. if path.is_symlink():
  904. # For symlinks, resolve only the parent directory
  905. parent_resolved = path.parent.resolve()
  906. resolved_path = parent_resolved / path.name
  907. else:
  908. # For regular files/dirs, resolve normally
  909. resolved_path = path.resolve()
  910. try:
  911. relpath = str(resolved_path.relative_to(repo_path)).replace(os.sep, "/")
  912. except ValueError as e:
  913. # Path is not within the repository
  914. p_str = p.decode() if isinstance(p, bytes) else str(p)
  915. raise ValueError(
  916. f"Path {p_str} is not within repository {repo_path}"
  917. ) from e
  918. # Handle directories by scanning their contents
  919. if resolved_path.is_dir():
  920. # Check if the directory itself is ignored
  921. dir_relpath = posixpath.join(relpath, "") if relpath != "." else ""
  922. if dir_relpath and ignore_manager.is_ignored(dir_relpath):
  923. ignored.add(dir_relpath)
  924. continue
  925. # When adding a directory, add all untracked files within it
  926. current_untracked = list(
  927. get_untracked_paths(
  928. str(resolved_path),
  929. str(repo_path),
  930. index,
  931. )
  932. )
  933. for untracked_path in current_untracked:
  934. # If we're scanning a subdirectory, adjust the path
  935. if relpath != ".":
  936. untracked_path = posixpath.join(relpath, untracked_path)
  937. if not ignore_manager.is_ignored(untracked_path):
  938. relpaths.append(untracked_path)
  939. else:
  940. ignored.add(untracked_path)
  941. # Also add unstaged (modified) files within this directory
  942. for unstaged_path in all_unstaged_paths:
  943. if isinstance(unstaged_path, bytes):
  944. unstaged_path_str = unstaged_path.decode("utf-8")
  945. else:
  946. unstaged_path_str = unstaged_path
  947. # Check if this unstaged file is within the directory we're processing
  948. unstaged_full_path = repo_path / unstaged_path_str
  949. try:
  950. unstaged_full_path.relative_to(resolved_path)
  951. # File is within this directory, add it
  952. if not ignore_manager.is_ignored(unstaged_path_str):
  953. relpaths.append(unstaged_path_str)
  954. else:
  955. ignored.add(unstaged_path_str)
  956. except ValueError:
  957. # File is not within this directory, skip it
  958. continue
  959. continue
  960. # FIXME: Support patterns
  961. if ignore_manager.is_ignored(relpath):
  962. ignored.add(relpath)
  963. continue
  964. relpaths.append(relpath)
  965. r.get_worktree().stage(relpaths)
  966. return (relpaths, ignored)
  967. def _is_subdir(
  968. subdir: Union[str, os.PathLike[str]], parentdir: Union[str, os.PathLike[str]]
  969. ) -> bool:
  970. """Check whether subdir is parentdir or a subdir of parentdir.
  971. If parentdir or subdir is a relative path, it will be disamgibuated
  972. relative to the pwd.
  973. """
  974. parentdir_abs = os.path.realpath(parentdir) + os.path.sep
  975. subdir_abs = os.path.realpath(subdir) + os.path.sep
  976. return subdir_abs.startswith(parentdir_abs)
  977. # TODO: option to remove ignored files also, in line with `git clean -fdx`
  978. def clean(
  979. repo: Union[str, os.PathLike[str], Repo] = ".",
  980. target_dir: Optional[Union[str, os.PathLike[str]]] = None,
  981. ) -> None:
  982. """Remove any untracked files from the target directory recursively.
  983. Equivalent to running ``git clean -fd`` in target_dir.
  984. Args:
  985. repo: Repository where the files may be tracked
  986. target_dir: Directory to clean - current directory if None
  987. """
  988. if target_dir is None:
  989. target_dir = os.getcwd()
  990. with open_repo_closing(repo) as r:
  991. if not _is_subdir(target_dir, r.path):
  992. raise Error("target_dir must be in the repo's working dir")
  993. config = r.get_config_stack()
  994. config.get_boolean((b"clean",), b"requireForce", True)
  995. # TODO(jelmer): if require_force is set, then make sure that -f, -i or
  996. # -n is specified.
  997. index = r.open_index()
  998. ignore_manager = IgnoreFilterManager.from_repo(r)
  999. paths_in_wd = _walk_working_dir_paths(target_dir, r.path)
  1000. # Reverse file visit order, so that files and subdirectories are
  1001. # removed before containing directory
  1002. for ap, is_dir in reversed(list(paths_in_wd)):
  1003. # target_dir and r.path are both str, so ap must be str
  1004. assert isinstance(ap, str)
  1005. if is_dir:
  1006. # All subdirectories and files have been removed if untracked,
  1007. # so dir contains no tracked files iff it is empty.
  1008. is_empty = len(os.listdir(ap)) == 0
  1009. if is_empty:
  1010. os.rmdir(ap)
  1011. else:
  1012. ip = path_to_tree_path(r.path, ap)
  1013. is_tracked = ip in index
  1014. rp = os.path.relpath(ap, r.path)
  1015. is_ignored = ignore_manager.is_ignored(rp)
  1016. if not is_tracked and not is_ignored:
  1017. os.remove(ap)
  1018. def remove(
  1019. repo: Union[str, os.PathLike[str], Repo] = ".",
  1020. paths: Sequence[Union[str, bytes, os.PathLike[str]]] = [],
  1021. cached: bool = False,
  1022. ) -> None:
  1023. """Remove files from the staging area.
  1024. Args:
  1025. repo: Repository for the files
  1026. paths: Paths to remove. Can be absolute or relative to the repository root.
  1027. cached: Only remove from index, not from working directory
  1028. """
  1029. with open_repo_closing(repo) as r:
  1030. index = r.open_index()
  1031. blob_normalizer = r.get_blob_normalizer()
  1032. for p in paths:
  1033. # If path is absolute, use it as-is. Otherwise, treat it as relative to repo
  1034. p_str = os.fsdecode(p) if isinstance(p, bytes) else str(p)
  1035. if os.path.isabs(p_str):
  1036. full_path = p_str
  1037. else:
  1038. # Treat relative paths as relative to the repository root
  1039. full_path = os.path.join(r.path, p_str)
  1040. tree_path = path_to_tree_path(r.path, full_path)
  1041. # Convert to bytes for file operations
  1042. full_path_bytes = os.fsencode(full_path)
  1043. try:
  1044. entry = index[tree_path]
  1045. if isinstance(entry, ConflictedIndexEntry):
  1046. raise Error(f"{p_str} has conflicts in the index")
  1047. index_sha = entry.sha
  1048. except KeyError as exc:
  1049. raise Error(f"{p_str} did not match any files") from exc
  1050. if not cached:
  1051. try:
  1052. st = os.lstat(full_path_bytes)
  1053. except OSError:
  1054. pass
  1055. else:
  1056. try:
  1057. blob = blob_from_path_and_stat(full_path_bytes, st)
  1058. # Apply checkin normalization to compare apples to apples
  1059. if blob_normalizer is not None:
  1060. blob = blob_normalizer.checkin_normalize(blob, tree_path)
  1061. except OSError:
  1062. pass
  1063. else:
  1064. try:
  1065. head_commit = r[r.head()]
  1066. assert isinstance(head_commit, Commit)
  1067. committed_sha = tree_lookup_path(
  1068. r.__getitem__, head_commit.tree, tree_path
  1069. )[1]
  1070. except KeyError:
  1071. committed_sha = None
  1072. if blob.id != index_sha and index_sha != committed_sha:
  1073. raise Error(
  1074. "file has staged content differing "
  1075. f"from both the file and head: {p_str}"
  1076. )
  1077. if index_sha != committed_sha:
  1078. raise Error(f"file has staged changes: {p_str}")
  1079. os.remove(full_path_bytes)
  1080. del index[tree_path]
  1081. index.write()
  1082. rm = remove
  1083. def mv(
  1084. repo: Union[str, os.PathLike[str], Repo],
  1085. source: Union[str, bytes, os.PathLike[str]],
  1086. destination: Union[str, bytes, os.PathLike[str]],
  1087. force: bool = False,
  1088. ) -> None:
  1089. """Move or rename a file, directory, or symlink.
  1090. Args:
  1091. repo: Path to the repository
  1092. source: Path to move from
  1093. destination: Path to move to
  1094. force: Force move even if destination exists
  1095. Raises:
  1096. Error: If source doesn't exist, is not tracked, or destination already exists (without force)
  1097. """
  1098. with open_repo_closing(repo) as r:
  1099. index = r.open_index()
  1100. # Handle paths - convert to string if necessary
  1101. if isinstance(source, bytes):
  1102. source = source.decode(sys.getfilesystemencoding())
  1103. elif hasattr(source, "__fspath__"):
  1104. source = os.fspath(source)
  1105. else:
  1106. source = str(source)
  1107. if isinstance(destination, bytes):
  1108. destination = destination.decode(sys.getfilesystemencoding())
  1109. elif hasattr(destination, "__fspath__"):
  1110. destination = os.fspath(destination)
  1111. else:
  1112. destination = str(destination)
  1113. # Get full paths
  1114. if os.path.isabs(source):
  1115. source_full_path = source
  1116. else:
  1117. # Treat relative paths as relative to the repository root
  1118. source_full_path = os.path.join(r.path, source)
  1119. if os.path.isabs(destination):
  1120. destination_full_path = destination
  1121. else:
  1122. # Treat relative paths as relative to the repository root
  1123. destination_full_path = os.path.join(r.path, destination)
  1124. # Check if destination is a directory
  1125. if os.path.isdir(destination_full_path):
  1126. # Move source into destination directory
  1127. basename = os.path.basename(source_full_path)
  1128. destination_full_path = os.path.join(destination_full_path, basename)
  1129. # Convert to tree paths for index
  1130. source_tree_path = path_to_tree_path(r.path, source_full_path)
  1131. destination_tree_path = path_to_tree_path(r.path, destination_full_path)
  1132. # Check if source exists in index
  1133. if source_tree_path not in index:
  1134. raise Error(f"source '{source}' is not under version control")
  1135. # Check if source exists in filesystem
  1136. if not os.path.exists(source_full_path):
  1137. raise Error(f"source '{source}' does not exist")
  1138. # Check if destination already exists
  1139. if os.path.exists(destination_full_path) and not force:
  1140. raise Error(f"destination '{destination}' already exists (use -f to force)")
  1141. # Check if destination is already in index
  1142. if destination_tree_path in index and not force:
  1143. raise Error(
  1144. f"destination '{destination}' already exists in index (use -f to force)"
  1145. )
  1146. # Get the index entry for the source
  1147. source_entry = index[source_tree_path]
  1148. # Convert to bytes for file operations
  1149. source_full_path_bytes = os.fsencode(source_full_path)
  1150. destination_full_path_bytes = os.fsencode(destination_full_path)
  1151. # Create parent directory for destination if needed
  1152. dest_dir = os.path.dirname(destination_full_path_bytes)
  1153. if dest_dir and not os.path.exists(dest_dir):
  1154. os.makedirs(dest_dir)
  1155. # Move the file in the filesystem
  1156. if os.path.exists(destination_full_path_bytes) and force:
  1157. os.remove(destination_full_path_bytes)
  1158. os.rename(source_full_path_bytes, destination_full_path_bytes)
  1159. # Update the index
  1160. del index[source_tree_path]
  1161. index[destination_tree_path] = source_entry
  1162. index.write()
  1163. move = mv
  1164. def commit_decode(
  1165. commit: Commit, contents: bytes, default_encoding: str = DEFAULT_ENCODING
  1166. ) -> str:
  1167. """Decode commit contents using the commit's encoding or default."""
  1168. if commit.encoding:
  1169. encoding = commit.encoding.decode("ascii")
  1170. else:
  1171. encoding = default_encoding
  1172. return contents.decode(encoding, "replace")
  1173. def commit_encode(
  1174. commit: Commit, contents: str, default_encoding: str = DEFAULT_ENCODING
  1175. ) -> bytes:
  1176. """Encode commit contents using the commit's encoding or default."""
  1177. if commit.encoding:
  1178. encoding = commit.encoding.decode("ascii")
  1179. else:
  1180. encoding = default_encoding
  1181. return contents.encode(encoding)
  1182. def print_commit(
  1183. commit: Commit,
  1184. decode: Callable[[bytes], str],
  1185. outstream: TextIO = sys.stdout,
  1186. ) -> None:
  1187. """Write a human-readable commit log entry.
  1188. Args:
  1189. commit: A `Commit` object
  1190. decode: Function to decode commit data
  1191. outstream: A stream file to write to
  1192. """
  1193. outstream.write("-" * 50 + "\n")
  1194. outstream.write("commit: " + commit.id.decode("ascii") + "\n")
  1195. if len(commit.parents) > 1:
  1196. outstream.write(
  1197. "merge: "
  1198. + "...".join([c.decode("ascii") for c in commit.parents[1:]])
  1199. + "\n"
  1200. )
  1201. outstream.write("Author: " + decode(commit.author) + "\n")
  1202. if commit.author != commit.committer:
  1203. outstream.write("Committer: " + decode(commit.committer) + "\n")
  1204. time_tuple = time.gmtime(commit.author_time + commit.author_timezone)
  1205. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  1206. timezone_str = format_timezone(commit.author_timezone).decode("ascii")
  1207. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  1208. if commit.message:
  1209. outstream.write("\n")
  1210. outstream.write(decode(commit.message) + "\n")
  1211. outstream.write("\n")
  1212. def print_tag(
  1213. tag: Tag, decode: Callable[[bytes], str], outstream: TextIO = sys.stdout
  1214. ) -> None:
  1215. """Write a human-readable tag.
  1216. Args:
  1217. tag: A `Tag` object
  1218. decode: Function for decoding bytes to unicode string
  1219. outstream: A stream to write to
  1220. """
  1221. outstream.write("Tagger: " + decode(tag.tagger) + "\n")
  1222. time_tuple = time.gmtime(tag.tag_time + tag.tag_timezone)
  1223. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  1224. timezone_str = format_timezone(tag.tag_timezone).decode("ascii")
  1225. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  1226. outstream.write("\n")
  1227. outstream.write(decode(tag.message))
  1228. outstream.write("\n")
  1229. def show_blob(
  1230. repo: RepoPath,
  1231. blob: Blob,
  1232. decode: Callable[[bytes], str],
  1233. outstream: TextIO = sys.stdout,
  1234. ) -> None:
  1235. """Write a blob to a stream.
  1236. Args:
  1237. repo: A `Repo` object
  1238. blob: A `Blob` object
  1239. decode: Function for decoding bytes to unicode string
  1240. outstream: A stream file to write to
  1241. """
  1242. outstream.write(decode(blob.data))
  1243. def show_commit(
  1244. repo: RepoPath,
  1245. commit: Commit,
  1246. decode: Callable[[bytes], str],
  1247. outstream: TextIO = sys.stdout,
  1248. ) -> None:
  1249. """Show a commit to a stream.
  1250. Args:
  1251. repo: A `Repo` object
  1252. commit: A `Commit` object
  1253. decode: Function for decoding bytes to unicode string
  1254. outstream: Stream to write to
  1255. """
  1256. from .diff import ColorizedDiffStream
  1257. # Create a wrapper for ColorizedDiffStream to handle string/bytes conversion
  1258. class _StreamWrapper:
  1259. def __init__(self, stream: "ColorizedDiffStream") -> None:
  1260. self.stream = stream
  1261. def write(self, data: Union[str, bytes]) -> None:
  1262. if isinstance(data, str):
  1263. # Convert string to bytes for ColorizedDiffStream
  1264. self.stream.write(data.encode("utf-8"))
  1265. else:
  1266. self.stream.write(data)
  1267. with open_repo_closing(repo) as r:
  1268. # Use wrapper for ColorizedDiffStream, direct stream for others
  1269. if isinstance(outstream, ColorizedDiffStream):
  1270. wrapped_stream = _StreamWrapper(outstream)
  1271. print_commit(commit, decode=decode, outstream=wrapped_stream)
  1272. # Write diff directly to the ColorizedDiffStream as bytes
  1273. write_tree_diff(
  1274. outstream,
  1275. r.object_store,
  1276. commit.parents[0] if commit.parents else None,
  1277. commit.tree,
  1278. )
  1279. else:
  1280. print_commit(commit, decode=decode, outstream=outstream)
  1281. if commit.parents:
  1282. parent_commit = r[commit.parents[0]]
  1283. assert isinstance(parent_commit, Commit)
  1284. base_tree = parent_commit.tree
  1285. else:
  1286. base_tree = None
  1287. # Traditional path: buffer diff and write as decoded text
  1288. diffstream = BytesIO()
  1289. write_tree_diff(diffstream, r.object_store, base_tree, commit.tree)
  1290. diffstream.seek(0)
  1291. outstream.write(commit_decode(commit, diffstream.getvalue()))
  1292. def show_tree(
  1293. repo: RepoPath,
  1294. tree: Tree,
  1295. decode: Callable[[bytes], str],
  1296. outstream: TextIO = sys.stdout,
  1297. ) -> None:
  1298. """Print a tree to a stream.
  1299. Args:
  1300. repo: A `Repo` object
  1301. tree: A `Tree` object
  1302. decode: Function for decoding bytes to unicode string
  1303. outstream: Stream to write to
  1304. """
  1305. for n in tree:
  1306. outstream.write(decode(n) + "\n")
  1307. def show_tag(
  1308. repo: RepoPath,
  1309. tag: Tag,
  1310. decode: Callable[[bytes], str],
  1311. outstream: TextIO = sys.stdout,
  1312. ) -> None:
  1313. """Print a tag to a stream.
  1314. Args:
  1315. repo: A `Repo` object
  1316. tag: A `Tag` object
  1317. decode: Function for decoding bytes to unicode string
  1318. outstream: Stream to write to
  1319. """
  1320. with open_repo_closing(repo) as r:
  1321. print_tag(tag, decode, outstream)
  1322. obj = r[tag.object[1]]
  1323. assert isinstance(obj, (Tree, Blob, Commit, Tag))
  1324. show_object(repo, obj, decode, outstream)
  1325. def show_object(
  1326. repo: RepoPath,
  1327. obj: Union[Tree, Blob, Commit, Tag],
  1328. decode: Callable[[bytes], str],
  1329. outstream: TextIO,
  1330. ) -> None:
  1331. """Show details of a git object."""
  1332. handlers: dict[bytes, Callable[[RepoPath, Any, Any, TextIO], None]] = {
  1333. b"tree": show_tree,
  1334. b"blob": show_blob,
  1335. b"commit": show_commit,
  1336. b"tag": show_tag,
  1337. }
  1338. handler = handlers.get(obj.type_name)
  1339. if handler is None:
  1340. raise ValueError(f"Unknown object type: {obj.type_name.decode()}")
  1341. handler(repo, obj, decode, outstream)
  1342. def print_name_status(changes: Iterator[TreeChange]) -> Iterator[str]:
  1343. """Print a simple status summary, listing changed files."""
  1344. for change in changes:
  1345. if not change:
  1346. continue
  1347. if isinstance(change, list):
  1348. change = change[0]
  1349. if change.type == CHANGE_ADD:
  1350. assert change.new is not None
  1351. path1 = change.new.path
  1352. assert path1 is not None
  1353. path2 = b""
  1354. kind = "A"
  1355. elif change.type == CHANGE_DELETE:
  1356. assert change.old is not None
  1357. path1 = change.old.path
  1358. assert path1 is not None
  1359. path2 = b""
  1360. kind = "D"
  1361. elif change.type == CHANGE_MODIFY:
  1362. assert change.new is not None
  1363. path1 = change.new.path
  1364. assert path1 is not None
  1365. path2 = b""
  1366. kind = "M"
  1367. elif change.type in RENAME_CHANGE_TYPES:
  1368. assert change.old is not None and change.new is not None
  1369. path1 = change.old.path
  1370. assert path1 is not None
  1371. path2_opt = change.new.path
  1372. assert path2_opt is not None
  1373. path2 = path2_opt
  1374. if change.type == CHANGE_RENAME:
  1375. kind = "R"
  1376. elif change.type == CHANGE_COPY:
  1377. kind = "C"
  1378. path1_str = (
  1379. path1.decode("utf-8", errors="replace")
  1380. if isinstance(path1, bytes)
  1381. else path1
  1382. )
  1383. path2_str = (
  1384. path2.decode("utf-8", errors="replace")
  1385. if isinstance(path2, bytes)
  1386. else path2
  1387. )
  1388. yield f"{kind:<8}{path1_str:<20}{path2_str:<20}"
  1389. def log(
  1390. repo: RepoPath = ".",
  1391. paths: Optional[Sequence[Union[str, bytes]]] = None,
  1392. outstream: TextIO = sys.stdout,
  1393. max_entries: Optional[int] = None,
  1394. reverse: bool = False,
  1395. name_status: bool = False,
  1396. ) -> None:
  1397. """Write commit logs.
  1398. Args:
  1399. repo: Path to repository
  1400. paths: Optional set of specific paths to print entries for
  1401. outstream: Stream to write log output to
  1402. reverse: Reverse order in which entries are printed
  1403. name_status: Print name status
  1404. max_entries: Optional maximum number of entries to display
  1405. """
  1406. with open_repo_closing(repo) as r:
  1407. try:
  1408. include = [r.head()]
  1409. except KeyError:
  1410. include = []
  1411. # Convert paths to bytes if needed
  1412. paths_bytes = None
  1413. if paths:
  1414. paths_bytes = [p.encode() if isinstance(p, str) else p for p in paths]
  1415. walker = r.get_walker(
  1416. include=include, max_entries=max_entries, paths=paths_bytes, reverse=reverse
  1417. )
  1418. for entry in walker:
  1419. def decode_wrapper(x: bytes) -> str:
  1420. return commit_decode(entry.commit, x)
  1421. print_commit(entry.commit, decode_wrapper, outstream)
  1422. if name_status:
  1423. outstream.writelines(
  1424. [
  1425. line + "\n"
  1426. for line in print_name_status(
  1427. cast(Iterator[TreeChange], entry.changes())
  1428. )
  1429. ]
  1430. )
  1431. # TODO(jelmer): better default for encoding?
  1432. def show(
  1433. repo: RepoPath = ".",
  1434. objects: Optional[Sequence[Union[str, bytes]]] = None,
  1435. outstream: TextIO = sys.stdout,
  1436. default_encoding: str = DEFAULT_ENCODING,
  1437. ) -> None:
  1438. """Print the changes in a commit.
  1439. Args:
  1440. repo: Path to repository
  1441. objects: Objects to show (defaults to [HEAD])
  1442. outstream: Stream to write to
  1443. default_encoding: Default encoding to use if none is set in the
  1444. commit
  1445. """
  1446. if objects is None:
  1447. objects = ["HEAD"]
  1448. if isinstance(objects, (str, bytes)):
  1449. objects = [objects]
  1450. with open_repo_closing(repo) as r:
  1451. for objectish in objects:
  1452. o = parse_object(r, objectish)
  1453. if isinstance(o, Commit):
  1454. def decode(x: bytes) -> str:
  1455. return commit_decode(o, x, default_encoding)
  1456. else:
  1457. def decode(x: bytes) -> str:
  1458. return x.decode(default_encoding)
  1459. assert isinstance(o, (Tree, Blob, Commit, Tag))
  1460. show_object(r, o, decode, outstream)
  1461. def diff_tree(
  1462. repo: RepoPath,
  1463. old_tree: Union[str, bytes, Tree],
  1464. new_tree: Union[str, bytes, Tree],
  1465. outstream: BinaryIO = default_bytes_out_stream,
  1466. ) -> None:
  1467. """Compares the content and mode of blobs found via two tree objects.
  1468. Args:
  1469. repo: Path to repository
  1470. old_tree: Id of old tree
  1471. new_tree: Id of new tree
  1472. outstream: Stream to write to
  1473. """
  1474. with open_repo_closing(repo) as r:
  1475. if isinstance(old_tree, Tree):
  1476. old_tree_id: Optional[bytes] = old_tree.id
  1477. elif isinstance(old_tree, str):
  1478. old_tree_id = old_tree.encode()
  1479. else:
  1480. old_tree_id = old_tree
  1481. if isinstance(new_tree, Tree):
  1482. new_tree_id: Optional[bytes] = new_tree.id
  1483. elif isinstance(new_tree, str):
  1484. new_tree_id = new_tree.encode()
  1485. else:
  1486. new_tree_id = new_tree
  1487. write_tree_diff(outstream, r.object_store, old_tree_id, new_tree_id)
  1488. def diff(
  1489. repo: RepoPath = ".",
  1490. commit: Optional[Union[str, bytes, Commit]] = None,
  1491. commit2: Optional[Union[str, bytes, Commit]] = None,
  1492. staged: bool = False,
  1493. paths: Optional[Sequence[Union[str, bytes]]] = None,
  1494. outstream: BinaryIO = default_bytes_out_stream,
  1495. diff_algorithm: Optional[str] = None,
  1496. ) -> None:
  1497. """Show diff.
  1498. Args:
  1499. repo: Path to repository
  1500. commit: First commit to compare. If staged is True, compare
  1501. index to this commit. If staged is False, compare working tree
  1502. to this commit. If None, defaults to HEAD for staged and index
  1503. for unstaged.
  1504. commit2: Second commit to compare against first commit. If provided,
  1505. show diff between commit and commit2 (ignoring staged flag).
  1506. staged: If True, show staged changes (index vs commit).
  1507. If False, show unstaged changes (working tree vs commit/index).
  1508. Ignored if commit2 is provided.
  1509. paths: Optional list of paths to limit diff
  1510. outstream: Stream to write to
  1511. diff_algorithm: Algorithm to use for diffing ("myers" or "patience"),
  1512. defaults to the underlying function's default if None
  1513. """
  1514. from . import diff as diff_module
  1515. with open_repo_closing(repo) as r:
  1516. # Normalize paths to bytes
  1517. byte_paths: Optional[list[bytes]] = None
  1518. if paths is not None and paths: # Check if paths is not empty
  1519. byte_paths = []
  1520. for p in paths:
  1521. if isinstance(p, str):
  1522. byte_paths.append(p.encode("utf-8"))
  1523. else:
  1524. byte_paths.append(p)
  1525. elif paths == []: # Convert empty list to None
  1526. byte_paths = None
  1527. else:
  1528. byte_paths = None
  1529. # Resolve commit refs to SHAs if provided
  1530. if commit is not None:
  1531. if isinstance(commit, Commit):
  1532. # Already a Commit object
  1533. commit_sha = commit.id
  1534. commit_obj = commit
  1535. else:
  1536. # parse_commit handles both refs and SHAs, and always returns a Commit object
  1537. commit_obj = parse_commit(r, commit)
  1538. commit_sha = commit_obj.id
  1539. else:
  1540. commit_sha = None
  1541. commit_obj = None
  1542. if commit2 is not None:
  1543. # Compare two commits
  1544. if isinstance(commit2, Commit):
  1545. commit2_obj = commit2
  1546. else:
  1547. commit2_obj = parse_commit(r, commit2)
  1548. # Get trees from commits
  1549. old_tree = commit_obj.tree if commit_obj else None
  1550. new_tree = commit2_obj.tree
  1551. # Use tree_changes to get the changes and apply path filtering
  1552. changes = r.object_store.tree_changes(old_tree, new_tree)
  1553. for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
  1554. # Skip if paths are specified and this change doesn't match
  1555. if byte_paths:
  1556. path_to_check = newpath or oldpath
  1557. assert path_to_check is not None
  1558. if not any(
  1559. path_to_check == p or path_to_check.startswith(p + b"/")
  1560. for p in byte_paths
  1561. ):
  1562. continue
  1563. write_object_diff(
  1564. outstream,
  1565. r.object_store,
  1566. (oldpath, oldmode, oldsha),
  1567. (newpath, newmode, newsha),
  1568. diff_algorithm=diff_algorithm,
  1569. )
  1570. elif staged:
  1571. # Show staged changes (index vs commit)
  1572. diff_module.diff_index_to_tree(
  1573. r, outstream, commit_sha, byte_paths, diff_algorithm=diff_algorithm
  1574. )
  1575. elif commit is not None:
  1576. # Compare working tree to a specific commit
  1577. assert (
  1578. commit_sha is not None
  1579. ) # mypy: commit_sha is set when commit is not None
  1580. diff_module.diff_working_tree_to_tree(
  1581. r, outstream, commit_sha, byte_paths, diff_algorithm=diff_algorithm
  1582. )
  1583. else:
  1584. # Compare working tree to index
  1585. diff_module.diff_working_tree_to_index(
  1586. r, outstream, byte_paths, diff_algorithm=diff_algorithm
  1587. )
  1588. def rev_list(
  1589. repo: RepoPath,
  1590. commits: Sequence[Union[str, bytes]],
  1591. outstream: BinaryIO = default_bytes_out_stream,
  1592. ) -> None:
  1593. """Lists commit objects in reverse chronological order.
  1594. Args:
  1595. repo: Path to repository
  1596. commits: Commits over which to iterate
  1597. outstream: Stream to write to
  1598. """
  1599. with open_repo_closing(repo) as r:
  1600. for entry in r.get_walker(
  1601. include=[r[c if isinstance(c, bytes) else c.encode()].id for c in commits]
  1602. ):
  1603. outstream.write(entry.commit.id + b"\n")
  1604. def _canonical_part(url: str) -> str:
  1605. name = url.rsplit("/", 1)[-1]
  1606. if name.endswith(".git"):
  1607. name = name[:-4]
  1608. return name
  1609. def submodule_add(
  1610. repo: Union[str, os.PathLike[str], Repo],
  1611. url: str,
  1612. path: Optional[Union[str, os.PathLike[str]]] = None,
  1613. name: Optional[str] = None,
  1614. ) -> None:
  1615. """Add a new submodule.
  1616. Args:
  1617. repo: Path to repository
  1618. url: URL of repository to add as submodule
  1619. path: Path where submodule should live
  1620. name: Name for the submodule
  1621. """
  1622. with open_repo_closing(repo) as r:
  1623. if path is None:
  1624. path = os.path.relpath(_canonical_part(url), r.path)
  1625. if name is None:
  1626. name = os.fsdecode(path) if path is not None else None
  1627. if name is None:
  1628. raise Error("Submodule name must be specified or derivable from path")
  1629. # TODO(jelmer): Move this logic to dulwich.submodule
  1630. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1631. try:
  1632. config = ConfigFile.from_path(gitmodules_path)
  1633. except FileNotFoundError:
  1634. config = ConfigFile()
  1635. config.path = gitmodules_path
  1636. config.set(("submodule", name), "url", url)
  1637. config.set(("submodule", name), "path", os.fsdecode(path))
  1638. config.write_to_path()
  1639. def submodule_init(repo: Union[str, os.PathLike[str], Repo]) -> None:
  1640. """Initialize submodules.
  1641. Args:
  1642. repo: Path to repository
  1643. """
  1644. with open_repo_closing(repo) as r:
  1645. config = r.get_config()
  1646. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1647. for path, url, name in read_submodules(gitmodules_path):
  1648. config.set((b"submodule", name), b"active", True)
  1649. config.set((b"submodule", name), b"url", url)
  1650. config.write_to_path()
  1651. def submodule_list(repo: RepoPath) -> Iterator[tuple[str, str]]:
  1652. """List submodules.
  1653. Args:
  1654. repo: Path to repository
  1655. """
  1656. from .submodule import iter_cached_submodules
  1657. with open_repo_closing(repo) as r:
  1658. head_commit = r[r.head()]
  1659. assert isinstance(head_commit, Commit)
  1660. for path, sha in iter_cached_submodules(r.object_store, head_commit.tree):
  1661. yield path.decode(DEFAULT_ENCODING), sha.decode(DEFAULT_ENCODING)
  1662. def submodule_update(
  1663. repo: Union[str, os.PathLike[str], Repo],
  1664. paths: Optional[Sequence[Union[str, bytes, os.PathLike[str]]]] = None,
  1665. init: bool = False,
  1666. force: bool = False,
  1667. errstream: Optional[BinaryIO] = None,
  1668. ) -> None:
  1669. """Update submodules.
  1670. Args:
  1671. repo: Path to repository
  1672. paths: Optional list of specific submodule paths to update. If None, updates all.
  1673. init: If True, initialize submodules first
  1674. force: Force update even if local changes exist
  1675. errstream: Error stream for error messages
  1676. """
  1677. from .submodule import iter_cached_submodules
  1678. with open_repo_closing(repo) as r:
  1679. if init:
  1680. submodule_init(r)
  1681. config = r.get_config()
  1682. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1683. # Get list of submodules to update
  1684. submodules_to_update = []
  1685. head_commit = r[r.head()]
  1686. assert isinstance(head_commit, Commit)
  1687. for path, sha in iter_cached_submodules(r.object_store, head_commit.tree):
  1688. path_str = (
  1689. path.decode(DEFAULT_ENCODING) if isinstance(path, bytes) else path
  1690. )
  1691. if paths is None or path_str in paths:
  1692. submodules_to_update.append((path, sha))
  1693. # Read submodule configuration
  1694. for path, target_sha in submodules_to_update:
  1695. path_str = (
  1696. path.decode(DEFAULT_ENCODING) if isinstance(path, bytes) else path
  1697. )
  1698. # Find the submodule name from .gitmodules
  1699. submodule_name: Optional[bytes] = None
  1700. for sm_path, sm_url, sm_name in read_submodules(gitmodules_path):
  1701. if sm_path == path:
  1702. submodule_name = sm_name
  1703. break
  1704. if not submodule_name:
  1705. continue
  1706. # Get the URL from config
  1707. section = (
  1708. b"submodule",
  1709. submodule_name
  1710. if isinstance(submodule_name, bytes)
  1711. else submodule_name.encode(),
  1712. )
  1713. try:
  1714. url_value = config.get(section, b"url")
  1715. if isinstance(url_value, bytes):
  1716. url = url_value.decode(DEFAULT_ENCODING)
  1717. else:
  1718. url = url_value
  1719. except KeyError:
  1720. # URL not in config, skip this submodule
  1721. continue
  1722. # Get or create the submodule repository paths
  1723. submodule_path = os.path.join(r.path, path_str)
  1724. submodule_git_dir = os.path.join(r.path, ".git", "modules", path_str)
  1725. # Clone or fetch the submodule
  1726. if not os.path.exists(submodule_git_dir):
  1727. # Clone the submodule as bare repository
  1728. os.makedirs(os.path.dirname(submodule_git_dir), exist_ok=True)
  1729. # Clone to the git directory
  1730. sub_repo = clone(url, submodule_git_dir, bare=True, checkout=False)
  1731. sub_repo.close()
  1732. # Create the submodule directory if it doesn't exist
  1733. if not os.path.exists(submodule_path):
  1734. os.makedirs(submodule_path)
  1735. # Create .git file in the submodule directory
  1736. depth = path_str.count("/") + 1
  1737. relative_git_dir = "../" * depth + ".git/modules/" + path_str
  1738. git_file_path = os.path.join(submodule_path, ".git")
  1739. with open(git_file_path, "w") as f:
  1740. f.write(f"gitdir: {relative_git_dir}\n")
  1741. # Set up working directory configuration
  1742. with open_repo_closing(submodule_git_dir) as sub_repo:
  1743. sub_config = sub_repo.get_config()
  1744. sub_config.set(
  1745. (b"core",),
  1746. b"worktree",
  1747. os.path.abspath(submodule_path).encode(),
  1748. )
  1749. sub_config.write_to_path()
  1750. # Checkout the target commit
  1751. sub_repo.refs[b"HEAD"] = target_sha
  1752. # Build the index and checkout files
  1753. tree = sub_repo[target_sha]
  1754. if hasattr(tree, "tree"): # If it's a commit, get the tree
  1755. tree_id = tree.tree
  1756. else:
  1757. tree_id = target_sha
  1758. build_index_from_tree(
  1759. submodule_path,
  1760. sub_repo.index_path(),
  1761. sub_repo.object_store,
  1762. tree_id,
  1763. )
  1764. else:
  1765. # Fetch and checkout in existing submodule
  1766. with open_repo_closing(submodule_git_dir) as sub_repo:
  1767. # Fetch from remote
  1768. client, path_segments = get_transport_and_path(url)
  1769. client.fetch(path_segments.encode(), sub_repo)
  1770. # Update to the target commit
  1771. sub_repo.refs[b"HEAD"] = target_sha
  1772. # Reset the working directory
  1773. reset(sub_repo, "hard", target_sha)
  1774. def tag_create(
  1775. repo: RepoPath,
  1776. tag: Union[str, bytes],
  1777. author: Optional[Union[str, bytes]] = None,
  1778. message: Optional[Union[str, bytes]] = None,
  1779. annotated: bool = False,
  1780. objectish: Union[str, bytes] = "HEAD",
  1781. tag_time: Optional[int] = None,
  1782. tag_timezone: Optional[int] = None,
  1783. sign: Optional[bool] = None,
  1784. encoding: str = DEFAULT_ENCODING,
  1785. ) -> None:
  1786. """Creates a tag in git via dulwich calls.
  1787. Args:
  1788. repo: Path to repository
  1789. tag: tag string
  1790. author: tag author (optional, if annotated is set)
  1791. message: tag message (optional)
  1792. annotated: whether to create an annotated tag
  1793. objectish: object the tag should point at, defaults to HEAD
  1794. tag_time: Optional time for annotated tag
  1795. tag_timezone: Optional timezone for annotated tag
  1796. sign: GPG Sign the tag (bool, defaults to False,
  1797. pass True to use default GPG key,
  1798. pass a str containing Key ID to use a specific GPG key)
  1799. encoding: Encoding to use for tag messages
  1800. """
  1801. with open_repo_closing(repo) as r:
  1802. object = parse_object(r, objectish)
  1803. if isinstance(tag, str):
  1804. tag = tag.encode(encoding)
  1805. if annotated:
  1806. # Create the tag object
  1807. tag_obj = Tag()
  1808. if author is None:
  1809. author = get_user_identity(r.get_config_stack())
  1810. elif isinstance(author, str):
  1811. author = author.encode(encoding)
  1812. else:
  1813. assert isinstance(author, bytes)
  1814. tag_obj.tagger = author
  1815. if isinstance(message, str):
  1816. message = message.encode(encoding)
  1817. elif isinstance(message, bytes):
  1818. pass
  1819. else:
  1820. message = b""
  1821. tag_obj.message = message + "\n".encode(encoding)
  1822. tag_obj.name = tag
  1823. tag_obj.object = (type(object), object.id)
  1824. if tag_time is None:
  1825. tag_time = int(time.time())
  1826. tag_obj.tag_time = tag_time
  1827. if tag_timezone is None:
  1828. tag_timezone = get_user_timezones()[1]
  1829. elif isinstance(tag_timezone, str):
  1830. tag_timezone = parse_timezone(tag_timezone.encode())
  1831. tag_obj.tag_timezone = tag_timezone
  1832. # Check if we should sign the tag
  1833. config = r.get_config_stack()
  1834. if sign is None:
  1835. # Check tag.gpgSign configuration when sign is not explicitly set
  1836. try:
  1837. should_sign = config.get_boolean(
  1838. (b"tag",), b"gpgsign", default=False
  1839. )
  1840. except KeyError:
  1841. should_sign = False # Default to not signing if no config
  1842. else:
  1843. should_sign = sign
  1844. # Get the signing key from config if signing is enabled
  1845. keyid = None
  1846. if should_sign:
  1847. try:
  1848. keyid_bytes = config.get((b"user",), b"signingkey")
  1849. keyid = keyid_bytes.decode() if keyid_bytes else None
  1850. except KeyError:
  1851. keyid = None
  1852. tag_obj.sign(keyid)
  1853. r.object_store.add_object(tag_obj)
  1854. tag_id = tag_obj.id
  1855. else:
  1856. tag_id = object.id
  1857. r.refs[_make_tag_ref(tag)] = tag_id
  1858. def verify_commit(
  1859. repo: RepoPath,
  1860. committish: Union[str, bytes] = "HEAD",
  1861. keyids: Optional[list[str]] = None,
  1862. ) -> None:
  1863. """Verify GPG signature on a commit.
  1864. Args:
  1865. repo: Path to repository
  1866. committish: Commit to verify (defaults to HEAD)
  1867. keyids: Optional list of trusted key IDs. If provided, the commit
  1868. must be signed by one of these keys. If not provided, just verifies
  1869. that the commit has a valid signature.
  1870. Raises:
  1871. gpg.errors.BadSignatures: if GPG signature verification fails
  1872. gpg.errors.MissingSignatures: if commit was not signed by a key
  1873. specified in keyids
  1874. """
  1875. with open_repo_closing(repo) as r:
  1876. commit = parse_commit(r, committish)
  1877. commit.verify(keyids)
  1878. def verify_tag(
  1879. repo: RepoPath,
  1880. tagname: Union[str, bytes],
  1881. keyids: Optional[list[str]] = None,
  1882. ) -> None:
  1883. """Verify GPG signature on a tag.
  1884. Args:
  1885. repo: Path to repository
  1886. tagname: Name of tag to verify
  1887. keyids: Optional list of trusted key IDs. If provided, the tag
  1888. must be signed by one of these keys. If not provided, just verifies
  1889. that the tag has a valid signature.
  1890. Raises:
  1891. gpg.errors.BadSignatures: if GPG signature verification fails
  1892. gpg.errors.MissingSignatures: if tag was not signed by a key
  1893. specified in keyids
  1894. """
  1895. with open_repo_closing(repo) as r:
  1896. if isinstance(tagname, str):
  1897. tagname = tagname.encode()
  1898. tag_ref = _make_tag_ref(tagname)
  1899. tag_id = r.refs[tag_ref]
  1900. tag_obj = r[tag_id]
  1901. if not isinstance(tag_obj, Tag):
  1902. raise Error(f"{tagname!r} does not point to a tag object")
  1903. tag_obj.verify(keyids)
  1904. def tag_list(repo: RepoPath, outstream: TextIO = sys.stdout) -> list[bytes]:
  1905. """List all tags.
  1906. Args:
  1907. repo: Path to repository
  1908. outstream: Stream to write tags to
  1909. """
  1910. with open_repo_closing(repo) as r:
  1911. tags = sorted(r.refs.as_dict(b"refs/tags"))
  1912. return tags
  1913. def tag_delete(repo: RepoPath, name: Union[str, bytes]) -> None:
  1914. """Remove a tag.
  1915. Args:
  1916. repo: Path to repository
  1917. name: Name of tag to remove
  1918. """
  1919. with open_repo_closing(repo) as r:
  1920. if isinstance(name, bytes):
  1921. names = [name]
  1922. elif isinstance(name, list):
  1923. names = name
  1924. else:
  1925. raise Error(f"Unexpected tag name type {name!r}")
  1926. for name in names:
  1927. del r.refs[_make_tag_ref(name)]
  1928. def _make_notes_ref(name: bytes) -> bytes:
  1929. """Make a notes ref name."""
  1930. if name.startswith(b"refs/notes/"):
  1931. return name
  1932. return LOCAL_NOTES_PREFIX + name
  1933. def notes_add(
  1934. repo: RepoPath,
  1935. object_sha: bytes,
  1936. note: bytes,
  1937. ref: bytes = b"commits",
  1938. author: Optional[bytes] = None,
  1939. committer: Optional[bytes] = None,
  1940. message: Optional[bytes] = None,
  1941. ) -> bytes:
  1942. """Add or update a note for an object.
  1943. Args:
  1944. repo: Path to repository
  1945. object_sha: SHA of the object to annotate
  1946. note: Note content
  1947. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  1948. author: Author identity (defaults to committer)
  1949. committer: Committer identity (defaults to config)
  1950. message: Commit message for the notes update
  1951. Returns:
  1952. SHA of the new notes commit
  1953. """
  1954. with open_repo_closing(repo) as r:
  1955. # Parse the object to get its SHA
  1956. obj = parse_object(r, object_sha)
  1957. object_sha = obj.id
  1958. if isinstance(note, str):
  1959. note = note.encode(DEFAULT_ENCODING)
  1960. if isinstance(ref, str):
  1961. ref = ref.encode(DEFAULT_ENCODING)
  1962. notes_ref = _make_notes_ref(ref)
  1963. config = r.get_config_stack()
  1964. return r.notes.set_note(
  1965. object_sha,
  1966. note,
  1967. notes_ref,
  1968. author=author,
  1969. committer=committer,
  1970. message=message,
  1971. config=config,
  1972. )
  1973. def notes_remove(
  1974. repo: RepoPath,
  1975. object_sha: bytes,
  1976. ref: bytes = b"commits",
  1977. author: Optional[bytes] = None,
  1978. committer: Optional[bytes] = None,
  1979. message: Optional[bytes] = None,
  1980. ) -> Optional[bytes]:
  1981. """Remove a note for an object.
  1982. Args:
  1983. repo: Path to repository
  1984. object_sha: SHA of the object to remove notes from
  1985. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  1986. author: Author identity (defaults to committer)
  1987. committer: Committer identity (defaults to config)
  1988. message: Commit message for the notes removal
  1989. Returns:
  1990. SHA of the new notes commit, or None if no note existed
  1991. """
  1992. with open_repo_closing(repo) as r:
  1993. # Parse the object to get its SHA
  1994. obj = parse_object(r, object_sha)
  1995. object_sha = obj.id
  1996. if isinstance(ref, str):
  1997. ref = ref.encode(DEFAULT_ENCODING)
  1998. notes_ref = _make_notes_ref(ref)
  1999. config = r.get_config_stack()
  2000. return r.notes.remove_note(
  2001. object_sha,
  2002. notes_ref,
  2003. author=author,
  2004. committer=committer,
  2005. message=message,
  2006. config=config,
  2007. )
  2008. def notes_show(
  2009. repo: Union[str, os.PathLike[str], Repo], object_sha: bytes, ref: bytes = b"commits"
  2010. ) -> Optional[bytes]:
  2011. """Show the note for an object.
  2012. Args:
  2013. repo: Path to repository
  2014. object_sha: SHA of the object
  2015. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  2016. Returns:
  2017. Note content as bytes, or None if no note exists
  2018. """
  2019. with open_repo_closing(repo) as r:
  2020. # Parse the object to get its SHA
  2021. obj = parse_object(r, object_sha)
  2022. object_sha = obj.id
  2023. if isinstance(ref, str):
  2024. ref = ref.encode(DEFAULT_ENCODING)
  2025. notes_ref = _make_notes_ref(ref)
  2026. config = r.get_config_stack()
  2027. return r.notes.get_note(object_sha, notes_ref, config=config)
  2028. def notes_list(repo: RepoPath, ref: bytes = b"commits") -> list[tuple[bytes, bytes]]:
  2029. """List all notes in a notes ref.
  2030. Args:
  2031. repo: Path to repository
  2032. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  2033. Returns:
  2034. List of tuples of (object_sha, note_content)
  2035. """
  2036. with open_repo_closing(repo) as r:
  2037. if isinstance(ref, str):
  2038. ref = ref.encode(DEFAULT_ENCODING)
  2039. notes_ref = _make_notes_ref(ref)
  2040. config = r.get_config_stack()
  2041. return r.notes.list_notes(notes_ref, config=config)
  2042. def reset(
  2043. repo: Union[str, os.PathLike[str], Repo],
  2044. mode: str,
  2045. treeish: Union[str, bytes, Commit, Tree, Tag] = "HEAD",
  2046. ) -> None:
  2047. """Reset current HEAD to the specified state.
  2048. Args:
  2049. repo: Path to repository
  2050. mode: Mode ("hard", "soft", "mixed")
  2051. treeish: Treeish to reset to
  2052. """
  2053. with open_repo_closing(repo) as r:
  2054. # Parse the target tree
  2055. tree = parse_tree(r, treeish)
  2056. # Only parse as commit if treeish is not a Tree object
  2057. if isinstance(treeish, Tree):
  2058. # For Tree objects, we can't determine the commit, skip updating HEAD
  2059. target_commit = None
  2060. else:
  2061. target_commit = parse_commit(r, treeish)
  2062. # Update HEAD to point to the target commit
  2063. if target_commit is not None:
  2064. r.refs[b"HEAD"] = target_commit.id
  2065. if mode == "soft":
  2066. # Soft reset: only update HEAD, leave index and working tree unchanged
  2067. return
  2068. elif mode == "mixed":
  2069. # Mixed reset: update HEAD and index, but leave working tree unchanged
  2070. from .object_store import iter_tree_contents
  2071. # Open the index
  2072. index = r.open_index()
  2073. # Clear the current index
  2074. index.clear()
  2075. # Populate index from the target tree
  2076. for entry in iter_tree_contents(r.object_store, tree.id):
  2077. # Create an IndexEntry from the tree entry
  2078. # Use zeros for filesystem-specific fields since we're not touching the working tree
  2079. assert (
  2080. entry.mode is not None
  2081. and entry.sha is not None
  2082. and entry.path is not None
  2083. )
  2084. index_entry = IndexEntry(
  2085. ctime=(0, 0),
  2086. mtime=(0, 0),
  2087. dev=0,
  2088. ino=0,
  2089. mode=entry.mode,
  2090. uid=0,
  2091. gid=0,
  2092. size=0, # Size will be 0 since we're not reading from disk
  2093. sha=entry.sha,
  2094. flags=0,
  2095. )
  2096. index[entry.path] = index_entry
  2097. # Write the updated index
  2098. index.write()
  2099. elif mode == "hard":
  2100. # Hard reset: update HEAD, index, and working tree
  2101. # Get configuration for working directory update
  2102. config = r.get_config()
  2103. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  2104. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  2105. validate_path_element = validate_path_element_ntfs
  2106. elif config.get_boolean(
  2107. b"core", b"core.protectHFS", sys.platform == "darwin"
  2108. ):
  2109. validate_path_element = validate_path_element_hfs
  2110. else:
  2111. validate_path_element = validate_path_element_default
  2112. if config.get_boolean(b"core", b"symlinks", True):
  2113. def symlink_wrapper(
  2114. source: Union[str, bytes, os.PathLike[str]],
  2115. target: Union[str, bytes, os.PathLike[str]],
  2116. ) -> None:
  2117. symlink(source, target) # type: ignore[arg-type,unused-ignore]
  2118. symlink_fn = symlink_wrapper
  2119. else:
  2120. def symlink_fallback(
  2121. source: Union[str, bytes, os.PathLike[str]],
  2122. target: Union[str, bytes, os.PathLike[str]],
  2123. ) -> None:
  2124. mode = "w" + ("b" if isinstance(source, bytes) else "")
  2125. with open(target, mode) as f:
  2126. f.write(source)
  2127. symlink_fn = symlink_fallback
  2128. # Update working tree and index
  2129. blob_normalizer = r.get_blob_normalizer()
  2130. # For reset --hard, use current index tree as old tree to get proper deletions
  2131. index = r.open_index()
  2132. if len(index) > 0:
  2133. index_tree_id = index.commit(r.object_store)
  2134. else:
  2135. # Empty index
  2136. index_tree_id = None
  2137. changes = tree_changes(
  2138. r.object_store, index_tree_id, tree.id, want_unchanged=True
  2139. )
  2140. update_working_tree(
  2141. r,
  2142. index_tree_id,
  2143. tree.id,
  2144. change_iterator=changes,
  2145. honor_filemode=honor_filemode,
  2146. validate_path_element=validate_path_element,
  2147. symlink_fn=symlink_fn,
  2148. force_remove_untracked=True,
  2149. blob_normalizer=blob_normalizer,
  2150. allow_overwrite_modified=True, # Allow overwriting modified files
  2151. )
  2152. else:
  2153. raise Error(f"Invalid reset mode: {mode}")
  2154. def get_remote_repo(
  2155. repo: Repo, remote_location: Optional[Union[str, bytes]] = None
  2156. ) -> tuple[Optional[str], str]:
  2157. """Get the remote repository information.
  2158. Args:
  2159. repo: Local repository object
  2160. remote_location: Optional remote name or URL; defaults to branch remote
  2161. Returns:
  2162. Tuple of (remote_name, remote_url) where remote_name may be None
  2163. if remote_location is a URL rather than a configured remote
  2164. """
  2165. config = repo.get_config()
  2166. if remote_location is None:
  2167. remote_location = get_branch_remote(repo)
  2168. if isinstance(remote_location, str):
  2169. encoded_location = remote_location.encode()
  2170. else:
  2171. encoded_location = remote_location
  2172. section = (b"remote", encoded_location)
  2173. remote_name: Optional[str] = None
  2174. if config.has_section(section):
  2175. remote_name = encoded_location.decode()
  2176. encoded_location = config.get(section, "url")
  2177. else:
  2178. remote_name = None
  2179. return (remote_name, encoded_location.decode())
  2180. def push(
  2181. repo: RepoPath,
  2182. remote_location: Optional[Union[str, bytes]] = None,
  2183. refspecs: Optional[Union[Union[str, bytes], Sequence[Union[str, bytes]]]] = None,
  2184. outstream: BinaryIO = default_bytes_out_stream,
  2185. errstream: Union[BinaryIO, RawIOBase] = default_bytes_err_stream,
  2186. force: bool = False,
  2187. **kwargs: object,
  2188. ) -> SendPackResult:
  2189. """Remote push with dulwich via dulwich.client.
  2190. Args:
  2191. repo: Path to repository
  2192. remote_location: Location of the remote
  2193. refspecs: Refs to push to remote
  2194. outstream: A stream file to write output
  2195. errstream: A stream file to write errors
  2196. force: Force overwriting refs
  2197. **kwargs: Additional keyword arguments for the client
  2198. """
  2199. # Open the repo
  2200. with open_repo_closing(repo) as r:
  2201. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  2202. # Check if mirror mode is enabled
  2203. mirror_mode = False
  2204. if remote_name:
  2205. try:
  2206. mirror_mode_val = r.get_config_stack().get_boolean(
  2207. (b"remote", remote_name.encode()), b"mirror"
  2208. )
  2209. if mirror_mode_val is not None:
  2210. mirror_mode = mirror_mode_val
  2211. except KeyError:
  2212. pass
  2213. if mirror_mode:
  2214. # Mirror mode: push all refs and delete non-existent ones
  2215. refspecs = []
  2216. for ref in r.refs.keys():
  2217. # Push all refs to the same name on remote
  2218. refspecs.append(ref + b":" + ref)
  2219. elif refspecs is None:
  2220. refspecs = [active_branch(r)]
  2221. # Normalize refspecs to bytes
  2222. if isinstance(refspecs, str):
  2223. refspecs_bytes: Union[bytes, list[bytes]] = refspecs.encode()
  2224. elif isinstance(refspecs, bytes):
  2225. refspecs_bytes = refspecs
  2226. else:
  2227. refspecs_bytes = []
  2228. for spec in refspecs:
  2229. if isinstance(spec, str):
  2230. refspecs_bytes.append(spec.encode())
  2231. else:
  2232. refspecs_bytes.append(spec)
  2233. # Get the client and path
  2234. client, path = get_transport_and_path(
  2235. remote_location,
  2236. config=r.get_config_stack(),
  2237. **kwargs, # type: ignore[arg-type]
  2238. )
  2239. selected_refs = []
  2240. remote_changed_refs: dict[bytes, Optional[bytes]] = {}
  2241. def update_refs(refs: dict[bytes, bytes]) -> dict[bytes, bytes]:
  2242. from .refs import DictRefsContainer
  2243. remote_refs = DictRefsContainer(refs)
  2244. selected_refs.extend(
  2245. parse_reftuples(r.refs, remote_refs, refspecs_bytes, force=force)
  2246. )
  2247. new_refs = {}
  2248. # In mirror mode, delete remote refs that don't exist locally
  2249. if mirror_mode:
  2250. local_refs = set(r.refs.keys())
  2251. for remote_ref in refs.keys():
  2252. if remote_ref not in local_refs:
  2253. new_refs[remote_ref] = ZERO_SHA
  2254. remote_changed_refs[remote_ref] = None
  2255. # TODO: Handle selected_refs == {None: None}
  2256. for lh, rh, force_ref in selected_refs:
  2257. if lh is None:
  2258. assert rh is not None
  2259. new_refs[rh] = ZERO_SHA
  2260. remote_changed_refs[rh] = None
  2261. else:
  2262. try:
  2263. localsha = r.refs[lh]
  2264. except KeyError as exc:
  2265. raise Error(
  2266. f"No valid ref {lh.decode() if isinstance(lh, bytes) else lh} in local repository"
  2267. ) from exc
  2268. assert rh is not None
  2269. if not force_ref and rh in refs:
  2270. check_diverged(r, refs[rh], localsha)
  2271. new_refs[rh] = localsha
  2272. remote_changed_refs[rh] = localsha
  2273. return new_refs
  2274. err_encoding = getattr(errstream, "encoding", None) or DEFAULT_ENCODING
  2275. remote_location = client.get_url(path)
  2276. try:
  2277. def generate_pack_data_wrapper(
  2278. have: AbstractSet[bytes],
  2279. want: AbstractSet[bytes],
  2280. ofs_delta: bool = False,
  2281. ) -> tuple[int, Iterator[UnpackedObject]]:
  2282. # Wrap to match the expected signature
  2283. # Convert AbstractSet to set since generate_pack_data expects set
  2284. return r.generate_pack_data(
  2285. set(have), set(want), progress=None, ofs_delta=ofs_delta
  2286. )
  2287. result = client.send_pack(
  2288. path.encode(),
  2289. update_refs,
  2290. generate_pack_data=generate_pack_data_wrapper,
  2291. progress=lambda data: (errstream.write(data), None)[1],
  2292. )
  2293. except SendPackError as exc:
  2294. raise Error(
  2295. "Push to " + remote_location + " failed -> " + exc.args[0].decode(),
  2296. ) from exc
  2297. else:
  2298. errstream.write(
  2299. b"Push to " + remote_location.encode(err_encoding) + b" successful.\n"
  2300. )
  2301. for ref, error in (result.ref_status or {}).items():
  2302. if error is not None:
  2303. errstream.write(
  2304. b"Push of ref %s failed: %s\n" % (ref, error.encode(err_encoding))
  2305. )
  2306. else:
  2307. errstream.write(b"Ref %s updated\n" % ref)
  2308. if remote_name is not None:
  2309. _import_remote_refs(r.refs, remote_name, remote_changed_refs)
  2310. return result
  2311. # Trigger auto GC if needed
  2312. from .gc import maybe_auto_gc
  2313. with open_repo_closing(repo) as r:
  2314. maybe_auto_gc(r)
  2315. def pull(
  2316. repo: RepoPath,
  2317. remote_location: Optional[Union[str, bytes]] = None,
  2318. refspecs: Optional[Union[Union[str, bytes], Sequence[Union[str, bytes]]]] = None,
  2319. outstream: BinaryIO = default_bytes_out_stream,
  2320. errstream: Union[BinaryIO, RawIOBase] = default_bytes_err_stream,
  2321. fast_forward: bool = True,
  2322. ff_only: bool = False,
  2323. force: bool = False,
  2324. filter_spec: Optional[str] = None,
  2325. protocol_version: Optional[int] = None,
  2326. **kwargs: object,
  2327. ) -> None:
  2328. """Pull from remote via dulwich.client.
  2329. Args:
  2330. repo: Path to repository
  2331. remote_location: Location of the remote
  2332. refspecs: refspecs to fetch. Can be a bytestring, a string, or a list of
  2333. bytestring/string.
  2334. outstream: A stream file to write to output
  2335. errstream: A stream file to write to errors
  2336. fast_forward: If True, raise an exception when fast-forward is not possible
  2337. ff_only: If True, only allow fast-forward merges. Raises DivergedBranches
  2338. when branches have diverged rather than performing a merge.
  2339. force: If True, allow overwriting local changes in the working tree.
  2340. If False, pull will abort if it would overwrite uncommitted changes.
  2341. filter_spec: A git-rev-list-style object filter spec, as an ASCII string.
  2342. Only used if the server supports the Git protocol-v2 'filter'
  2343. feature, and ignored otherwise.
  2344. protocol_version: desired Git protocol version. By default the highest
  2345. mutually supported protocol version will be used
  2346. **kwargs: Additional keyword arguments for the client
  2347. """
  2348. # Open the repo
  2349. with open_repo_closing(repo) as r:
  2350. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  2351. selected_refs = []
  2352. if refspecs is None:
  2353. refspecs_normalized: Union[bytes, list[bytes]] = [b"HEAD"]
  2354. elif isinstance(refspecs, str):
  2355. refspecs_normalized = refspecs.encode()
  2356. elif isinstance(refspecs, bytes):
  2357. refspecs_normalized = refspecs
  2358. else:
  2359. refspecs_normalized = []
  2360. for spec in refspecs:
  2361. if isinstance(spec, str):
  2362. refspecs_normalized.append(spec.encode())
  2363. else:
  2364. refspecs_normalized.append(spec)
  2365. def determine_wants(
  2366. remote_refs: dict[bytes, bytes], depth: Optional[int] = None
  2367. ) -> list[bytes]:
  2368. from .refs import DictRefsContainer
  2369. remote_refs_container = DictRefsContainer(remote_refs)
  2370. selected_refs.extend(
  2371. parse_reftuples(
  2372. remote_refs_container, r.refs, refspecs_normalized, force=force
  2373. )
  2374. )
  2375. return [
  2376. remote_refs[lh]
  2377. for (lh, rh, force_ref) in selected_refs
  2378. if lh is not None
  2379. and lh in remote_refs
  2380. and remote_refs[lh] not in r.object_store
  2381. ]
  2382. client, path = get_transport_and_path(
  2383. remote_location,
  2384. config=r.get_config_stack(),
  2385. **kwargs, # type: ignore[arg-type]
  2386. )
  2387. if filter_spec:
  2388. filter_spec_bytes: Optional[bytes] = filter_spec.encode("ascii")
  2389. else:
  2390. filter_spec_bytes = None
  2391. def progress(data: bytes) -> None:
  2392. errstream.write(data)
  2393. fetch_result = client.fetch(
  2394. path.encode(),
  2395. r,
  2396. progress=progress,
  2397. determine_wants=determine_wants, # type: ignore[arg-type] # Function matches protocol but mypy can't verify
  2398. filter_spec=filter_spec_bytes,
  2399. protocol_version=protocol_version,
  2400. )
  2401. # Store the old HEAD tree before making changes
  2402. try:
  2403. old_head = r.refs[b"HEAD"]
  2404. old_commit = r[old_head]
  2405. assert isinstance(old_commit, Commit)
  2406. old_tree_id = old_commit.tree
  2407. except KeyError:
  2408. old_tree_id = None
  2409. merged = False
  2410. for lh, rh, force_ref in selected_refs:
  2411. if not force_ref and rh is not None and rh in r.refs:
  2412. try:
  2413. assert lh is not None
  2414. followed_ref = r.refs.follow(rh)[1]
  2415. assert followed_ref is not None
  2416. lh_ref = fetch_result.refs[lh]
  2417. assert lh_ref is not None
  2418. check_diverged(r, followed_ref, lh_ref)
  2419. except DivergedBranches as exc:
  2420. if ff_only or fast_forward:
  2421. raise
  2422. else:
  2423. # Perform merge
  2424. assert lh is not None
  2425. merge_ref = fetch_result.refs[lh]
  2426. assert merge_ref is not None
  2427. _merge_result, conflicts = _do_merge(r, merge_ref)
  2428. if conflicts:
  2429. raise Error(
  2430. f"Merge conflicts occurred: {conflicts}"
  2431. ) from exc
  2432. merged = True
  2433. # Skip updating ref since merge already updated HEAD
  2434. continue
  2435. if rh is not None and lh is not None:
  2436. lh_value = fetch_result.refs[lh]
  2437. if lh_value is not None:
  2438. r.refs[rh] = lh_value
  2439. # Only update HEAD if we didn't perform a merge
  2440. if selected_refs and not merged:
  2441. lh, rh, _ = selected_refs[0]
  2442. if lh is not None:
  2443. ref_value = fetch_result.refs[lh]
  2444. if ref_value is not None:
  2445. r[b"HEAD"] = ref_value
  2446. # Update working tree to match the new HEAD
  2447. # Skip if merge was performed as merge already updates the working tree
  2448. if not merged and old_tree_id is not None:
  2449. head_commit = r[b"HEAD"]
  2450. assert isinstance(head_commit, Commit)
  2451. new_tree_id = head_commit.tree
  2452. blob_normalizer = r.get_blob_normalizer()
  2453. changes = tree_changes(r.object_store, old_tree_id, new_tree_id)
  2454. update_working_tree(
  2455. r,
  2456. old_tree_id,
  2457. new_tree_id,
  2458. change_iterator=changes,
  2459. blob_normalizer=blob_normalizer,
  2460. allow_overwrite_modified=force,
  2461. )
  2462. if remote_name is not None:
  2463. _import_remote_refs(r.refs, remote_name, fetch_result.refs)
  2464. # Trigger auto GC if needed
  2465. from .gc import maybe_auto_gc
  2466. with open_repo_closing(repo) as r:
  2467. maybe_auto_gc(r)
  2468. def status(
  2469. repo: Union[str, os.PathLike[str], Repo] = ".",
  2470. ignored: bool = False,
  2471. untracked_files: str = "normal",
  2472. ) -> GitStatus:
  2473. """Returns staged, unstaged, and untracked changes relative to the HEAD.
  2474. Args:
  2475. repo: Path to repository or repository object
  2476. ignored: Whether to include ignored files in untracked
  2477. untracked_files: How to handle untracked files, defaults to "all":
  2478. "no": do not return untracked files
  2479. "normal": return untracked directories, not their contents
  2480. "all": include all files in untracked directories
  2481. Using untracked_files="no" can be faster than "all" when the worktree
  2482. contains many untracked files/directories.
  2483. Using untracked_files="normal" provides a good balance, only showing
  2484. directories that are entirely untracked without listing all their contents.
  2485. Returns: GitStatus tuple,
  2486. staged - dict with lists of staged paths (diff index/HEAD)
  2487. unstaged - list of unstaged paths (diff index/working-tree)
  2488. untracked - list of untracked, un-ignored & non-.git paths
  2489. """
  2490. with open_repo_closing(repo) as r:
  2491. # 1. Get status of staged
  2492. tracked_changes = get_tree_changes(r)
  2493. # 2. Get status of unstaged
  2494. index = r.open_index()
  2495. normalizer = r.get_blob_normalizer()
  2496. # Create a wrapper that handles the bytes -> Blob conversion
  2497. if normalizer is not None:
  2498. def filter_callback(data: bytes, path: bytes) -> bytes:
  2499. from dulwich.objects import Blob
  2500. blob = Blob()
  2501. blob.data = data
  2502. normalized_blob = normalizer.checkin_normalize(blob, path)
  2503. result_data: bytes = normalized_blob.data
  2504. return result_data
  2505. else:
  2506. filter_callback = None
  2507. # Check if core.preloadIndex is enabled
  2508. config = r.get_config_stack()
  2509. preload_index = config.get_boolean(b"core", b"preloadIndex", False)
  2510. unstaged_changes = list(
  2511. get_unstaged_changes(index, r.path, filter_callback, preload_index)
  2512. )
  2513. untracked_paths = get_untracked_paths(
  2514. r.path,
  2515. r.path,
  2516. index,
  2517. exclude_ignored=not ignored,
  2518. untracked_files=untracked_files,
  2519. )
  2520. if sys.platform == "win32":
  2521. untracked_changes = [
  2522. path.replace(os.path.sep, "/") for path in untracked_paths
  2523. ]
  2524. else:
  2525. untracked_changes = list(untracked_paths)
  2526. return GitStatus(tracked_changes, unstaged_changes, untracked_changes)
  2527. def shortlog(
  2528. repo: Union[str, os.PathLike[str], Repo],
  2529. summary_only: bool = False,
  2530. sort_by_commits: bool = False,
  2531. ) -> list[dict[str, str]]:
  2532. """Summarize commits by author, like git shortlog.
  2533. Args:
  2534. repo: Path to repository or Repo object.
  2535. summary_only: If True, only show counts per author.
  2536. sort_by_commits: If True, sort authors by number of commits.
  2537. Returns:
  2538. A list of dictionaries, each containing:
  2539. - "author": the author's name as a string
  2540. - "messages": all commit messages concatenated into a single string
  2541. """
  2542. with open_repo_closing(repo) as r:
  2543. walker = r.get_walker()
  2544. authors: dict[str, list[str]] = {}
  2545. for entry in walker:
  2546. commit = entry.commit
  2547. author = commit.author.decode(commit.encoding or "utf-8")
  2548. message = commit.message.decode(commit.encoding or "utf-8").strip()
  2549. authors.setdefault(author, []).append(message)
  2550. # Convert messages to single string per author
  2551. items: list[dict[str, str]] = [
  2552. {"author": author, "messages": "\n".join(msgs)}
  2553. for author, msgs in authors.items()
  2554. ]
  2555. if sort_by_commits:
  2556. # Sort by number of commits (lines in messages)
  2557. items.sort(key=lambda x: len(x["messages"].splitlines()), reverse=True)
  2558. return items
  2559. def _walk_working_dir_paths(
  2560. frompath: Union[str, bytes, os.PathLike[str]],
  2561. basepath: Union[str, bytes, os.PathLike[str]],
  2562. prune_dirnames: Optional[Callable[[str, list[str]], list[str]]] = None,
  2563. ) -> Iterator[tuple[Union[str, bytes], bool]]:
  2564. """Get path, is_dir for files in working dir from frompath.
  2565. Args:
  2566. frompath: Path to begin walk
  2567. basepath: Path to compare to
  2568. prune_dirnames: Optional callback to prune dirnames during os.walk
  2569. dirnames will be set to result of prune_dirnames(dirpath, dirnames)
  2570. """
  2571. # Convert paths to strings for os.walk compatibility
  2572. for dirpath, dirnames, filenames in os.walk(frompath): # type: ignore[type-var]
  2573. # Skip .git and below.
  2574. if ".git" in dirnames:
  2575. dirnames.remove(".git")
  2576. if dirpath != basepath:
  2577. continue
  2578. if ".git" in filenames:
  2579. filenames.remove(".git")
  2580. if dirpath != basepath:
  2581. continue
  2582. if dirpath != frompath:
  2583. yield dirpath, True # type: ignore[misc]
  2584. for filename in filenames:
  2585. filepath = os.path.join(dirpath, filename) # type: ignore[call-overload]
  2586. yield filepath, False
  2587. if prune_dirnames:
  2588. dirnames[:] = prune_dirnames(dirpath, dirnames) # type: ignore[arg-type]
  2589. def get_untracked_paths(
  2590. frompath: Union[str, bytes, os.PathLike[str]],
  2591. basepath: Union[str, bytes, os.PathLike[str]],
  2592. index: Index,
  2593. exclude_ignored: bool = False,
  2594. untracked_files: str = "all",
  2595. ) -> Iterator[str]:
  2596. """Get untracked paths.
  2597. Args:
  2598. frompath: Path to walk
  2599. basepath: Path to compare to
  2600. index: Index to check against
  2601. exclude_ignored: Whether to exclude ignored paths
  2602. untracked_files: How to handle untracked files:
  2603. - "no": return an empty list
  2604. - "all": return all files in untracked directories
  2605. - "normal": return untracked directories without listing their contents
  2606. Note: ignored directories will never be walked for performance reasons.
  2607. If exclude_ignored is False, only the path to an ignored directory will
  2608. be yielded, no files inside the directory will be returned
  2609. """
  2610. if untracked_files not in ("no", "all", "normal"):
  2611. raise ValueError("untracked_files must be one of (no, all, normal)")
  2612. if untracked_files == "no":
  2613. return
  2614. # Normalize paths to str
  2615. frompath_str = os.fsdecode(os.fspath(frompath))
  2616. basepath_str = os.fsdecode(os.fspath(basepath))
  2617. with open_repo_closing(basepath_str) as r:
  2618. ignore_manager = IgnoreFilterManager.from_repo(r)
  2619. ignored_dirs = []
  2620. # List to store untracked directories found during traversal
  2621. untracked_dir_list = []
  2622. def directory_has_non_ignored_files(dir_path: str, base_rel_path: str) -> bool:
  2623. """Recursively check if directory contains any non-ignored files."""
  2624. try:
  2625. for entry in os.listdir(dir_path):
  2626. entry_path = os.path.join(dir_path, entry)
  2627. rel_entry = os.path.join(base_rel_path, entry)
  2628. if os.path.isfile(entry_path):
  2629. if ignore_manager.is_ignored(rel_entry) is not True:
  2630. return True
  2631. elif os.path.isdir(entry_path):
  2632. if directory_has_non_ignored_files(entry_path, rel_entry):
  2633. return True
  2634. return False
  2635. except OSError:
  2636. # If we can't read the directory, assume it has non-ignored files
  2637. return True
  2638. def prune_dirnames(dirpath: str, dirnames: list[str]) -> list[str]:
  2639. for i in range(len(dirnames) - 1, -1, -1):
  2640. path = os.path.join(dirpath, dirnames[i])
  2641. ip = os.path.join(os.path.relpath(path, basepath_str), "")
  2642. # Check if directory is ignored
  2643. if ignore_manager.is_ignored(ip) is True:
  2644. if not exclude_ignored:
  2645. ignored_dirs.append(
  2646. os.path.join(os.path.relpath(path, frompath_str), "")
  2647. )
  2648. del dirnames[i]
  2649. continue
  2650. # For "normal" mode, check if the directory is entirely untracked
  2651. if untracked_files == "normal":
  2652. # Convert directory path to tree path for index lookup
  2653. dir_tree_path = path_to_tree_path(basepath_str, path)
  2654. # Check if any file in this directory is tracked
  2655. dir_prefix = dir_tree_path + b"/" if dir_tree_path else b""
  2656. has_tracked_files = any(name.startswith(dir_prefix) for name in index)
  2657. if not has_tracked_files:
  2658. # This directory is entirely untracked
  2659. rel_path_base = os.path.relpath(path, basepath_str)
  2660. rel_path_from = os.path.join(
  2661. os.path.relpath(path, frompath_str), ""
  2662. )
  2663. # If excluding ignored, check if directory contains any non-ignored files
  2664. if exclude_ignored:
  2665. if not directory_has_non_ignored_files(path, rel_path_base):
  2666. # Directory only contains ignored files, skip it
  2667. del dirnames[i]
  2668. continue
  2669. # Check if it should be excluded due to ignore rules
  2670. is_ignored = ignore_manager.is_ignored(rel_path_base)
  2671. if not exclude_ignored or not is_ignored:
  2672. untracked_dir_list.append(rel_path_from)
  2673. del dirnames[i]
  2674. return dirnames
  2675. # For "all" mode, use the original behavior
  2676. if untracked_files == "all":
  2677. for ap, is_dir in _walk_working_dir_paths(
  2678. frompath_str, basepath_str, prune_dirnames=prune_dirnames
  2679. ):
  2680. # frompath_str and basepath_str are both str, so ap must be str
  2681. assert isinstance(ap, str)
  2682. if not is_dir:
  2683. ip = path_to_tree_path(basepath_str, ap)
  2684. if ip not in index:
  2685. if not exclude_ignored or not ignore_manager.is_ignored(
  2686. os.path.relpath(ap, basepath_str)
  2687. ):
  2688. yield os.path.relpath(ap, frompath_str)
  2689. else: # "normal" mode
  2690. # Walk directories, handling both files and directories
  2691. for ap, is_dir in _walk_working_dir_paths(
  2692. frompath_str, basepath_str, prune_dirnames=prune_dirnames
  2693. ):
  2694. # frompath_str and basepath_str are both str, so ap must be str
  2695. assert isinstance(ap, str)
  2696. # This part won't be reached for pruned directories
  2697. if is_dir:
  2698. # Check if this directory is entirely untracked
  2699. dir_tree_path = path_to_tree_path(basepath_str, ap)
  2700. dir_prefix = dir_tree_path + b"/" if dir_tree_path else b""
  2701. has_tracked_files = any(name.startswith(dir_prefix) for name in index)
  2702. if not has_tracked_files:
  2703. if not exclude_ignored or not ignore_manager.is_ignored(
  2704. os.path.relpath(ap, basepath_str)
  2705. ):
  2706. yield os.path.join(os.path.relpath(ap, frompath_str), "")
  2707. else:
  2708. # Check individual files in directories that contain tracked files
  2709. ip = path_to_tree_path(basepath_str, ap)
  2710. if ip not in index:
  2711. if not exclude_ignored or not ignore_manager.is_ignored(
  2712. os.path.relpath(ap, basepath_str)
  2713. ):
  2714. yield os.path.relpath(ap, frompath_str)
  2715. # Yield any untracked directories found during pruning
  2716. yield from untracked_dir_list
  2717. yield from ignored_dirs
  2718. def get_tree_changes(repo: RepoPath) -> dict[str, list[Union[str, bytes]]]:
  2719. """Return add/delete/modify changes to tree by comparing index to HEAD.
  2720. Args:
  2721. repo: repo path or object
  2722. Returns: dict with lists for each type of change
  2723. """
  2724. with open_repo_closing(repo) as r:
  2725. index = r.open_index()
  2726. # Compares the Index to the HEAD & determines changes
  2727. # Iterate through the changes and report add/delete/modify
  2728. # TODO: call out to dulwich.diff_tree somehow.
  2729. tracked_changes: dict[str, list[Union[str, bytes]]] = {
  2730. "add": [],
  2731. "delete": [],
  2732. "modify": [],
  2733. }
  2734. try:
  2735. head_commit = r[b"HEAD"]
  2736. assert isinstance(head_commit, Commit)
  2737. tree_id = head_commit.tree
  2738. except KeyError:
  2739. tree_id = None
  2740. for change in index.changes_from_tree(r.object_store, tree_id):
  2741. if not change[0][0]:
  2742. assert change[0][1] is not None
  2743. tracked_changes["add"].append(change[0][1])
  2744. elif not change[0][1]:
  2745. assert change[0][0] is not None
  2746. tracked_changes["delete"].append(change[0][0])
  2747. elif change[0][0] == change[0][1]:
  2748. assert change[0][0] is not None
  2749. tracked_changes["modify"].append(change[0][0])
  2750. else:
  2751. raise NotImplementedError("git mv ops not yet supported")
  2752. return tracked_changes
  2753. def daemon(
  2754. path: Union[str, os.PathLike[str]] = ".",
  2755. address: Optional[str] = None,
  2756. port: Optional[int] = None,
  2757. ) -> None:
  2758. """Run a daemon serving Git requests over TCP/IP.
  2759. Args:
  2760. path: Path to the directory to serve.
  2761. address: Optional address to listen on (defaults to ::)
  2762. port: Optional port to listen on (defaults to TCP_GIT_PORT)
  2763. """
  2764. # TODO(jelmer): Support git-daemon-export-ok and --export-all.
  2765. backend = FileSystemBackend(os.fspath(path))
  2766. server = TCPGitServer(backend, address or "localhost", port or 9418)
  2767. server.serve_forever()
  2768. def web_daemon(
  2769. path: Union[str, os.PathLike[str]] = ".",
  2770. address: Optional[str] = None,
  2771. port: Optional[int] = None,
  2772. ) -> None:
  2773. """Run a daemon serving Git requests over HTTP.
  2774. Args:
  2775. path: Path to the directory to serve
  2776. address: Optional address to listen on (defaults to ::)
  2777. port: Optional port to listen on (defaults to 80)
  2778. """
  2779. from .web import (
  2780. WSGIRequestHandlerLogger,
  2781. WSGIServerLogger,
  2782. make_server,
  2783. make_wsgi_chain,
  2784. )
  2785. backend = FileSystemBackend(os.fspath(path))
  2786. app = make_wsgi_chain(backend)
  2787. server = make_server(
  2788. address or "::",
  2789. port or 80,
  2790. app,
  2791. handler_class=WSGIRequestHandlerLogger,
  2792. server_class=WSGIServerLogger,
  2793. )
  2794. server.serve_forever()
  2795. def upload_pack(
  2796. path: Union[str, os.PathLike[str]] = ".",
  2797. inf: Optional[BinaryIO] = None,
  2798. outf: Optional[BinaryIO] = None,
  2799. ) -> int:
  2800. """Upload a pack file after negotiating its contents using smart protocol.
  2801. Args:
  2802. path: Path to the repository
  2803. inf: Input stream to communicate with client
  2804. outf: Output stream to communicate with client
  2805. """
  2806. if outf is None:
  2807. outf = sys.stdout.buffer
  2808. if inf is None:
  2809. inf = sys.stdin.buffer
  2810. assert outf is not None
  2811. assert inf is not None
  2812. path = os.path.expanduser(path)
  2813. backend = FileSystemBackend(path)
  2814. def send_fn(data: bytes) -> None:
  2815. outf.write(data)
  2816. outf.flush()
  2817. proto = Protocol(inf.read, send_fn)
  2818. handler = UploadPackHandler(backend, [path], proto)
  2819. # FIXME: Catch exceptions and write a single-line summary to outf.
  2820. handler.handle()
  2821. return 0
  2822. def receive_pack(
  2823. path: Union[str, os.PathLike[str]] = ".",
  2824. inf: Optional[BinaryIO] = None,
  2825. outf: Optional[BinaryIO] = None,
  2826. ) -> int:
  2827. """Receive a pack file after negotiating its contents using smart protocol.
  2828. Args:
  2829. path: Path to the repository
  2830. inf: Input stream to communicate with client
  2831. outf: Output stream to communicate with client
  2832. """
  2833. if outf is None:
  2834. outf = sys.stdout.buffer
  2835. if inf is None:
  2836. inf = sys.stdin.buffer
  2837. assert outf is not None
  2838. assert inf is not None
  2839. path = os.path.expanduser(path)
  2840. backend = FileSystemBackend(path)
  2841. def send_fn(data: bytes) -> None:
  2842. outf.write(data)
  2843. outf.flush()
  2844. proto = Protocol(inf.read, send_fn)
  2845. handler = ReceivePackHandler(backend, [path], proto)
  2846. # FIXME: Catch exceptions and write a single-line summary to outf.
  2847. handler.handle()
  2848. return 0
  2849. def _make_branch_ref(name: Union[str, bytes]) -> Ref:
  2850. if isinstance(name, str):
  2851. name = name.encode(DEFAULT_ENCODING)
  2852. return LOCAL_BRANCH_PREFIX + name
  2853. def _make_tag_ref(name: Union[str, bytes]) -> Ref:
  2854. if isinstance(name, str):
  2855. name = name.encode(DEFAULT_ENCODING)
  2856. return LOCAL_TAG_PREFIX + name
  2857. def branch_delete(
  2858. repo: RepoPath, name: Union[str, bytes, Sequence[Union[str, bytes]]]
  2859. ) -> None:
  2860. """Delete a branch.
  2861. Args:
  2862. repo: Path to the repository
  2863. name: Name of the branch
  2864. """
  2865. with open_repo_closing(repo) as r:
  2866. if isinstance(name, (list, tuple)):
  2867. names = name
  2868. else:
  2869. names = [name]
  2870. for branch_name in names:
  2871. del r.refs[_make_branch_ref(branch_name)]
  2872. def branch_create(
  2873. repo: Union[str, os.PathLike[str], Repo],
  2874. name: Union[str, bytes],
  2875. objectish: Optional[Union[str, bytes]] = None,
  2876. force: bool = False,
  2877. ) -> None:
  2878. """Create a branch.
  2879. Args:
  2880. repo: Path to the repository
  2881. name: Name of the new branch
  2882. objectish: Target object to point new branch at (defaults to HEAD)
  2883. force: Force creation of branch, even if it already exists
  2884. """
  2885. with open_repo_closing(repo) as r:
  2886. if objectish is None:
  2887. objectish = "HEAD"
  2888. # Try to expand branch shorthand before parsing
  2889. original_objectish = objectish
  2890. objectish_bytes = (
  2891. objectish.encode(DEFAULT_ENCODING)
  2892. if isinstance(objectish, str)
  2893. else objectish
  2894. )
  2895. if b"refs/remotes/" + objectish_bytes in r.refs:
  2896. objectish = b"refs/remotes/" + objectish_bytes
  2897. elif b"refs/heads/" + objectish_bytes in r.refs:
  2898. objectish = b"refs/heads/" + objectish_bytes
  2899. object = parse_object(r, objectish)
  2900. refname = _make_branch_ref(name)
  2901. ref_message = (
  2902. b"branch: Created from " + original_objectish.encode(DEFAULT_ENCODING)
  2903. if isinstance(original_objectish, str)
  2904. else b"branch: Created from " + original_objectish
  2905. )
  2906. if force:
  2907. r.refs.set_if_equals(refname, None, object.id, message=ref_message)
  2908. else:
  2909. if not r.refs.add_if_new(refname, object.id, message=ref_message):
  2910. name_str = name.decode() if isinstance(name, bytes) else name
  2911. raise Error(f"Branch with name {name_str} already exists.")
  2912. # Check if we should set up tracking
  2913. config = r.get_config_stack()
  2914. try:
  2915. auto_setup_merge = config.get((b"branch",), b"autoSetupMerge").decode()
  2916. except KeyError:
  2917. auto_setup_merge = "true" # Default value
  2918. # Determine if the objectish refers to a remote-tracking branch
  2919. objectish_ref = None
  2920. if original_objectish != "HEAD":
  2921. # Try to resolve objectish as a ref
  2922. objectish_bytes = (
  2923. original_objectish.encode(DEFAULT_ENCODING)
  2924. if isinstance(original_objectish, str)
  2925. else original_objectish
  2926. )
  2927. if objectish_bytes in r.refs:
  2928. objectish_ref = objectish_bytes
  2929. elif b"refs/remotes/" + objectish_bytes in r.refs:
  2930. objectish_ref = b"refs/remotes/" + objectish_bytes
  2931. elif b"refs/heads/" + objectish_bytes in r.refs:
  2932. objectish_ref = b"refs/heads/" + objectish_bytes
  2933. else:
  2934. # HEAD might point to a remote-tracking branch
  2935. head_ref = r.refs.follow(b"HEAD")[0][1]
  2936. if head_ref.startswith(b"refs/remotes/"):
  2937. objectish_ref = head_ref
  2938. # Set up tracking if appropriate
  2939. if objectish_ref and (
  2940. (auto_setup_merge == "always")
  2941. or (
  2942. auto_setup_merge == "true"
  2943. and objectish_ref.startswith(b"refs/remotes/")
  2944. )
  2945. ):
  2946. # Extract remote name and branch from the ref
  2947. if objectish_ref.startswith(b"refs/remotes/"):
  2948. parts = objectish_ref[len(b"refs/remotes/") :].split(b"/", 1)
  2949. if len(parts) == 2:
  2950. remote_name = parts[0]
  2951. remote_branch = b"refs/heads/" + parts[1]
  2952. # Set up tracking
  2953. repo_config = r.get_config()
  2954. branch_name_bytes = (
  2955. name.encode(DEFAULT_ENCODING) if isinstance(name, str) else name
  2956. )
  2957. repo_config.set(
  2958. (b"branch", branch_name_bytes), b"remote", remote_name
  2959. )
  2960. repo_config.set(
  2961. (b"branch", branch_name_bytes), b"merge", remote_branch
  2962. )
  2963. repo_config.write_to_path()
  2964. def filter_branches_by_pattern(branches: Iterable[bytes], pattern: str) -> list[bytes]:
  2965. """Filter branches by fnmatch pattern.
  2966. Args:
  2967. branches: Iterable of branch names as bytes
  2968. pattern: Pattern to match against
  2969. Returns:
  2970. List of filtered branch names
  2971. """
  2972. return [
  2973. branch for branch in branches if fnmatch.fnmatchcase(branch.decode(), pattern)
  2974. ]
  2975. def branch_list(repo: RepoPath) -> list[bytes]:
  2976. """List all branches.
  2977. Args:
  2978. repo: Path to the repository
  2979. Returns:
  2980. List of branch names (without refs/heads/ prefix)
  2981. """
  2982. with open_repo_closing(repo) as r:
  2983. branches = list(r.refs.keys(base=LOCAL_BRANCH_PREFIX))
  2984. # Check for branch.sort configuration
  2985. config = r.get_config_stack()
  2986. try:
  2987. sort_key = config.get((b"branch",), b"sort").decode()
  2988. except KeyError:
  2989. # Default is refname (alphabetical)
  2990. sort_key = "refname"
  2991. # Parse sort key
  2992. reverse = False
  2993. if sort_key.startswith("-"):
  2994. reverse = True
  2995. sort_key = sort_key[1:]
  2996. # Apply sorting
  2997. if sort_key == "refname":
  2998. # Simple alphabetical sort (default)
  2999. branches.sort(reverse=reverse)
  3000. elif sort_key in ("committerdate", "authordate"):
  3001. # Sort by date
  3002. def get_commit_date(branch_name: bytes) -> int:
  3003. ref = LOCAL_BRANCH_PREFIX + branch_name
  3004. sha = r.refs[ref]
  3005. commit = r.object_store[sha]
  3006. assert isinstance(commit, Commit)
  3007. if sort_key == "committerdate":
  3008. return cast(int, commit.commit_time)
  3009. else: # authordate
  3010. return cast(int, commit.author_time)
  3011. # Sort branches by date
  3012. # Note: Python's sort naturally orders smaller values first (ascending)
  3013. # For dates, this means oldest first by default
  3014. # Use a stable sort with branch name as secondary key for consistent ordering
  3015. if reverse:
  3016. # For reverse sort, we want newest dates first but alphabetical names second
  3017. branches.sort(key=lambda b: (-get_commit_date(b), b))
  3018. else:
  3019. branches.sort(key=lambda b: (get_commit_date(b), b))
  3020. else:
  3021. # Unknown sort key, fall back to default
  3022. branches.sort()
  3023. return branches
  3024. def branch_remotes_list(repo: RepoPath) -> list[bytes]:
  3025. """List the short names of all remote branches.
  3026. Args:
  3027. repo: Path to the repository
  3028. Returns:
  3029. List of branch names (without refs/remotes/ prefix, and without remote name; e.g. 'main' from 'origin/main')
  3030. """
  3031. with open_repo_closing(repo) as r:
  3032. branches = list(r.refs.keys(base=LOCAL_REMOTE_PREFIX))
  3033. config = r.get_config_stack()
  3034. try:
  3035. sort_key = config.get((b"branch",), b"sort").decode()
  3036. except KeyError:
  3037. # Default is refname (alphabetical)
  3038. sort_key = "refname"
  3039. # Parse sort key
  3040. reverse = False
  3041. if sort_key.startswith("-"):
  3042. reverse = True
  3043. sort_key = sort_key[1:]
  3044. # Apply sorting
  3045. if sort_key == "refname":
  3046. # Simple alphabetical sort (default)
  3047. branches.sort(reverse=reverse)
  3048. elif sort_key in ("committerdate", "authordate"):
  3049. # Sort by date
  3050. def get_commit_date(branch_name: bytes) -> int:
  3051. ref = LOCAL_REMOTE_PREFIX + branch_name
  3052. sha = r.refs[ref]
  3053. commit = r.object_store[sha]
  3054. assert isinstance(commit, Commit)
  3055. if sort_key == "committerdate":
  3056. return cast(int, commit.commit_time)
  3057. else: # authordate
  3058. return cast(int, commit.author_time)
  3059. # Sort branches by date
  3060. # Note: Python's sort naturally orders smaller values first (ascending)
  3061. # For dates, this means oldest first by default
  3062. # Use a stable sort with branch name as secondary key for consistent ordering
  3063. if reverse:
  3064. # For reverse sort, we want newest dates first but alphabetical names second
  3065. branches.sort(key=lambda b: (-get_commit_date(b), b))
  3066. else:
  3067. branches.sort(key=lambda b: (get_commit_date(b), b))
  3068. else:
  3069. # Unknown sort key
  3070. raise ValueError(f"Unknown sort key: {sort_key}")
  3071. return branches
  3072. def _get_branch_merge_status(repo: RepoPath) -> Iterator[tuple[bytes, bool]]:
  3073. """Get merge status for all branches relative to current HEAD.
  3074. Args:
  3075. repo: Path to the repository
  3076. Yields:
  3077. Tuple of (branch_name, is_merged) where:
  3078. - branch_name: Branch name without refs/heads/ prefix
  3079. - is_merged: True if branch is merged into HEAD, False otherwise
  3080. """
  3081. with open_repo_closing(repo) as r:
  3082. current_sha = r.refs[b"HEAD"]
  3083. for branch_ref, branch_sha in r.refs.as_dict(base=b"refs/heads/").items():
  3084. # Check if branch is an ancestor of HEAD (fully merged)
  3085. is_merged = can_fast_forward(r, branch_sha, current_sha)
  3086. yield branch_ref, is_merged
  3087. def merged_branches(repo: RepoPath) -> Iterator[bytes]:
  3088. """List branches that have been merged into the current branch.
  3089. Args:
  3090. repo: Path to the repository
  3091. Yields:
  3092. Branch names (without refs/heads/ prefix) that are merged
  3093. into the current HEAD
  3094. """
  3095. for branch_name, is_merged in _get_branch_merge_status(repo):
  3096. if is_merged:
  3097. yield branch_name
  3098. def no_merged_branches(repo: RepoPath) -> Iterator[bytes]:
  3099. """List branches that have been merged into the current branch.
  3100. Args:
  3101. repo: Path to the repository
  3102. Yields:
  3103. Branch names (without refs/heads/ prefix) that are merged
  3104. into the current HEAD
  3105. """
  3106. for branch_name, is_merged in _get_branch_merge_status(repo):
  3107. if not is_merged:
  3108. yield branch_name
  3109. def branches_containing(repo: RepoPath, commit: str) -> Iterator[bytes]:
  3110. """List branches that contain the specified commit.
  3111. Args:
  3112. repo: Path to the repository
  3113. commit: Commit-ish string (SHA, branch name, tag, etc.)
  3114. Yields:
  3115. Branch names (without refs/heads/ prefix) that contain the commit
  3116. Raises:
  3117. ValueError: If the commit reference is malformed
  3118. KeyError: If the commit reference does not exist
  3119. """
  3120. with open_repo_closing(repo) as r:
  3121. commit_obj = parse_commit(r, commit)
  3122. commit_sha = commit_obj.id
  3123. for branch_ref, branch_sha in r.refs.as_dict(base=LOCAL_BRANCH_PREFIX).items():
  3124. if can_fast_forward(r, commit_sha, branch_sha):
  3125. yield branch_ref
  3126. def active_branch(repo: RepoPath) -> bytes:
  3127. """Return the active branch in the repository, if any.
  3128. Args:
  3129. repo: Repository to open
  3130. Returns:
  3131. branch name
  3132. Raises:
  3133. KeyError: if the repository does not have a working tree
  3134. IndexError: if HEAD is floating
  3135. """
  3136. with open_repo_closing(repo) as r:
  3137. active_ref = r.refs.follow(b"HEAD")[0][1]
  3138. if not active_ref.startswith(LOCAL_BRANCH_PREFIX):
  3139. raise ValueError(active_ref)
  3140. return active_ref[len(LOCAL_BRANCH_PREFIX) :]
  3141. def get_branch_remote(repo: Union[str, os.PathLike[str], Repo]) -> bytes:
  3142. """Return the active branch's remote name, if any.
  3143. Args:
  3144. repo: Repository to open
  3145. Returns:
  3146. remote name
  3147. Raises:
  3148. KeyError: if the repository does not have a working tree
  3149. """
  3150. with open_repo_closing(repo) as r:
  3151. branch_name = active_branch(r.path)
  3152. config = r.get_config()
  3153. try:
  3154. remote_name = config.get((b"branch", branch_name), b"remote")
  3155. except KeyError:
  3156. remote_name = b"origin"
  3157. return remote_name
  3158. def get_branch_merge(repo: RepoPath, branch_name: Optional[bytes] = None) -> bytes:
  3159. """Return the branch's merge reference (upstream branch), if any.
  3160. Args:
  3161. repo: Repository to open
  3162. branch_name: Name of the branch (defaults to active branch)
  3163. Returns:
  3164. merge reference name (e.g. b"refs/heads/main")
  3165. Raises:
  3166. KeyError: if the branch does not have a merge configuration
  3167. """
  3168. with open_repo_closing(repo) as r:
  3169. if branch_name is None:
  3170. branch_name = active_branch(r.path)
  3171. config = r.get_config()
  3172. return config.get((b"branch", branch_name), b"merge")
  3173. def set_branch_tracking(
  3174. repo: Union[str, os.PathLike[str], Repo],
  3175. branch_name: bytes,
  3176. remote_name: bytes,
  3177. remote_ref: bytes,
  3178. ) -> None:
  3179. """Set up branch tracking configuration.
  3180. Args:
  3181. repo: Repository to open
  3182. branch_name: Name of the local branch
  3183. remote_name: Name of the remote (e.g. b"origin")
  3184. remote_ref: Remote reference to track (e.g. b"refs/heads/main")
  3185. """
  3186. with open_repo_closing(repo) as r:
  3187. config = r.get_config()
  3188. config.set((b"branch", branch_name), b"remote", remote_name)
  3189. config.set((b"branch", branch_name), b"merge", remote_ref)
  3190. config.write_to_path()
  3191. def fetch(
  3192. repo: RepoPath,
  3193. remote_location: Optional[Union[str, bytes]] = None,
  3194. outstream: TextIO = sys.stdout,
  3195. errstream: Union[BinaryIO, RawIOBase] = default_bytes_err_stream,
  3196. message: Optional[bytes] = None,
  3197. depth: Optional[int] = None,
  3198. prune: bool = False,
  3199. prune_tags: bool = False,
  3200. force: bool = False,
  3201. operation: Optional[str] = None,
  3202. thin_packs: bool = True,
  3203. report_activity: Optional[Callable[[int, str], None]] = None,
  3204. quiet: bool = False,
  3205. include_tags: bool = False,
  3206. username: Optional[str] = None,
  3207. password: Optional[str] = None,
  3208. key_filename: Optional[str] = None,
  3209. ssh_command: Optional[str] = None,
  3210. ) -> FetchPackResult:
  3211. """Fetch objects from a remote server.
  3212. Args:
  3213. repo: Path to the repository
  3214. remote_location: String identifying a remote server
  3215. outstream: Output stream (defaults to stdout)
  3216. errstream: Error stream (defaults to stderr)
  3217. message: Reflog message (defaults to b"fetch: from <remote_name>")
  3218. depth: Depth to fetch at
  3219. prune: Prune remote removed refs
  3220. prune_tags: Prune remote removed tags
  3221. force: Force fetching even if it would overwrite local changes
  3222. operation: Git operation for authentication (e.g., "fetch")
  3223. thin_packs: Whether to use thin packs
  3224. report_activity: Optional callback for reporting transport activity
  3225. quiet: Whether to suppress progress output
  3226. include_tags: Whether to include tags
  3227. username: Username for authentication
  3228. password: Password for authentication
  3229. key_filename: SSH key filename
  3230. ssh_command: SSH command to use
  3231. Returns:
  3232. Dictionary with refs on the remote
  3233. """
  3234. with open_repo_closing(repo) as r:
  3235. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  3236. if message is None:
  3237. message = b"fetch: from " + remote_location.encode(DEFAULT_ENCODING)
  3238. client, path = get_transport_and_path(
  3239. remote_location,
  3240. config=r.get_config_stack(),
  3241. operation=operation,
  3242. thin_packs=thin_packs,
  3243. report_activity=report_activity,
  3244. quiet=quiet,
  3245. include_tags=include_tags,
  3246. username=username,
  3247. password=password,
  3248. key_filename=key_filename,
  3249. ssh_command=ssh_command,
  3250. )
  3251. def progress(data: bytes) -> None:
  3252. errstream.write(data)
  3253. fetch_result = client.fetch(path.encode(), r, progress=progress, depth=depth)
  3254. if remote_name is not None:
  3255. _import_remote_refs(
  3256. r.refs,
  3257. remote_name,
  3258. fetch_result.refs,
  3259. message,
  3260. prune=prune,
  3261. prune_tags=prune_tags,
  3262. )
  3263. # Trigger auto GC if needed
  3264. from .gc import maybe_auto_gc
  3265. with open_repo_closing(repo) as r:
  3266. maybe_auto_gc(r)
  3267. return fetch_result
  3268. def for_each_ref(
  3269. repo: Union[Repo, str] = ".",
  3270. pattern: Optional[Union[str, bytes]] = None,
  3271. ) -> list[tuple[bytes, bytes, bytes]]:
  3272. """Iterate over all refs that match the (optional) pattern.
  3273. Args:
  3274. repo: Path to the repository
  3275. pattern: Optional glob (7) patterns to filter the refs with
  3276. Returns: List of bytes tuples with: (sha, object_type, ref_name)
  3277. """
  3278. if isinstance(pattern, str):
  3279. pattern = os.fsencode(pattern)
  3280. with open_repo_closing(repo) as r:
  3281. refs = r.get_refs()
  3282. if pattern:
  3283. matching_refs: dict[bytes, bytes] = {}
  3284. pattern_parts = pattern.split(b"/")
  3285. for ref, sha in refs.items():
  3286. matches = False
  3287. # git for-each-ref uses glob (7) style patterns, but fnmatch
  3288. # is greedy and also matches slashes, unlike glob.glob.
  3289. # We have to check parts of the pattern individually.
  3290. # See https://github.com/python/cpython/issues/72904
  3291. ref_parts = ref.split(b"/")
  3292. if len(ref_parts) > len(pattern_parts):
  3293. continue
  3294. for pat, ref_part in zip(pattern_parts, ref_parts):
  3295. matches = fnmatch.fnmatchcase(ref_part, pat)
  3296. if not matches:
  3297. break
  3298. if matches:
  3299. matching_refs[ref] = sha
  3300. refs = matching_refs
  3301. ret: list[tuple[bytes, bytes, bytes]] = [
  3302. (sha, r.get_object(sha).type_name, ref)
  3303. for ref, sha in sorted(
  3304. refs.items(),
  3305. key=lambda ref_sha: ref_sha[0],
  3306. )
  3307. if ref != b"HEAD"
  3308. ]
  3309. return ret
  3310. def show_ref(
  3311. repo: Union[Repo, str] = ".",
  3312. patterns: Optional[list[Union[str, bytes]]] = None,
  3313. head: bool = False,
  3314. branches: bool = False,
  3315. tags: bool = False,
  3316. dereference: bool = False,
  3317. verify: bool = False,
  3318. ) -> list[tuple[bytes, bytes]]:
  3319. """List references in a local repository.
  3320. Args:
  3321. repo: Path to the repository
  3322. patterns: Optional list of patterns to filter refs (matched from the end)
  3323. head: Show the HEAD reference
  3324. branches: Limit to local branches (refs/heads/)
  3325. tags: Limit to local tags (refs/tags/)
  3326. dereference: Dereference tags into object IDs
  3327. verify: Enable stricter reference checking (exact path match)
  3328. Returns: List of tuples with (sha, ref_name) or (sha, ref_name^{}) for dereferenced tags
  3329. """
  3330. # Convert string patterns to bytes
  3331. byte_patterns: Optional[list[bytes]] = None
  3332. if patterns:
  3333. byte_patterns = [os.fsencode(p) if isinstance(p, str) else p for p in patterns]
  3334. with open_repo_closing(repo) as r:
  3335. refs = r.get_refs()
  3336. # Filter by branches/tags if specified
  3337. if branches or tags:
  3338. prefixes = []
  3339. if branches:
  3340. prefixes.append(LOCAL_BRANCH_PREFIX)
  3341. if tags:
  3342. prefixes.append(LOCAL_TAG_PREFIX)
  3343. filtered_refs = filter_ref_prefix(refs, prefixes)
  3344. else:
  3345. # By default, show tags, heads, and remote refs (but not HEAD)
  3346. filtered_refs = filter_ref_prefix(refs, [b"refs/"])
  3347. # Add HEAD if requested
  3348. if head and b"HEAD" in refs:
  3349. filtered_refs[b"HEAD"] = refs[b"HEAD"]
  3350. # Filter by patterns if specified
  3351. if byte_patterns:
  3352. matching_refs: dict[bytes, bytes] = {}
  3353. for ref, sha in filtered_refs.items():
  3354. for pattern in byte_patterns:
  3355. if verify:
  3356. # Verify mode requires exact match
  3357. if ref == pattern:
  3358. matching_refs[ref] = sha
  3359. break
  3360. else:
  3361. # Pattern matching from the end of the full name
  3362. # Only complete parts are matched
  3363. # E.g., "master" matches "refs/heads/master" but not "refs/heads/mymaster"
  3364. pattern_parts = pattern.split(b"/")
  3365. ref_parts = ref.split(b"/")
  3366. # Try to match from the end
  3367. if len(pattern_parts) <= len(ref_parts):
  3368. # Check if the end of ref matches the pattern
  3369. matches = True
  3370. for i in range(len(pattern_parts)):
  3371. if (
  3372. ref_parts[-(len(pattern_parts) - i)]
  3373. != pattern_parts[i]
  3374. ):
  3375. matches = False
  3376. break
  3377. if matches:
  3378. matching_refs[ref] = sha
  3379. break
  3380. filtered_refs = matching_refs
  3381. # Sort by ref name
  3382. sorted_refs = sorted(filtered_refs.items(), key=lambda x: x[0])
  3383. # Build result list
  3384. result: list[tuple[bytes, bytes]] = []
  3385. for ref, sha in sorted_refs:
  3386. result.append((sha, ref))
  3387. # Dereference tags if requested
  3388. if dereference and ref.startswith(LOCAL_TAG_PREFIX):
  3389. try:
  3390. obj = r.get_object(sha)
  3391. # Peel tag objects to get the underlying commit/object
  3392. from .objects import Tag
  3393. while obj.type_name == b"tag":
  3394. assert isinstance(obj, Tag)
  3395. _obj_class, sha = obj.object
  3396. obj = r.get_object(sha)
  3397. result.append((sha, ref + b"^{}"))
  3398. except KeyError:
  3399. # Object not found, skip dereferencing
  3400. pass
  3401. return result
  3402. def show_branch(
  3403. repo: Union[Repo, str] = ".",
  3404. branches: Optional[list[Union[str, bytes]]] = None,
  3405. all_branches: bool = False,
  3406. remotes: bool = False,
  3407. current: bool = False,
  3408. topo_order: bool = False,
  3409. more: Optional[int] = None,
  3410. list_branches: bool = False,
  3411. independent_branches: bool = False,
  3412. merge_base: bool = False,
  3413. ) -> list[str]:
  3414. """Display branches and their commits.
  3415. Args:
  3416. repo: Path to the repository
  3417. branches: List of specific branches to show (default: all local branches)
  3418. all_branches: Show both local and remote branches
  3419. remotes: Show only remote branches
  3420. current: Include current branch if not specified
  3421. topo_order: Show in topological order instead of chronological
  3422. more: Show N more commits beyond common ancestor (negative to show only headers)
  3423. list_branches: Synonym for more=-1 (show only branch headers)
  3424. independent_branches: Show only branches not reachable from others
  3425. merge_base: Show merge bases instead of commit list
  3426. Returns:
  3427. List of output lines
  3428. """
  3429. from .graph import find_octopus_base, independent
  3430. output_lines: list[str] = []
  3431. with open_repo_closing(repo) as r:
  3432. refs = r.get_refs()
  3433. # Determine which branches to show
  3434. branch_refs: dict[bytes, bytes] = {}
  3435. if branches:
  3436. # Specific branches requested
  3437. for branch in branches:
  3438. branch_bytes = (
  3439. os.fsencode(branch) if isinstance(branch, str) else branch
  3440. )
  3441. # Try as full ref name first
  3442. if branch_bytes in refs:
  3443. branch_refs[branch_bytes] = refs[branch_bytes]
  3444. # Try as branch name
  3445. elif LOCAL_BRANCH_PREFIX + branch_bytes in refs:
  3446. branch_refs[LOCAL_BRANCH_PREFIX + branch_bytes] = refs[
  3447. LOCAL_BRANCH_PREFIX + branch_bytes
  3448. ]
  3449. # Try as remote branch
  3450. elif LOCAL_REMOTE_PREFIX + branch_bytes in refs:
  3451. branch_refs[LOCAL_REMOTE_PREFIX + branch_bytes] = refs[
  3452. LOCAL_REMOTE_PREFIX + branch_bytes
  3453. ]
  3454. else:
  3455. # Default behavior: show local branches
  3456. if all_branches:
  3457. # Show both local and remote branches
  3458. branch_refs = filter_ref_prefix(
  3459. refs, [LOCAL_BRANCH_PREFIX, LOCAL_REMOTE_PREFIX]
  3460. )
  3461. elif remotes:
  3462. # Show only remote branches
  3463. branch_refs = filter_ref_prefix(refs, [LOCAL_REMOTE_PREFIX])
  3464. else:
  3465. # Show only local branches
  3466. branch_refs = filter_ref_prefix(refs, [LOCAL_BRANCH_PREFIX])
  3467. # Add current branch if requested and not already included
  3468. if current:
  3469. try:
  3470. head_refs, _ = r.refs.follow(b"HEAD")
  3471. if head_refs:
  3472. head_ref = head_refs[0]
  3473. if head_ref not in branch_refs and head_ref in refs:
  3474. branch_refs[head_ref] = refs[head_ref]
  3475. except (KeyError, TypeError):
  3476. # HEAD doesn't point to a branch or doesn't exist
  3477. pass
  3478. if not branch_refs:
  3479. return output_lines
  3480. # Sort branches for consistent output
  3481. sorted_branches = sorted(branch_refs.items(), key=lambda x: x[0])
  3482. branch_sha_list = [sha for _, sha in sorted_branches]
  3483. # Handle --independent flag
  3484. if independent_branches:
  3485. independent_shas = independent(r, branch_sha_list)
  3486. for ref_name, sha in sorted_branches:
  3487. if sha in independent_shas:
  3488. ref_str = os.fsdecode(shorten_ref_name(ref_name))
  3489. output_lines.append(ref_str)
  3490. return output_lines
  3491. # Handle --merge-base flag
  3492. if merge_base:
  3493. if len(branch_sha_list) < 2:
  3494. # Need at least 2 branches for merge base
  3495. return output_lines
  3496. merge_bases = find_octopus_base(r, branch_sha_list)
  3497. for sha in merge_bases:
  3498. output_lines.append(sha.decode("ascii"))
  3499. return output_lines
  3500. # Get current branch for marking
  3501. current_branch: Optional[bytes] = None
  3502. try:
  3503. head_refs, _ = r.refs.follow(b"HEAD")
  3504. if head_refs:
  3505. current_branch = head_refs[0]
  3506. except (KeyError, TypeError):
  3507. pass
  3508. # Collect commit information for each branch
  3509. branch_commits: list[tuple[bytes, str]] = [] # (sha, message)
  3510. for ref_name, sha in sorted_branches:
  3511. try:
  3512. commit = r[sha]
  3513. if hasattr(commit, "message"):
  3514. message = commit.message.decode("utf-8", errors="replace").split(
  3515. "\n"
  3516. )[0]
  3517. else:
  3518. message = ""
  3519. branch_commits.append((sha, message))
  3520. except KeyError:
  3521. branch_commits.append((sha, ""))
  3522. # Handle --list flag (show only branch headers)
  3523. if list_branches or (more is not None and more < 0):
  3524. # Just show the branch headers
  3525. for i, (ref_name, sha) in enumerate(sorted_branches):
  3526. is_current = ref_name == current_branch
  3527. marker = "*" if is_current else "!"
  3528. # Create spacing for alignment
  3529. prefix = " " * i + marker + " " * (len(sorted_branches) - i - 1)
  3530. ref_str = os.fsdecode(shorten_ref_name(ref_name))
  3531. _, message = branch_commits[i]
  3532. output_lines.append(f"{prefix}[{ref_str}] {message}")
  3533. return output_lines
  3534. # Build commit history for visualization
  3535. # Collect all commits reachable from any branch
  3536. all_commits: dict[
  3537. bytes, tuple[int, list[bytes], str]
  3538. ] = {} # sha -> (timestamp, parents, message)
  3539. def collect_commits(sha: bytes, branch_idx: int, visited: set[bytes]) -> None:
  3540. """Recursively collect commits."""
  3541. if sha in visited:
  3542. return
  3543. visited.add(sha)
  3544. try:
  3545. commit = r[sha]
  3546. if not hasattr(commit, "commit_time"):
  3547. return
  3548. timestamp = commit.commit_time
  3549. parents = commit.parents if hasattr(commit, "parents") else []
  3550. message = (
  3551. commit.message.decode("utf-8", errors="replace").split("\n")[0]
  3552. if hasattr(commit, "message")
  3553. else ""
  3554. )
  3555. if sha not in all_commits:
  3556. all_commits[sha] = (timestamp, parents, message)
  3557. # Recurse to parents
  3558. for parent in parents:
  3559. collect_commits(parent, branch_idx, visited)
  3560. except KeyError:
  3561. # Commit not found, stop traversal
  3562. pass
  3563. # Collect commits from all branches
  3564. for i, (_, sha) in enumerate(sorted_branches):
  3565. collect_commits(sha, i, set())
  3566. # Find common ancestor
  3567. common_ancestor_sha = None
  3568. if len(branch_sha_list) >= 2:
  3569. try:
  3570. merge_bases = find_octopus_base(r, branch_sha_list)
  3571. if merge_bases:
  3572. common_ancestor_sha = merge_bases[0]
  3573. except (KeyError, IndexError):
  3574. pass
  3575. # Sort commits (chronological by default, or topological if requested)
  3576. if topo_order:
  3577. # Topological sort is more complex, for now use chronological
  3578. # TODO: Implement proper topological ordering
  3579. sorted_commits = sorted(all_commits.items(), key=lambda x: -x[1][0])
  3580. else:
  3581. # Reverse chronological order (newest first)
  3582. sorted_commits = sorted(all_commits.items(), key=lambda x: -x[1][0])
  3583. # Determine how many commits to show
  3584. if more is not None:
  3585. # Find index of common ancestor
  3586. if common_ancestor_sha and common_ancestor_sha in all_commits:
  3587. ancestor_idx = next(
  3588. (
  3589. i
  3590. for i, (sha, _) in enumerate(sorted_commits)
  3591. if sha == common_ancestor_sha
  3592. ),
  3593. None,
  3594. )
  3595. if ancestor_idx is not None:
  3596. # Show commits up to ancestor + more
  3597. sorted_commits = sorted_commits[: ancestor_idx + 1 + more]
  3598. # Determine which branches contain which commits
  3599. branch_contains: list[set[bytes]] = []
  3600. for ref_name, sha in sorted_branches:
  3601. reachable = set()
  3602. def mark_reachable(commit_sha: bytes) -> None:
  3603. if commit_sha in reachable:
  3604. return
  3605. reachable.add(commit_sha)
  3606. if commit_sha in all_commits:
  3607. _, parents, _ = all_commits[commit_sha]
  3608. for parent in parents:
  3609. mark_reachable(parent)
  3610. mark_reachable(sha)
  3611. branch_contains.append(reachable)
  3612. # Output branch headers
  3613. for i, (ref_name, sha) in enumerate(sorted_branches):
  3614. is_current = ref_name == current_branch
  3615. marker = "*" if is_current else "!"
  3616. # Create spacing for alignment
  3617. prefix = " " * i + marker + " " * (len(sorted_branches) - i - 1)
  3618. ref_str = os.fsdecode(shorten_ref_name(ref_name))
  3619. _, message = branch_commits[i]
  3620. output_lines.append(f"{prefix}[{ref_str}] {message}")
  3621. # Output separator
  3622. output_lines.append("-" * (len(sorted_branches) + 2))
  3623. # Output commits
  3624. for commit_sha, (_, _, message) in sorted_commits:
  3625. # Build marker string
  3626. markers = []
  3627. for i, (ref_name, branch_sha) in enumerate(sorted_branches):
  3628. if commit_sha == branch_sha:
  3629. # This is the tip of the branch
  3630. markers.append("*")
  3631. elif commit_sha in branch_contains[i]:
  3632. # This commit is in the branch
  3633. markers.append("+")
  3634. else:
  3635. # This commit is not in the branch
  3636. markers.append(" ")
  3637. marker_str = "".join(markers)
  3638. output_lines.append(f"{marker_str} [{message}]")
  3639. # Limit output to 26 branches (git show-branch limitation)
  3640. if len(sorted_branches) > 26:
  3641. break
  3642. return output_lines
  3643. def ls_remote(
  3644. remote: Union[str, bytes],
  3645. config: Optional[Config] = None,
  3646. operation: Optional[str] = None,
  3647. thin_packs: bool = True,
  3648. report_activity: Optional[Callable[[int, str], None]] = None,
  3649. quiet: bool = False,
  3650. include_tags: bool = False,
  3651. username: Optional[str] = None,
  3652. password: Optional[str] = None,
  3653. key_filename: Optional[str] = None,
  3654. ssh_command: Optional[str] = None,
  3655. ) -> LsRemoteResult:
  3656. """List the refs in a remote.
  3657. Args:
  3658. remote: Remote repository location
  3659. config: Configuration to use
  3660. operation: Operation type
  3661. thin_packs: Whether to use thin packs
  3662. report_activity: Function to report activity
  3663. quiet: Whether to suppress output
  3664. include_tags: Whether to include tags
  3665. username: Username for authentication
  3666. password: Password for authentication
  3667. key_filename: SSH key filename
  3668. ssh_command: SSH command to use
  3669. Returns:
  3670. LsRemoteResult object with refs and symrefs
  3671. """
  3672. if config is None:
  3673. config = StackedConfig.default()
  3674. remote_str = remote.decode() if isinstance(remote, bytes) else remote
  3675. client, host_path = get_transport_and_path(
  3676. remote_str,
  3677. config=config,
  3678. operation=operation,
  3679. thin_packs=thin_packs,
  3680. report_activity=report_activity,
  3681. quiet=quiet,
  3682. include_tags=include_tags,
  3683. username=username,
  3684. password=password,
  3685. key_filename=key_filename,
  3686. ssh_command=ssh_command,
  3687. )
  3688. return client.get_refs(
  3689. host_path.encode() if isinstance(host_path, str) else host_path
  3690. )
  3691. def repack(repo: RepoPath) -> None:
  3692. """Repack loose files in a repository.
  3693. Currently this only packs loose objects.
  3694. Args:
  3695. repo: Path to the repository
  3696. """
  3697. with open_repo_closing(repo) as r:
  3698. r.object_store.pack_loose_objects()
  3699. def pack_objects(
  3700. repo: RepoPath,
  3701. object_ids: Sequence[bytes],
  3702. packf: BinaryIO,
  3703. idxf: Optional[BinaryIO],
  3704. delta_window_size: Optional[int] = None,
  3705. deltify: Optional[bool] = None,
  3706. reuse_deltas: bool = True,
  3707. pack_index_version: Optional[int] = None,
  3708. ) -> None:
  3709. """Pack objects into a file.
  3710. Args:
  3711. repo: Path to the repository
  3712. object_ids: List of object ids to write
  3713. packf: File-like object to write to
  3714. idxf: File-like object to write to (can be None)
  3715. delta_window_size: Sliding window size for searching for deltas;
  3716. Set to None for default window size.
  3717. deltify: Whether to deltify objects
  3718. reuse_deltas: Allow reuse of existing deltas while deltifying
  3719. pack_index_version: Pack index version to use (1, 2, or 3). If None, uses default version.
  3720. """
  3721. with open_repo_closing(repo) as r:
  3722. entries, data_sum = write_pack_from_container(
  3723. packf.write,
  3724. r.object_store,
  3725. [(oid, None) for oid in object_ids],
  3726. deltify=deltify,
  3727. delta_window_size=delta_window_size,
  3728. reuse_deltas=reuse_deltas,
  3729. )
  3730. if idxf is not None:
  3731. index_entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
  3732. write_pack_index(idxf, index_entries, data_sum, version=pack_index_version)
  3733. def ls_tree(
  3734. repo: RepoPath,
  3735. treeish: Union[str, bytes, Commit, Tree, Tag] = b"HEAD",
  3736. outstream: Union[TextIO, BinaryIO] = sys.stdout,
  3737. recursive: bool = False,
  3738. name_only: bool = False,
  3739. ) -> None:
  3740. """List contents of a tree.
  3741. Args:
  3742. repo: Path to the repository
  3743. treeish: Tree id to list
  3744. outstream: Output stream (defaults to stdout)
  3745. recursive: Whether to recursively list files
  3746. name_only: Only print item name
  3747. """
  3748. def list_tree(store: BaseObjectStore, treeid: bytes, base: bytes) -> None:
  3749. tree = store[treeid]
  3750. assert isinstance(tree, Tree)
  3751. for name, mode, sha in tree.iteritems():
  3752. assert name is not None
  3753. assert mode is not None
  3754. assert sha is not None
  3755. if base:
  3756. name = posixpath.join(base, name)
  3757. if name_only:
  3758. if isinstance(outstream, BinaryIO):
  3759. outstream.write(name + b"\n")
  3760. else:
  3761. outstream.write(name.decode("utf-8", "replace") + "\n")
  3762. else:
  3763. formatted = pretty_format_tree_entry(name, mode, sha)
  3764. if isinstance(outstream, BinaryIO):
  3765. outstream.write(formatted.encode("utf-8"))
  3766. else:
  3767. outstream.write(formatted)
  3768. if stat.S_ISDIR(mode) and recursive:
  3769. list_tree(store, sha, name)
  3770. with open_repo_closing(repo) as r:
  3771. tree = parse_tree(r, treeish)
  3772. list_tree(r.object_store, tree.id, b"")
  3773. def remote_add(
  3774. repo: RepoPath,
  3775. name: Union[bytes, str],
  3776. url: Union[bytes, str],
  3777. ) -> None:
  3778. """Add a remote.
  3779. Args:
  3780. repo: Path to the repository
  3781. name: Remote name
  3782. url: Remote URL
  3783. """
  3784. if not isinstance(name, bytes):
  3785. name = name.encode(DEFAULT_ENCODING)
  3786. if not isinstance(url, bytes):
  3787. url = url.encode(DEFAULT_ENCODING)
  3788. with open_repo_closing(repo) as r:
  3789. c = r.get_config()
  3790. section = (b"remote", name)
  3791. if c.has_section(section):
  3792. raise RemoteExists(f"Remote {name.decode()} already exists")
  3793. c.set(section, b"url", url)
  3794. c.write_to_path()
  3795. def remote_remove(repo: Repo, name: Union[bytes, str]) -> None:
  3796. """Remove a remote.
  3797. Args:
  3798. repo: Path to the repository
  3799. name: Remote name
  3800. """
  3801. if not isinstance(name, bytes):
  3802. name = name.encode(DEFAULT_ENCODING)
  3803. with open_repo_closing(repo) as r:
  3804. c = r.get_config()
  3805. section = (b"remote", name)
  3806. del c[section]
  3807. c.write_to_path()
  3808. def _quote_path(path: str) -> str:
  3809. """Quote a path using C-style quoting similar to git's core.quotePath.
  3810. Args:
  3811. path: Path to quote
  3812. Returns:
  3813. Quoted path string
  3814. """
  3815. # Check if path needs quoting (non-ASCII or special characters)
  3816. needs_quoting = False
  3817. for char in path:
  3818. if ord(char) > 127 or char in '"\\':
  3819. needs_quoting = True
  3820. break
  3821. if not needs_quoting:
  3822. return path
  3823. # Apply C-style quoting
  3824. quoted = '"'
  3825. for char in path:
  3826. if ord(char) > 127:
  3827. # Non-ASCII character, encode as octal escape
  3828. utf8_bytes = char.encode("utf-8")
  3829. for byte in utf8_bytes:
  3830. quoted += f"\\{byte:03o}"
  3831. elif char == '"':
  3832. quoted += '\\"'
  3833. elif char == "\\":
  3834. quoted += "\\\\"
  3835. else:
  3836. quoted += char
  3837. quoted += '"'
  3838. return quoted
  3839. def check_ignore(
  3840. repo: RepoPath,
  3841. paths: Sequence[Union[str, bytes, os.PathLike[str]]],
  3842. no_index: bool = False,
  3843. quote_path: bool = True,
  3844. ) -> Iterator[str]:
  3845. r"""Debug gitignore files.
  3846. Args:
  3847. repo: Path to the repository
  3848. paths: List of paths to check for
  3849. no_index: Don't check index
  3850. quote_path: If True, quote non-ASCII characters in returned paths using
  3851. C-style octal escapes (e.g. "тест.txt" becomes "\\321\\202\\320\\265\\321\\201\\321\\202.txt").
  3852. If False, return raw unicode paths.
  3853. Returns: List of ignored files
  3854. """
  3855. with open_repo_closing(repo) as r:
  3856. index = r.open_index()
  3857. ignore_manager = IgnoreFilterManager.from_repo(r)
  3858. for original_path in paths:
  3859. # Convert path to string for consistent handling
  3860. original_path_fspath = os.fspath(original_path)
  3861. # Normalize to str
  3862. original_path_str = os.fsdecode(original_path_fspath)
  3863. if not no_index and path_to_tree_path(r.path, original_path_str) in index:
  3864. continue
  3865. # Preserve whether the original path had a trailing slash
  3866. had_trailing_slash = original_path_str.endswith(("/", os.path.sep))
  3867. if os.path.isabs(original_path_str):
  3868. path = os.path.relpath(original_path_str, r.path)
  3869. # Normalize Windows paths to use forward slashes
  3870. if os.path.sep != "/":
  3871. path = path.replace(os.path.sep, "/")
  3872. else:
  3873. path = original_path_str
  3874. # Restore trailing slash if it was in the original
  3875. if had_trailing_slash and not path.endswith("/"):
  3876. path = path + "/"
  3877. # For directories, check with trailing slash to get correct ignore behavior
  3878. test_path = path
  3879. path_without_slash = path.rstrip("/")
  3880. is_directory = os.path.isdir(os.path.join(r.path, path_without_slash))
  3881. # If this is a directory path, ensure we test it correctly
  3882. if is_directory and not path.endswith("/"):
  3883. test_path = path + "/"
  3884. if ignore_manager.is_ignored(test_path):
  3885. # Return relative path (like git does) when absolute path was provided
  3886. if os.path.isabs(original_path):
  3887. output_path = path
  3888. else:
  3889. output_path = original_path # type: ignore[assignment]
  3890. yield _quote_path(output_path) if quote_path else output_path
  3891. def update_head(
  3892. repo: RepoPath,
  3893. target: Union[str, bytes],
  3894. detached: bool = False,
  3895. new_branch: Optional[Union[str, bytes]] = None,
  3896. ) -> None:
  3897. """Update HEAD to point at a new branch/commit.
  3898. Note that this does not actually update the working tree.
  3899. Args:
  3900. repo: Path to the repository
  3901. detached: Create a detached head
  3902. target: Branch or committish to switch to
  3903. new_branch: New branch to create
  3904. """
  3905. with open_repo_closing(repo) as r:
  3906. if new_branch is not None:
  3907. to_set = _make_branch_ref(new_branch)
  3908. else:
  3909. to_set = b"HEAD"
  3910. if detached:
  3911. # TODO(jelmer): Provide some way so that the actual ref gets
  3912. # updated rather than what it points to, so the delete isn't
  3913. # necessary.
  3914. del r.refs[to_set]
  3915. r.refs[to_set] = parse_commit(r, target).id
  3916. else:
  3917. r.refs.set_symbolic_ref(to_set, parse_ref(r, target))
  3918. if new_branch is not None:
  3919. r.refs.set_symbolic_ref(b"HEAD", to_set)
  3920. def checkout(
  3921. repo: Union[str, os.PathLike[str], Repo],
  3922. target: Optional[Union[str, bytes, Commit, Tag]] = None,
  3923. force: bool = False,
  3924. new_branch: Optional[Union[bytes, str]] = None,
  3925. paths: Optional[list[Union[bytes, str]]] = None,
  3926. ) -> None:
  3927. """Switch to a branch or commit, updating both HEAD and the working tree.
  3928. This is similar to 'git checkout', allowing you to switch to a branch,
  3929. tag, or specific commit. Unlike update_head, this function also updates
  3930. the working tree to match the target.
  3931. Args:
  3932. repo: Path to repository or repository object
  3933. target: Branch name, tag, or commit SHA to checkout. If None and paths is specified,
  3934. restores files from HEAD
  3935. force: Force checkout even if there are local changes
  3936. new_branch: Create a new branch at target (like git checkout -b)
  3937. paths: List of specific paths to checkout. If specified, only these paths are updated
  3938. and HEAD is not changed
  3939. Raises:
  3940. CheckoutError: If checkout cannot be performed due to conflicts
  3941. KeyError: If the target reference cannot be found
  3942. """
  3943. with open_repo_closing(repo) as r:
  3944. # Store the original target for later reference checks
  3945. original_target = target
  3946. worktree = r.get_worktree()
  3947. # Handle path-specific checkout (like git checkout -- <paths>)
  3948. if paths is not None:
  3949. # Convert paths to bytes
  3950. byte_paths = []
  3951. for path in paths:
  3952. if isinstance(path, str):
  3953. byte_paths.append(path.encode(DEFAULT_ENCODING))
  3954. else:
  3955. byte_paths.append(path)
  3956. # If no target specified, use HEAD
  3957. if target is None:
  3958. try:
  3959. target = r.refs[b"HEAD"]
  3960. except KeyError:
  3961. raise CheckoutError("No HEAD reference found")
  3962. else:
  3963. if isinstance(target, str):
  3964. target = target.encode(DEFAULT_ENCODING)
  3965. # Get the target commit and tree
  3966. target_tree = parse_tree(r, target)
  3967. # Get blob normalizer for line ending conversion
  3968. blob_normalizer = r.get_blob_normalizer()
  3969. # Restore specified paths from target tree
  3970. for path in byte_paths:
  3971. try:
  3972. # Look up the path in the target tree
  3973. mode, sha = target_tree.lookup_path(
  3974. r.object_store.__getitem__, path
  3975. )
  3976. obj = r[sha]
  3977. assert isinstance(obj, Blob), "Expected a Blob object"
  3978. except KeyError:
  3979. # Path doesn't exist in target tree
  3980. pass
  3981. else:
  3982. # Create directories if needed
  3983. # Handle path as string
  3984. if isinstance(path, bytes):
  3985. path_str = path.decode(DEFAULT_ENCODING)
  3986. else:
  3987. path_str = path
  3988. file_path = os.path.join(r.path, path_str)
  3989. os.makedirs(os.path.dirname(file_path), exist_ok=True)
  3990. # Write the file content
  3991. if stat.S_ISREG(mode):
  3992. # Apply checkout filters (smudge)
  3993. if blob_normalizer:
  3994. obj = blob_normalizer.checkout_normalize(obj, path)
  3995. flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
  3996. if sys.platform == "win32":
  3997. flags |= os.O_BINARY
  3998. with os.fdopen(os.open(file_path, flags, mode), "wb") as f:
  3999. f.write(obj.data)
  4000. # Update the index
  4001. worktree.stage(path)
  4002. return
  4003. # Normal checkout (switching branches/commits)
  4004. if target is None:
  4005. raise ValueError("Target must be specified for branch/commit checkout")
  4006. if isinstance(target, str):
  4007. target_bytes = target.encode(DEFAULT_ENCODING)
  4008. elif isinstance(target, bytes):
  4009. target_bytes = target
  4010. else:
  4011. # For Commit/Tag objects, we'll use their SHA
  4012. target_bytes = target.id
  4013. if isinstance(new_branch, str):
  4014. new_branch = new_branch.encode(DEFAULT_ENCODING)
  4015. # Parse the target to get the commit
  4016. assert (
  4017. original_target is not None
  4018. ) # Guaranteed by earlier check for normal checkout
  4019. target_commit = parse_commit(r, original_target)
  4020. target_tree_id = target_commit.tree
  4021. # Get current HEAD tree for comparison
  4022. try:
  4023. current_head = r.refs[b"HEAD"]
  4024. current_commit = r[current_head]
  4025. assert isinstance(current_commit, Commit), "Expected a Commit object"
  4026. current_tree_id = current_commit.tree
  4027. except KeyError:
  4028. # No HEAD yet (empty repo)
  4029. current_tree_id = None
  4030. # Check for uncommitted changes if not forcing
  4031. if not force and current_tree_id is not None:
  4032. status_report = status(r)
  4033. changes = []
  4034. # staged is a dict with 'add', 'delete', 'modify' keys
  4035. if isinstance(status_report.staged, dict):
  4036. changes.extend(status_report.staged.get("add", []))
  4037. changes.extend(status_report.staged.get("delete", []))
  4038. changes.extend(status_report.staged.get("modify", []))
  4039. # unstaged is a list
  4040. changes.extend(status_report.unstaged)
  4041. if changes:
  4042. # Check if any changes would conflict with checkout
  4043. target_tree_obj = r[target_tree_id]
  4044. assert isinstance(target_tree_obj, Tree), "Expected a Tree object"
  4045. target_tree = target_tree_obj
  4046. for change in changes:
  4047. if isinstance(change, str):
  4048. change = change.encode(DEFAULT_ENCODING)
  4049. try:
  4050. target_tree.lookup_path(r.object_store.__getitem__, change)
  4051. except KeyError:
  4052. # File doesn't exist in target tree - change can be preserved
  4053. pass
  4054. else:
  4055. # File exists in target tree - would overwrite local changes
  4056. raise CheckoutError(
  4057. f"Your local changes to '{change.decode()}' would be "
  4058. "overwritten by checkout. Please commit or stash before switching."
  4059. )
  4060. # Get configuration for working directory update
  4061. config = r.get_config()
  4062. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  4063. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  4064. validate_path_element = validate_path_element_ntfs
  4065. else:
  4066. validate_path_element = validate_path_element_default
  4067. if config.get_boolean(b"core", b"symlinks", True):
  4068. def symlink_wrapper(
  4069. source: Union[str, bytes, os.PathLike[str]],
  4070. target: Union[str, bytes, os.PathLike[str]],
  4071. ) -> None:
  4072. symlink(source, target) # type: ignore[arg-type,unused-ignore]
  4073. symlink_fn = symlink_wrapper
  4074. else:
  4075. def symlink_fallback(
  4076. source: Union[str, bytes, os.PathLike[str]],
  4077. target: Union[str, bytes, os.PathLike[str]],
  4078. ) -> None:
  4079. mode = "w" + ("b" if isinstance(source, bytes) else "")
  4080. with open(target, mode) as f:
  4081. f.write(source)
  4082. symlink_fn = symlink_fallback
  4083. # Get blob normalizer for line ending conversion
  4084. blob_normalizer = r.get_blob_normalizer()
  4085. # Update working tree
  4086. tree_change_iterator: Iterator[TreeChange] = tree_changes(
  4087. r.object_store, current_tree_id, target_tree_id
  4088. )
  4089. update_working_tree(
  4090. r,
  4091. current_tree_id,
  4092. target_tree_id,
  4093. change_iterator=tree_change_iterator,
  4094. honor_filemode=honor_filemode,
  4095. validate_path_element=validate_path_element,
  4096. symlink_fn=symlink_fn,
  4097. force_remove_untracked=force,
  4098. blob_normalizer=blob_normalizer,
  4099. allow_overwrite_modified=force,
  4100. )
  4101. # Update HEAD
  4102. if new_branch:
  4103. # Create new branch and switch to it
  4104. branch_create(r, new_branch, objectish=target_commit.id.decode("ascii"))
  4105. update_head(r, new_branch)
  4106. # Set up tracking if creating from a remote branch
  4107. from .refs import LOCAL_REMOTE_PREFIX, parse_remote_ref
  4108. if isinstance(original_target, bytes) and target_bytes.startswith(
  4109. LOCAL_REMOTE_PREFIX
  4110. ):
  4111. try:
  4112. remote_name, branch_name = parse_remote_ref(target_bytes)
  4113. # Set tracking to refs/heads/<branch> on the remote
  4114. set_branch_tracking(
  4115. r, new_branch, remote_name, b"refs/heads/" + branch_name
  4116. )
  4117. except ValueError:
  4118. # Invalid remote ref format, skip tracking setup
  4119. pass
  4120. else:
  4121. # Check if target is a branch name (with or without refs/heads/ prefix)
  4122. branch_ref = None
  4123. if (
  4124. isinstance(original_target, (str, bytes))
  4125. and target_bytes in r.refs.keys()
  4126. ):
  4127. if target_bytes.startswith(LOCAL_BRANCH_PREFIX):
  4128. branch_ref = target_bytes
  4129. else:
  4130. # Try adding refs/heads/ prefix
  4131. potential_branch = (
  4132. _make_branch_ref(target_bytes)
  4133. if isinstance(original_target, (str, bytes))
  4134. else None
  4135. )
  4136. if potential_branch in r.refs.keys():
  4137. branch_ref = potential_branch
  4138. if branch_ref:
  4139. # It's a branch - update HEAD symbolically
  4140. update_head(r, branch_ref)
  4141. else:
  4142. # It's a tag, other ref, or commit SHA - detached HEAD
  4143. update_head(r, target_commit.id.decode("ascii"), detached=True)
  4144. def reset_file(
  4145. repo: Repo,
  4146. file_path: str,
  4147. target: Union[str, bytes, Commit, Tree, Tag] = b"HEAD",
  4148. symlink_fn: Optional[
  4149. Callable[
  4150. [Union[str, bytes, os.PathLike[str]], Union[str, bytes, os.PathLike[str]]],
  4151. None,
  4152. ]
  4153. ] = None,
  4154. ) -> None:
  4155. """Reset the file to specific commit or branch.
  4156. Args:
  4157. repo: dulwich Repo object
  4158. file_path: file to reset, relative to the repository path
  4159. target: branch or commit or b'HEAD' to reset
  4160. symlink_fn: Function to use for creating symlinks
  4161. """
  4162. tree = parse_tree(repo, treeish=target)
  4163. tree_path = _fs_to_tree_path(file_path)
  4164. file_entry = tree.lookup_path(repo.object_store.__getitem__, tree_path)
  4165. full_path = os.path.join(os.fsencode(repo.path), tree_path)
  4166. blob = repo.object_store[file_entry[1]]
  4167. assert isinstance(blob, Blob)
  4168. mode = file_entry[0]
  4169. build_file_from_blob(blob, mode, full_path, symlink_fn=symlink_fn)
  4170. @replace_me(since="0.22.9", remove_in="0.24.0")
  4171. def checkout_branch(
  4172. repo: Union[str, os.PathLike[str], Repo],
  4173. target: Union[bytes, str],
  4174. force: bool = False,
  4175. ) -> None:
  4176. """Switch branches or restore working tree files.
  4177. This is now a wrapper around the general checkout() function.
  4178. Preserved for backward compatibility.
  4179. Args:
  4180. repo: dulwich Repo object
  4181. target: branch name or commit sha to checkout
  4182. force: true or not to force checkout
  4183. """
  4184. # Simply delegate to the new checkout function
  4185. return checkout(repo, target, force=force)
  4186. def sparse_checkout(
  4187. repo: Union[str, os.PathLike[str], Repo],
  4188. patterns: Optional[list[str]] = None,
  4189. force: bool = False,
  4190. cone: Optional[bool] = None,
  4191. ) -> None:
  4192. """Perform a sparse checkout in the repository (either 'full' or 'cone mode').
  4193. Perform sparse checkout in either 'cone' (directory-based) mode or
  4194. 'full pattern' (.gitignore) mode, depending on the ``cone`` parameter.
  4195. If ``cone`` is ``None``, the mode is inferred from the repository's
  4196. ``core.sparseCheckoutCone`` config setting.
  4197. Steps:
  4198. 1) If ``patterns`` is provided, write them to ``.git/info/sparse-checkout``.
  4199. 2) Determine which paths in the index are included vs. excluded.
  4200. - If ``cone=True``, use "cone-compatible" directory-based logic.
  4201. - If ``cone=False``, use standard .gitignore-style matching.
  4202. 3) Update the index's skip-worktree bits and add/remove files in
  4203. the working tree accordingly.
  4204. 4) If ``force=False``, refuse to remove files that have local modifications.
  4205. Args:
  4206. repo: Path to the repository or a Repo object.
  4207. patterns: Optional list of sparse-checkout patterns to write.
  4208. force: Whether to force removal of locally modified files (default False).
  4209. cone: Boolean indicating cone mode (True/False). If None, read from config.
  4210. Returns:
  4211. None
  4212. """
  4213. with open_repo_closing(repo) as repo_obj:
  4214. # --- 0) Possibly infer 'cone' from config ---
  4215. if cone is None:
  4216. cone = repo_obj.get_worktree().infer_cone_mode()
  4217. # --- 1) Read or write patterns ---
  4218. if patterns is None:
  4219. lines = repo_obj.get_worktree().get_sparse_checkout_patterns()
  4220. if lines is None:
  4221. raise Error("No sparse checkout patterns found.")
  4222. else:
  4223. lines = patterns
  4224. repo_obj.get_worktree().set_sparse_checkout_patterns(patterns)
  4225. # --- 2) Determine the set of included paths ---
  4226. index = repo_obj.open_index()
  4227. included_paths = determine_included_paths(index, lines, cone)
  4228. # --- 3) Apply those results to the index & working tree ---
  4229. try:
  4230. apply_included_paths(repo_obj, included_paths, force=force)
  4231. except SparseCheckoutConflictError as exc:
  4232. raise CheckoutError(*exc.args) from exc
  4233. def cone_mode_init(repo: Union[str, os.PathLike[str], Repo]) -> None:
  4234. """Initialize a repository to use sparse checkout in 'cone' mode.
  4235. Sets ``core.sparseCheckout`` and ``core.sparseCheckoutCone`` in the config.
  4236. Writes an initial ``.git/info/sparse-checkout`` file that includes only
  4237. top-level files (and excludes all subdirectories), e.g. ``["/*", "!/*/"]``.
  4238. Then performs a sparse checkout to update the working tree accordingly.
  4239. If no directories are specified, then only top-level files are included:
  4240. https://git-scm.com/docs/git-sparse-checkout#_internalscone_mode_handling
  4241. Args:
  4242. repo: Path to the repository or a Repo object.
  4243. Returns:
  4244. None
  4245. """
  4246. with open_repo_closing(repo) as repo_obj:
  4247. repo_obj.get_worktree().configure_for_cone_mode()
  4248. patterns = ["/*", "!/*/"] # root-level files only
  4249. sparse_checkout(repo_obj, patterns, force=True, cone=True)
  4250. def cone_mode_set(
  4251. repo: Union[str, os.PathLike[str], Repo], dirs: Sequence[str], force: bool = False
  4252. ) -> None:
  4253. """Overwrite the existing 'cone-mode' sparse patterns with a new set of directories.
  4254. Ensures ``core.sparseCheckout`` and ``core.sparseCheckoutCone`` are enabled.
  4255. Writes new patterns so that only the specified directories (and top-level files)
  4256. remain in the working tree, and applies the sparse checkout update.
  4257. Args:
  4258. repo: Path to the repository or a Repo object.
  4259. dirs: List of directory names to include.
  4260. force: Whether to forcibly discard local modifications (default False).
  4261. Returns:
  4262. None
  4263. """
  4264. with open_repo_closing(repo) as repo_obj:
  4265. repo_obj.get_worktree().configure_for_cone_mode()
  4266. repo_obj.get_worktree().set_cone_mode_patterns(dirs=dirs)
  4267. new_patterns = repo_obj.get_worktree().get_sparse_checkout_patterns()
  4268. # Finally, apply the patterns and update the working tree
  4269. sparse_checkout(repo_obj, new_patterns, force=force, cone=True)
  4270. def cone_mode_add(
  4271. repo: Union[str, os.PathLike[str], Repo], dirs: Sequence[str], force: bool = False
  4272. ) -> None:
  4273. """Add new directories to the existing 'cone-mode' sparse-checkout patterns.
  4274. Reads the current patterns from ``.git/info/sparse-checkout``, adds pattern
  4275. lines to include the specified directories, and then performs a sparse
  4276. checkout to update the working tree accordingly.
  4277. Args:
  4278. repo: Path to the repository or a Repo object.
  4279. dirs: List of directory names to add to the sparse-checkout.
  4280. force: Whether to forcibly discard local modifications (default False).
  4281. Returns:
  4282. None
  4283. """
  4284. with open_repo_closing(repo) as repo_obj:
  4285. repo_obj.get_worktree().configure_for_cone_mode()
  4286. # Do not pass base patterns as dirs
  4287. base_patterns = ["/*", "!/*/"]
  4288. existing_dirs = [
  4289. pat.strip("/")
  4290. for pat in repo_obj.get_worktree().get_sparse_checkout_patterns()
  4291. if pat not in base_patterns
  4292. ]
  4293. added_dirs = existing_dirs + list(dirs or [])
  4294. repo_obj.get_worktree().set_cone_mode_patterns(dirs=added_dirs)
  4295. new_patterns = repo_obj.get_worktree().get_sparse_checkout_patterns()
  4296. sparse_checkout(repo_obj, patterns=new_patterns, force=force, cone=True)
  4297. def check_mailmap(repo: RepoPath, contact: Union[str, bytes]) -> bytes:
  4298. """Check canonical name and email of contact.
  4299. Args:
  4300. repo: Path to the repository
  4301. contact: Contact name and/or email
  4302. Returns: Canonical contact data
  4303. """
  4304. with open_repo_closing(repo) as r:
  4305. from .mailmap import Mailmap
  4306. try:
  4307. mailmap = Mailmap.from_path(os.path.join(r.path, ".mailmap"))
  4308. except FileNotFoundError:
  4309. mailmap = Mailmap()
  4310. contact_bytes = (
  4311. contact.encode(DEFAULT_ENCODING) if isinstance(contact, str) else contact
  4312. )
  4313. result = mailmap.lookup(contact_bytes)
  4314. if isinstance(result, bytes):
  4315. return result
  4316. else:
  4317. # Convert tuple back to bytes format
  4318. name, email = result
  4319. if name is None:
  4320. name = b""
  4321. if email is None:
  4322. email = b""
  4323. return name + b" <" + email + b">"
  4324. def fsck(repo: RepoPath) -> Iterator[tuple[bytes, Exception]]:
  4325. """Check a repository.
  4326. Args:
  4327. repo: A path to the repository
  4328. Returns: Iterator over errors/warnings
  4329. """
  4330. with open_repo_closing(repo) as r:
  4331. # TODO(jelmer): check pack files
  4332. # TODO(jelmer): check graph
  4333. # TODO(jelmer): check refs
  4334. for sha in r.object_store:
  4335. o = r.object_store[sha]
  4336. try:
  4337. o.check()
  4338. except Exception as e:
  4339. yield (sha, e)
  4340. def stash_list(
  4341. repo: Union[str, os.PathLike[str], Repo],
  4342. ) -> Iterator[tuple[int, tuple[bytes, bytes]]]:
  4343. """List all stashes in a repository."""
  4344. with open_repo_closing(repo) as r:
  4345. from .stash import Stash
  4346. stash = Stash.from_repo(r)
  4347. entries = stash.stashes()
  4348. # Convert Entry objects to (old_sha, new_sha) tuples
  4349. return enumerate([(entry.old_sha, entry.new_sha) for entry in entries])
  4350. def stash_push(repo: Union[str, os.PathLike[str], Repo]) -> None:
  4351. """Push a new stash onto the stack."""
  4352. with open_repo_closing(repo) as r:
  4353. from .stash import Stash
  4354. stash = Stash.from_repo(r)
  4355. stash.push()
  4356. def stash_pop(repo: Union[str, os.PathLike[str], Repo]) -> None:
  4357. """Pop a stash from the stack."""
  4358. with open_repo_closing(repo) as r:
  4359. from .stash import Stash
  4360. stash = Stash.from_repo(r)
  4361. stash.pop(0)
  4362. def stash_drop(repo: Union[str, os.PathLike[str], Repo], index: int) -> None:
  4363. """Drop a stash from the stack."""
  4364. with open_repo_closing(repo) as r:
  4365. from .stash import Stash
  4366. stash = Stash.from_repo(r)
  4367. stash.drop(index)
  4368. def ls_files(repo: RepoPath) -> list[bytes]:
  4369. """List all files in an index."""
  4370. with open_repo_closing(repo) as r:
  4371. return sorted(r.open_index())
  4372. def find_unique_abbrev(
  4373. object_store: BaseObjectStore, object_id: Union[str, bytes], min_length: int = 7
  4374. ) -> str:
  4375. """Find the shortest unique abbreviation for an object ID.
  4376. Args:
  4377. object_store: Object store to search in
  4378. object_id: The full object ID to abbreviate
  4379. min_length: Minimum length of abbreviation (default 7)
  4380. Returns:
  4381. The shortest unique prefix of the object ID (at least min_length chars)
  4382. """
  4383. if isinstance(object_id, bytes):
  4384. hex_id = object_id.decode("ascii")
  4385. else:
  4386. hex_id = object_id
  4387. # Start with minimum length
  4388. for length in range(min_length, len(hex_id) + 1):
  4389. prefix = hex_id[:length]
  4390. matches = 0
  4391. # Check if this prefix is unique
  4392. for obj_id in object_store:
  4393. if obj_id.decode("ascii").startswith(prefix):
  4394. matches += 1
  4395. if matches > 1:
  4396. # Not unique, need more characters
  4397. break
  4398. if matches == 1:
  4399. # Found unique prefix
  4400. return prefix
  4401. # If we get here, return the full ID
  4402. return hex_id
  4403. def describe(
  4404. repo: Union[str, os.PathLike[str], Repo], abbrev: Optional[int] = None
  4405. ) -> str:
  4406. """Describe the repository version.
  4407. Args:
  4408. repo: git repository
  4409. abbrev: number of characters of commit to take, default is 7
  4410. Returns: a string description of the current git revision
  4411. Examples: "gabcdefh", "v0.1" or "v0.1-5-gabcdefh".
  4412. """
  4413. abbrev_slice = slice(0, abbrev if abbrev is not None else 7)
  4414. # Get the repository
  4415. with open_repo_closing(repo) as r:
  4416. # Get a list of all tags
  4417. refs = r.get_refs()
  4418. tags = {}
  4419. for key, value in refs.items():
  4420. key_str = key.decode()
  4421. obj = r.get_object(value)
  4422. if "tags" not in key_str:
  4423. continue
  4424. _, tag = key_str.rsplit("/", 1)
  4425. if isinstance(obj, Tag):
  4426. # Annotated tag case
  4427. commit = r.get_object(obj.object[1])
  4428. else:
  4429. # Lightweight tag case - obj is already the commit
  4430. commit = obj
  4431. if not isinstance(commit, Commit):
  4432. raise AssertionError(
  4433. f"Expected Commit object, got {type(commit).__name__}"
  4434. )
  4435. tag_info: list[Any] = [
  4436. datetime.datetime(*time.gmtime(commit.commit_time)[:6]),
  4437. commit.id.decode("ascii"),
  4438. ]
  4439. tags[tag] = tag_info
  4440. # Sort tags by datetime (first element of the value list)
  4441. sorted_tags = sorted(
  4442. tags.items(), key=lambda tag_item: tag_item[1][0], reverse=True
  4443. )
  4444. # Get the latest commit
  4445. latest_commit = r[r.head()]
  4446. # If there are no tags, return the latest commit
  4447. if len(sorted_tags) == 0:
  4448. if abbrev is not None:
  4449. return "g{}".format(latest_commit.id.decode("ascii")[abbrev_slice])
  4450. return f"g{find_unique_abbrev(r.object_store, latest_commit.id)}"
  4451. # We're now 0 commits from the top
  4452. commit_count = 0
  4453. # Walk through all commits
  4454. walker = r.get_walker()
  4455. for entry in walker:
  4456. # Check if tag
  4457. commit_id = entry.commit.id.decode("ascii")
  4458. for tag_item in sorted_tags:
  4459. tag_name = tag_item[0]
  4460. tag_commit = tag_item[1][1]
  4461. if commit_id == tag_commit:
  4462. if commit_count == 0:
  4463. return tag_name
  4464. else:
  4465. if abbrev is not None:
  4466. abbrev_hash = latest_commit.id.decode("ascii")[abbrev_slice]
  4467. else:
  4468. abbrev_hash = find_unique_abbrev(
  4469. r.object_store, latest_commit.id
  4470. )
  4471. return f"{tag_name}-{commit_count}-g{abbrev_hash}"
  4472. commit_count += 1
  4473. # Return plain commit if no parent tag can be found
  4474. if abbrev is not None:
  4475. return "g{}".format(latest_commit.id.decode("ascii")[abbrev_slice])
  4476. return f"g{find_unique_abbrev(r.object_store, latest_commit.id)}"
  4477. def get_object_by_path(
  4478. repo: RepoPath,
  4479. path: Union[str, bytes],
  4480. committish: Optional[Union[str, bytes, Commit, Tag]] = None,
  4481. ) -> Union[Blob, Tree, Commit, Tag]:
  4482. """Get an object by path.
  4483. Args:
  4484. repo: A path to the repository
  4485. path: Path to look up
  4486. committish: Commit to look up path in
  4487. Returns: A `ShaFile` object
  4488. """
  4489. if committish is None:
  4490. committish = "HEAD"
  4491. # Get the repository
  4492. with open_repo_closing(repo) as r:
  4493. commit = parse_commit(r, committish)
  4494. base_tree = commit.tree
  4495. if not isinstance(path, bytes):
  4496. path = commit_encode(commit, path)
  4497. (_mode, sha) = tree_lookup_path(r.object_store.__getitem__, base_tree, path)
  4498. obj = r[sha]
  4499. assert isinstance(obj, (Blob, Tree, Commit, Tag))
  4500. return obj
  4501. def write_tree(repo: RepoPath) -> bytes:
  4502. """Write a tree object from the index.
  4503. Args:
  4504. repo: Repository for which to write tree
  4505. Returns: tree id for the tree that was written
  4506. """
  4507. with open_repo_closing(repo) as r:
  4508. return r.open_index().commit(r.object_store)
  4509. def _do_merge(
  4510. r: Repo,
  4511. merge_commit_id: bytes,
  4512. no_commit: bool = False,
  4513. no_ff: bool = False,
  4514. message: Optional[bytes] = None,
  4515. author: Optional[bytes] = None,
  4516. committer: Optional[bytes] = None,
  4517. ) -> tuple[Optional[bytes], list[bytes]]:
  4518. """Internal merge implementation that operates on an open repository.
  4519. Args:
  4520. r: Open repository object
  4521. merge_commit_id: SHA of commit to merge
  4522. no_commit: If True, do not create a merge commit
  4523. no_ff: If True, force creation of a merge commit
  4524. message: Optional merge commit message
  4525. author: Optional author for merge commit
  4526. committer: Optional committer for merge commit
  4527. Returns:
  4528. Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None
  4529. if no_commit=True or there were conflicts
  4530. """
  4531. from .graph import find_merge_base
  4532. from .merge import three_way_merge
  4533. # Get HEAD commit
  4534. try:
  4535. head_commit_id = r.refs[b"HEAD"]
  4536. except KeyError:
  4537. raise Error("No HEAD reference found")
  4538. head_commit = r[head_commit_id]
  4539. assert isinstance(head_commit, Commit), "Expected a Commit object"
  4540. merge_commit = r[merge_commit_id]
  4541. assert isinstance(merge_commit, Commit), "Expected a Commit object"
  4542. # Check if fast-forward is possible
  4543. merge_bases = find_merge_base(r, [head_commit_id, merge_commit_id])
  4544. if not merge_bases:
  4545. raise Error("No common ancestor found")
  4546. # Use the first merge base
  4547. base_commit_id = merge_bases[0]
  4548. # Check if we're trying to merge the same commit
  4549. if head_commit_id == merge_commit_id:
  4550. # Already up to date
  4551. return (None, [])
  4552. # Check for fast-forward
  4553. if base_commit_id == head_commit_id and not no_ff:
  4554. # Fast-forward merge
  4555. r.refs[b"HEAD"] = merge_commit_id
  4556. # Update the working directory
  4557. changes = tree_changes(r.object_store, head_commit.tree, merge_commit.tree)
  4558. update_working_tree(
  4559. r, head_commit.tree, merge_commit.tree, change_iterator=changes
  4560. )
  4561. return (merge_commit_id, [])
  4562. if base_commit_id == merge_commit_id:
  4563. # Already up to date
  4564. return (None, [])
  4565. # Perform three-way merge
  4566. base_commit = r[base_commit_id]
  4567. assert isinstance(base_commit, Commit), "Expected a Commit object"
  4568. gitattributes = r.get_gitattributes()
  4569. config = r.get_config()
  4570. merged_tree, conflicts = three_way_merge(
  4571. r.object_store, base_commit, head_commit, merge_commit, gitattributes, config
  4572. )
  4573. # Add merged tree to object store
  4574. r.object_store.add_object(merged_tree)
  4575. # Update index and working directory
  4576. changes = tree_changes(r.object_store, head_commit.tree, merged_tree.id)
  4577. update_working_tree(r, head_commit.tree, merged_tree.id, change_iterator=changes)
  4578. if conflicts or no_commit:
  4579. # Don't create a commit if there are conflicts or no_commit is True
  4580. return (None, conflicts)
  4581. # Create merge commit
  4582. merge_commit_obj = Commit()
  4583. merge_commit_obj.tree = merged_tree.id
  4584. merge_commit_obj.parents = [head_commit_id, merge_commit_id]
  4585. # Set author/committer
  4586. if author is None:
  4587. author = get_user_identity(r.get_config_stack())
  4588. if committer is None:
  4589. committer = author
  4590. merge_commit_obj.author = author
  4591. merge_commit_obj.committer = committer
  4592. # Set timestamps
  4593. timestamp = int(time.time())
  4594. timezone = 0 # UTC
  4595. merge_commit_obj.author_time = timestamp
  4596. merge_commit_obj.author_timezone = timezone
  4597. merge_commit_obj.commit_time = timestamp
  4598. merge_commit_obj.commit_timezone = timezone
  4599. # Set commit message
  4600. if message is None:
  4601. message = f"Merge commit '{merge_commit_id.decode()[:7]}'\n".encode()
  4602. merge_commit_obj.message = message.encode() if isinstance(message, str) else message
  4603. # Add commit to object store
  4604. r.object_store.add_object(merge_commit_obj)
  4605. # Update HEAD
  4606. r.refs[b"HEAD"] = merge_commit_obj.id
  4607. return (merge_commit_obj.id, [])
  4608. def merge(
  4609. repo: Union[str, os.PathLike[str], Repo],
  4610. committish: Union[str, bytes, Commit, Tag],
  4611. no_commit: bool = False,
  4612. no_ff: bool = False,
  4613. message: Optional[bytes] = None,
  4614. author: Optional[bytes] = None,
  4615. committer: Optional[bytes] = None,
  4616. ) -> tuple[Optional[bytes], list[bytes]]:
  4617. """Merge a commit into the current branch.
  4618. Args:
  4619. repo: Repository to merge into
  4620. committish: Commit to merge
  4621. no_commit: If True, do not create a merge commit
  4622. no_ff: If True, force creation of a merge commit
  4623. message: Optional merge commit message
  4624. author: Optional author for merge commit
  4625. committer: Optional committer for merge commit
  4626. Returns:
  4627. Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None
  4628. if no_commit=True or there were conflicts
  4629. Raises:
  4630. Error: If there is no HEAD reference or commit cannot be found
  4631. """
  4632. with open_repo_closing(repo) as r:
  4633. # Parse the commit to merge
  4634. try:
  4635. merge_commit_id = parse_commit(r, committish).id
  4636. except KeyError:
  4637. raise Error(
  4638. f"Cannot find commit '{committish.decode() if isinstance(committish, bytes) else committish}'"
  4639. )
  4640. result = _do_merge(
  4641. r, merge_commit_id, no_commit, no_ff, message, author, committer
  4642. )
  4643. # Trigger auto GC if needed
  4644. from .gc import maybe_auto_gc
  4645. maybe_auto_gc(r)
  4646. return result
  4647. def unpack_objects(
  4648. pack_path: Union[str, os.PathLike[str]], target: Union[str, os.PathLike[str]] = "."
  4649. ) -> int:
  4650. """Unpack objects from a pack file into the repository.
  4651. Args:
  4652. pack_path: Path to the pack file to unpack
  4653. target: Path to the repository to unpack into
  4654. Returns:
  4655. Number of objects unpacked
  4656. """
  4657. from .pack import Pack
  4658. with open_repo_closing(target) as r:
  4659. pack_basename = os.path.splitext(pack_path)[0]
  4660. with Pack(pack_basename) as pack:
  4661. count = 0
  4662. for unpacked in pack.iter_unpacked():
  4663. obj = unpacked.sha_file()
  4664. r.object_store.add_object(obj)
  4665. count += 1
  4666. return count
  4667. def merge_tree(
  4668. repo: RepoPath,
  4669. base_tree: Optional[Union[str, bytes, Tree, Commit, Tag]],
  4670. our_tree: Union[str, bytes, Tree, Commit, Tag],
  4671. their_tree: Union[str, bytes, Tree, Commit, Tag],
  4672. ) -> tuple[bytes, list[bytes]]:
  4673. """Perform a three-way tree merge without touching the working directory.
  4674. This is similar to git merge-tree, performing a merge at the tree level
  4675. without creating commits or updating any references.
  4676. Args:
  4677. repo: Repository containing the trees
  4678. base_tree: Tree-ish of the common ancestor (or None for no common ancestor)
  4679. our_tree: Tree-ish of our side of the merge
  4680. their_tree: Tree-ish of their side of the merge
  4681. Returns:
  4682. tuple: A tuple of (merged_tree_id, conflicts) where:
  4683. - merged_tree_id is the SHA-1 of the merged tree
  4684. - conflicts is a list of paths (as bytes) that had conflicts
  4685. Raises:
  4686. KeyError: If any of the tree-ish arguments cannot be resolved
  4687. """
  4688. from .merge import Merger
  4689. with open_repo_closing(repo) as r:
  4690. # Resolve tree-ish arguments to actual trees
  4691. base = parse_tree(r, base_tree) if base_tree else None
  4692. ours = parse_tree(r, our_tree)
  4693. theirs = parse_tree(r, their_tree)
  4694. # Perform the merge
  4695. gitattributes = r.get_gitattributes()
  4696. config = r.get_config()
  4697. merger = Merger(r.object_store, gitattributes, config)
  4698. merged_tree, conflicts = merger.merge_trees(base, ours, theirs)
  4699. # Add the merged tree to the object store
  4700. r.object_store.add_object(merged_tree)
  4701. return merged_tree.id, conflicts
  4702. def cherry_pick( # noqa: D417
  4703. repo: Union[str, os.PathLike[str], Repo],
  4704. committish: Union[str, bytes, Commit, Tag, None],
  4705. no_commit: bool = False,
  4706. continue_: bool = False,
  4707. abort: bool = False,
  4708. ) -> Optional[bytes]:
  4709. r"""Cherry-pick a commit onto the current branch.
  4710. Args:
  4711. repo: Repository to cherry-pick into
  4712. committish: Commit to cherry-pick (can be None only when resuming or aborting)
  4713. no_commit: If True, do not create a commit after applying changes
  4714. ``continue_``: Resume an in-progress cherry-pick after resolving conflicts if True
  4715. abort: Abort an in-progress cherry-pick
  4716. Returns:
  4717. The SHA of the newly created commit, or None if no_commit=True or there were conflicts
  4718. Raises:
  4719. Error: If there is no HEAD reference, commit cannot be found, or operation fails
  4720. """
  4721. from .merge import three_way_merge
  4722. # Validate that committish is provided when needed
  4723. if not (continue_ or abort) and committish is None:
  4724. raise ValueError("committish is required when not using --continue or --abort")
  4725. with open_repo_closing(repo) as r:
  4726. # Handle abort
  4727. if abort:
  4728. # Clean up any cherry-pick state
  4729. try:
  4730. os.remove(os.path.join(r.controldir(), "CHERRY_PICK_HEAD"))
  4731. except FileNotFoundError:
  4732. pass
  4733. try:
  4734. os.remove(os.path.join(r.controldir(), "MERGE_MSG"))
  4735. except FileNotFoundError:
  4736. pass
  4737. # Reset index to HEAD
  4738. head_commit = r[b"HEAD"]
  4739. assert isinstance(head_commit, Commit)
  4740. r.get_worktree().reset_index(head_commit.tree)
  4741. return None
  4742. # Handle continue
  4743. if continue_:
  4744. # Check if there's a cherry-pick in progress
  4745. cherry_pick_head_path = os.path.join(r.controldir(), "CHERRY_PICK_HEAD")
  4746. try:
  4747. with open(cherry_pick_head_path, "rb") as f:
  4748. cherry_pick_commit_id = f.read().strip()
  4749. cherry_pick_commit = r[cherry_pick_commit_id]
  4750. except FileNotFoundError:
  4751. raise Error("No cherry-pick in progress")
  4752. # Check for unresolved conflicts
  4753. if r.open_index().has_conflicts():
  4754. raise Error("Unresolved conflicts remain")
  4755. # Create the commit
  4756. tree_id = r.open_index().commit(r.object_store)
  4757. # Read saved message if any
  4758. merge_msg_path = os.path.join(r.controldir(), "MERGE_MSG")
  4759. try:
  4760. with open(merge_msg_path, "rb") as f:
  4761. message = f.read()
  4762. except FileNotFoundError:
  4763. assert isinstance(cherry_pick_commit, Commit)
  4764. message = cherry_pick_commit.message
  4765. assert isinstance(cherry_pick_commit, Commit)
  4766. new_commit = r.get_worktree().commit(
  4767. message=message,
  4768. tree=tree_id,
  4769. author=cherry_pick_commit.author,
  4770. author_timestamp=cherry_pick_commit.author_time,
  4771. author_timezone=cherry_pick_commit.author_timezone,
  4772. )
  4773. # Clean up state files
  4774. try:
  4775. os.remove(cherry_pick_head_path)
  4776. except FileNotFoundError:
  4777. pass
  4778. try:
  4779. os.remove(merge_msg_path)
  4780. except FileNotFoundError:
  4781. pass
  4782. return new_commit
  4783. # Normal cherry-pick operation
  4784. # Get current HEAD
  4785. try:
  4786. head_commit = r[b"HEAD"]
  4787. except KeyError:
  4788. raise Error("No HEAD reference found")
  4789. # Parse the commit to cherry-pick
  4790. # committish cannot be None here due to validation above
  4791. assert committish is not None
  4792. try:
  4793. cherry_pick_commit = parse_commit(r, committish)
  4794. except KeyError:
  4795. raise Error(
  4796. f"Cannot find commit '{committish.decode() if isinstance(committish, bytes) else committish}'"
  4797. )
  4798. # Check if commit has parents
  4799. assert isinstance(cherry_pick_commit, Commit)
  4800. if not cherry_pick_commit.parents:
  4801. raise Error("Cannot cherry-pick root commit")
  4802. # Get parent of cherry-pick commit
  4803. parent_commit = r[cherry_pick_commit.parents[0]]
  4804. assert isinstance(parent_commit, Commit)
  4805. # Perform three-way merge
  4806. assert isinstance(head_commit, Commit)
  4807. merged_tree, conflicts = three_way_merge(
  4808. r.object_store, parent_commit, head_commit, cherry_pick_commit
  4809. )
  4810. # Add merged tree to object store
  4811. r.object_store.add_object(merged_tree)
  4812. # Update working tree and index
  4813. # Reset index to match merged tree
  4814. r.get_worktree().reset_index(merged_tree.id)
  4815. # Update working tree from the new index
  4816. # Allow overwriting because we're applying the merge result
  4817. assert isinstance(head_commit, Commit)
  4818. changes = tree_changes(r.object_store, head_commit.tree, merged_tree.id)
  4819. update_working_tree(
  4820. r,
  4821. head_commit.tree,
  4822. merged_tree.id,
  4823. change_iterator=changes,
  4824. allow_overwrite_modified=True,
  4825. )
  4826. if conflicts:
  4827. # Save state for later continuation
  4828. with open(os.path.join(r.controldir(), "CHERRY_PICK_HEAD"), "wb") as f:
  4829. f.write(cherry_pick_commit.id + b"\n")
  4830. # Save commit message
  4831. with open(os.path.join(r.controldir(), "MERGE_MSG"), "wb") as f:
  4832. f.write(cherry_pick_commit.message)
  4833. raise Error(
  4834. f"Conflicts in: {', '.join(c.decode('utf-8', 'replace') for c in conflicts)}\n"
  4835. f"Fix conflicts and run 'dulwich cherry-pick --continue'"
  4836. )
  4837. if no_commit:
  4838. return None
  4839. # Create the commit
  4840. new_commit = r.get_worktree().commit(
  4841. message=cherry_pick_commit.message,
  4842. tree=merged_tree.id,
  4843. author=cherry_pick_commit.author,
  4844. author_timestamp=cherry_pick_commit.author_time,
  4845. author_timezone=cherry_pick_commit.author_timezone,
  4846. )
  4847. return new_commit
  4848. def revert(
  4849. repo: Union[str, os.PathLike[str], Repo],
  4850. commits: Union[str, bytes, Commit, Tag, Sequence[Union[str, bytes, Commit, Tag]]],
  4851. no_commit: bool = False,
  4852. message: Optional[Union[str, bytes]] = None,
  4853. author: Optional[bytes] = None,
  4854. committer: Optional[bytes] = None,
  4855. ) -> Optional[bytes]:
  4856. """Revert one or more commits.
  4857. This creates a new commit that undoes the changes introduced by the
  4858. specified commits. Unlike reset, revert creates a new commit that
  4859. preserves history.
  4860. Args:
  4861. repo: Path to repository or repository object
  4862. commits: List of commit-ish (SHA, ref, etc.) to revert, or a single commit-ish
  4863. no_commit: If True, apply changes to index/working tree but don't commit
  4864. message: Optional commit message (default: "Revert <original subject>")
  4865. author: Optional author for revert commit
  4866. committer: Optional committer for revert commit
  4867. Returns:
  4868. SHA1 of the new revert commit, or None if no_commit=True
  4869. Raises:
  4870. Error: If revert fails due to conflicts or other issues
  4871. """
  4872. from .merge import three_way_merge
  4873. # Normalize commits to a list
  4874. if isinstance(commits, (str, bytes, Commit, Tag)):
  4875. commits = [commits]
  4876. with open_repo_closing(repo) as r:
  4877. # Convert string refs to bytes
  4878. commits_to_revert = []
  4879. for commit_ref in commits:
  4880. if isinstance(commit_ref, str):
  4881. commit_ref = commit_ref.encode("utf-8")
  4882. commit = parse_commit(r, commit_ref)
  4883. commits_to_revert.append(commit)
  4884. # Get current HEAD
  4885. try:
  4886. head_commit_id = r.refs[b"HEAD"]
  4887. except KeyError:
  4888. raise Error("No HEAD reference found")
  4889. head_commit = r[head_commit_id]
  4890. assert isinstance(head_commit, Commit)
  4891. current_tree = head_commit.tree
  4892. # Process commits in order
  4893. for commit_to_revert in commits_to_revert:
  4894. # For revert, we want to apply the inverse of the commit
  4895. # This means using the commit's tree as "base" and its parent as "theirs"
  4896. if not commit_to_revert.parents:
  4897. raise Error(
  4898. 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"
  4899. )
  4900. # For simplicity, we only handle commits with one parent (no merge commits)
  4901. if len(commit_to_revert.parents) > 1:
  4902. raise Error(
  4903. 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"
  4904. )
  4905. parent_commit = r[commit_to_revert.parents[0]]
  4906. assert isinstance(parent_commit, Commit)
  4907. # Perform three-way merge:
  4908. # - base: the commit we're reverting (what we want to remove)
  4909. # - ours: current HEAD (what we have now)
  4910. # - theirs: parent of commit being reverted (what we want to go back to)
  4911. assert isinstance(commit_to_revert, Commit)
  4912. head_for_merge = r[head_commit_id]
  4913. assert isinstance(head_for_merge, Commit)
  4914. merged_tree, conflicts = three_way_merge(
  4915. r.object_store,
  4916. commit_to_revert, # base
  4917. head_for_merge, # ours
  4918. parent_commit, # theirs
  4919. )
  4920. if conflicts:
  4921. # Update working tree with conflicts
  4922. changes = tree_changes(r.object_store, current_tree, merged_tree.id)
  4923. update_working_tree(
  4924. r, current_tree, merged_tree.id, change_iterator=changes
  4925. )
  4926. conflicted_paths = [c.decode("utf-8", "replace") for c in conflicts]
  4927. raise Error(f"Conflicts while reverting: {', '.join(conflicted_paths)}")
  4928. # Add merged tree to object store
  4929. r.object_store.add_object(merged_tree)
  4930. # Update working tree
  4931. changes = tree_changes(r.object_store, current_tree, merged_tree.id)
  4932. update_working_tree(
  4933. r, current_tree, merged_tree.id, change_iterator=changes
  4934. )
  4935. current_tree = merged_tree.id
  4936. if not no_commit:
  4937. # Create revert commit
  4938. revert_commit = Commit()
  4939. revert_commit.tree = merged_tree.id
  4940. revert_commit.parents = [head_commit_id]
  4941. # Set author/committer
  4942. if author is None:
  4943. author = get_user_identity(r.get_config_stack())
  4944. if committer is None:
  4945. committer = author
  4946. revert_commit.author = author
  4947. revert_commit.committer = committer
  4948. # Set timestamps
  4949. timestamp = int(time.time())
  4950. timezone = 0 # UTC
  4951. revert_commit.author_time = timestamp
  4952. revert_commit.author_timezone = timezone
  4953. revert_commit.commit_time = timestamp
  4954. revert_commit.commit_timezone = timezone
  4955. # Set message
  4956. if message is None:
  4957. # Extract original commit subject
  4958. original_message = commit_to_revert.message
  4959. if isinstance(original_message, bytes):
  4960. original_message = original_message.decode("utf-8", "replace")
  4961. subject = original_message.split("\n")[0]
  4962. message = f'Revert "{subject}"\n\nThis reverts commit {commit_to_revert.id.decode("ascii")}.'.encode()
  4963. elif isinstance(message, str):
  4964. message = message.encode("utf-8")
  4965. revert_commit.message = message
  4966. # Add commit to object store
  4967. r.object_store.add_object(revert_commit)
  4968. # Update HEAD
  4969. r.refs[b"HEAD"] = revert_commit.id
  4970. head_commit_id = revert_commit.id
  4971. return head_commit_id if not no_commit else None
  4972. def gc(
  4973. repo: RepoPath,
  4974. auto: bool = False,
  4975. aggressive: bool = False,
  4976. prune: bool = True,
  4977. grace_period: Optional[int] = 1209600, # 2 weeks default
  4978. dry_run: bool = False,
  4979. progress: Optional[Callable[[str], None]] = None,
  4980. ) -> "GCStats":
  4981. """Run garbage collection on a repository.
  4982. Args:
  4983. repo: Path to the repository or a Repo object
  4984. auto: If True, only run gc if needed
  4985. aggressive: If True, use more aggressive settings
  4986. prune: If True, prune unreachable objects
  4987. grace_period: Grace period in seconds for pruning (default 2 weeks)
  4988. dry_run: If True, only report what would be done
  4989. progress: Optional progress callback
  4990. Returns:
  4991. GCStats object with garbage collection statistics
  4992. """
  4993. from .gc import garbage_collect
  4994. with open_repo_closing(repo) as r:
  4995. return garbage_collect(
  4996. r,
  4997. auto=auto,
  4998. aggressive=aggressive,
  4999. prune=prune,
  5000. grace_period=grace_period,
  5001. dry_run=dry_run,
  5002. progress=progress,
  5003. )
  5004. def prune(
  5005. repo: RepoPath,
  5006. grace_period: Optional[int] = None,
  5007. dry_run: bool = False,
  5008. progress: Optional[Callable[[str], None]] = None,
  5009. ) -> None:
  5010. """Prune/clean up a repository's object store.
  5011. This removes temporary files that were left behind by interrupted
  5012. pack operations.
  5013. Args:
  5014. repo: Path to the repository or a Repo object
  5015. grace_period: Grace period in seconds for removing temporary files
  5016. (default 2 weeks)
  5017. dry_run: If True, only report what would be done
  5018. progress: Optional progress callback
  5019. """
  5020. with open_repo_closing(repo) as r:
  5021. if progress:
  5022. progress("Pruning temporary files")
  5023. if not dry_run:
  5024. r.object_store.prune(grace_period=grace_period)
  5025. def count_objects(repo: RepoPath = ".", verbose: bool = False) -> CountObjectsResult:
  5026. """Count unpacked objects and their disk usage.
  5027. Args:
  5028. repo: Path to repository or repository object
  5029. verbose: Whether to return verbose information
  5030. Returns:
  5031. CountObjectsResult object with detailed statistics
  5032. """
  5033. with open_repo_closing(repo) as r:
  5034. object_store = r.object_store
  5035. # Count loose objects
  5036. loose_count = 0
  5037. loose_size = 0
  5038. for sha in object_store._iter_loose_objects():
  5039. loose_count += 1
  5040. from .object_store import DiskObjectStore
  5041. assert isinstance(object_store, DiskObjectStore)
  5042. path = object_store._get_shafile_path(sha)
  5043. try:
  5044. stat_info = os.stat(path)
  5045. # Git uses disk usage, not file size. st_blocks is always in
  5046. # 512-byte blocks per POSIX standard
  5047. st_blocks = getattr(stat_info, "st_blocks", None)
  5048. if st_blocks is not None:
  5049. # Available on Linux and macOS
  5050. loose_size += st_blocks * 512
  5051. else:
  5052. # Fallback for Windows
  5053. loose_size += stat_info.st_size
  5054. except FileNotFoundError:
  5055. # Object may have been removed between iteration and stat
  5056. pass
  5057. if not verbose:
  5058. return CountObjectsResult(count=loose_count, size=loose_size)
  5059. # Count pack information
  5060. pack_count = len(object_store.packs)
  5061. in_pack_count = 0
  5062. pack_size = 0
  5063. for pack in object_store.packs:
  5064. in_pack_count += len(pack)
  5065. # Get pack file size
  5066. pack_path = pack._data_path
  5067. try:
  5068. pack_size += os.path.getsize(pack_path)
  5069. except FileNotFoundError:
  5070. pass
  5071. # Get index file size
  5072. idx_path = pack._idx_path
  5073. try:
  5074. pack_size += os.path.getsize(idx_path)
  5075. except FileNotFoundError:
  5076. pass
  5077. return CountObjectsResult(
  5078. count=loose_count,
  5079. size=loose_size,
  5080. in_pack=in_pack_count,
  5081. packs=pack_count,
  5082. size_pack=pack_size,
  5083. )
  5084. def is_interactive_rebase(repo: Union[Repo, str]) -> bool:
  5085. """Check if an interactive rebase is in progress.
  5086. Args:
  5087. repo: Repository to check
  5088. Returns:
  5089. True if interactive rebase is in progress, False otherwise
  5090. """
  5091. with open_repo_closing(repo) as r:
  5092. state_manager = r.get_rebase_state_manager()
  5093. if not state_manager.exists():
  5094. return False
  5095. # Check if todo file exists
  5096. todo = state_manager.load_todo()
  5097. return todo is not None
  5098. def rebase(
  5099. repo: Union[Repo, str],
  5100. upstream: Union[bytes, str],
  5101. onto: Optional[Union[bytes, str]] = None,
  5102. branch: Optional[Union[bytes, str]] = None,
  5103. abort: bool = False,
  5104. continue_rebase: bool = False,
  5105. skip: bool = False,
  5106. interactive: bool = False,
  5107. edit_todo: bool = False,
  5108. ) -> list[bytes]:
  5109. """Rebase commits onto another branch.
  5110. Args:
  5111. repo: Repository to rebase in
  5112. upstream: Upstream branch/commit to rebase onto
  5113. onto: Specific commit to rebase onto (defaults to upstream)
  5114. branch: Branch to rebase (defaults to current branch)
  5115. abort: Abort an in-progress rebase
  5116. continue_rebase: Continue an in-progress rebase
  5117. skip: Skip current commit and continue rebase
  5118. interactive: Start an interactive rebase
  5119. edit_todo: Edit the todo list of an interactive rebase
  5120. Returns:
  5121. List of new commit SHAs created by rebase
  5122. Raises:
  5123. Error: If rebase fails or conflicts occur
  5124. """
  5125. from .cli import launch_editor
  5126. from .rebase import (
  5127. RebaseConflict,
  5128. RebaseError,
  5129. Rebaser,
  5130. process_interactive_rebase,
  5131. start_interactive,
  5132. )
  5133. from .rebase import (
  5134. edit_todo as edit_todo_func,
  5135. )
  5136. with open_repo_closing(repo) as r:
  5137. rebaser = Rebaser(r)
  5138. if abort:
  5139. try:
  5140. rebaser.abort()
  5141. return []
  5142. except RebaseError as e:
  5143. raise Error(str(e))
  5144. if edit_todo:
  5145. # Edit the todo list of an interactive rebase
  5146. try:
  5147. edit_todo_func(r, launch_editor)
  5148. print("Todo list updated. Continue with 'rebase --continue'")
  5149. return []
  5150. except RebaseError as e:
  5151. raise Error(str(e))
  5152. if continue_rebase:
  5153. try:
  5154. if interactive:
  5155. # Continue interactive rebase
  5156. is_complete, pause_reason = process_interactive_rebase(
  5157. r, editor_callback=launch_editor
  5158. )
  5159. if is_complete:
  5160. return [c.id for c in rebaser._done]
  5161. else:
  5162. if pause_reason == "conflict":
  5163. raise Error("Conflicts detected. Resolve and continue.")
  5164. elif pause_reason == "edit":
  5165. print("Stopped for editing. Make changes and continue.")
  5166. elif pause_reason == "break":
  5167. print("Rebase paused at break. Continue when ready.")
  5168. else:
  5169. print(f"Rebase paused: {pause_reason}")
  5170. return []
  5171. else:
  5172. # Continue regular rebase
  5173. result = rebaser.continue_()
  5174. if result is None:
  5175. # Rebase complete
  5176. return [c.id for c in rebaser._done]
  5177. elif isinstance(result, tuple) and result[1]:
  5178. # Still have conflicts
  5179. raise Error(
  5180. f"Conflicts in: {', '.join(f.decode('utf-8', 'replace') for f in result[1])}"
  5181. )
  5182. except RebaseError as e:
  5183. raise Error(str(e))
  5184. # Convert string refs to bytes
  5185. if isinstance(upstream, str):
  5186. upstream = upstream.encode("utf-8")
  5187. if isinstance(onto, str):
  5188. onto = onto.encode("utf-8") if onto else None
  5189. if isinstance(branch, str):
  5190. branch = branch.encode("utf-8") if branch else None
  5191. try:
  5192. if interactive:
  5193. # Start interactive rebase
  5194. todo = start_interactive(r, upstream, onto, branch, launch_editor)
  5195. # Process the todo list
  5196. is_complete, pause_reason = process_interactive_rebase(
  5197. r, todo, editor_callback=launch_editor
  5198. )
  5199. if is_complete:
  5200. return [c.id for c in rebaser._done]
  5201. else:
  5202. if pause_reason == "conflict":
  5203. raise Error("Conflicts detected. Resolve and continue.")
  5204. elif pause_reason == "edit":
  5205. print("Stopped for editing. Make changes and continue.")
  5206. elif pause_reason == "break":
  5207. print("Rebase paused at break. Continue when ready.")
  5208. else:
  5209. print(f"Rebase paused: {pause_reason}")
  5210. return []
  5211. else:
  5212. # Regular rebase
  5213. rebaser.start(upstream, onto, branch)
  5214. # Continue rebase automatically
  5215. result = rebaser.continue_()
  5216. if result is not None:
  5217. # Conflicts
  5218. raise RebaseConflict(result[1])
  5219. # Return the SHAs of the rebased commits
  5220. return [c.id for c in rebaser._done]
  5221. except RebaseConflict as e:
  5222. raise Error(str(e))
  5223. except RebaseError as e:
  5224. raise Error(str(e))
  5225. def annotate(
  5226. repo: RepoPath,
  5227. path: Union[str, bytes],
  5228. committish: Optional[Union[str, bytes, Commit, Tag]] = None,
  5229. ) -> list[tuple[tuple[Commit, TreeEntry], bytes]]:
  5230. """Annotate the history of a file.
  5231. :param repo: Path to the repository
  5232. :param path: Path to annotate
  5233. :param committish: Commit id to find path in
  5234. :return: List of ((Commit, TreeChange), line) tuples
  5235. """
  5236. if committish is None:
  5237. committish = "HEAD"
  5238. from dulwich.annotate import annotate_lines
  5239. with open_repo_closing(repo) as r:
  5240. commit_id = parse_commit(r, committish).id
  5241. # Ensure path is bytes
  5242. if isinstance(path, str):
  5243. path = path.encode()
  5244. return annotate_lines(r.object_store, commit_id, path)
  5245. blame = annotate
  5246. def filter_branch(
  5247. repo: RepoPath = ".",
  5248. branch: Union[str, bytes] = "HEAD",
  5249. *,
  5250. filter_fn: Optional[Callable[[Commit], Optional["CommitData"]]] = None,
  5251. filter_author: Optional[Callable[[bytes], Optional[bytes]]] = None,
  5252. filter_committer: Optional[Callable[[bytes], Optional[bytes]]] = None,
  5253. filter_message: Optional[Callable[[bytes], Optional[bytes]]] = None,
  5254. tree_filter: Optional[Callable[[bytes, str], Optional[bytes]]] = None,
  5255. index_filter: Optional[Callable[[bytes, str], Optional[bytes]]] = None,
  5256. parent_filter: Optional[Callable[[Sequence[bytes]], list[bytes]]] = None,
  5257. commit_filter: Optional[Callable[[Commit, bytes], Optional[bytes]]] = None,
  5258. subdirectory_filter: Optional[Union[str, bytes]] = None,
  5259. prune_empty: bool = False,
  5260. tag_name_filter: Optional[Callable[[bytes], Optional[bytes]]] = None,
  5261. force: bool = False,
  5262. keep_original: bool = True,
  5263. refs: Optional[list[bytes]] = None,
  5264. ) -> dict[bytes, bytes]:
  5265. """Rewrite branch history by creating new commits with filtered properties.
  5266. This is similar to git filter-branch, allowing you to rewrite commit
  5267. history by modifying trees, parents, author, committer, or commit messages.
  5268. Args:
  5269. repo: Path to repository
  5270. branch: Branch to rewrite (defaults to HEAD)
  5271. filter_fn: Optional callable that takes a Commit object and returns
  5272. a dict of updated fields (author, committer, message, etc.)
  5273. filter_author: Optional callable that takes author bytes and returns
  5274. updated author bytes or None to keep unchanged
  5275. filter_committer: Optional callable that takes committer bytes and returns
  5276. updated committer bytes or None to keep unchanged
  5277. filter_message: Optional callable that takes commit message bytes
  5278. and returns updated message bytes
  5279. tree_filter: Optional callable that takes (tree_sha, temp_dir) and returns
  5280. new tree SHA after modifying working directory
  5281. index_filter: Optional callable that takes (tree_sha, temp_index_path) and
  5282. returns new tree SHA after modifying index
  5283. parent_filter: Optional callable that takes parent list and returns
  5284. modified parent list
  5285. commit_filter: Optional callable that takes (Commit, tree_sha) and returns
  5286. new commit SHA or None to skip commit
  5287. subdirectory_filter: Optional subdirectory path to extract as new root
  5288. prune_empty: Whether to prune commits that become empty
  5289. tag_name_filter: Optional callable to rename tags
  5290. force: Force operation even if branch has been filtered before
  5291. keep_original: Keep original refs under refs/original/
  5292. refs: List of refs to rewrite (defaults to [branch])
  5293. Returns:
  5294. Dict mapping old commit SHAs to new commit SHAs
  5295. Raises:
  5296. Error: If branch is already filtered and force is False
  5297. """
  5298. from .filter_branch import CommitFilter, filter_refs
  5299. with open_repo_closing(repo) as r:
  5300. # Parse branch/committish
  5301. if isinstance(branch, str):
  5302. branch = branch.encode()
  5303. # Determine which refs to process
  5304. if refs is None:
  5305. if branch == b"HEAD":
  5306. # Resolve HEAD to actual branch
  5307. try:
  5308. resolved = r.refs.follow(b"HEAD")
  5309. if resolved and resolved[0]:
  5310. # resolved is a list of (refname, sha) tuples
  5311. resolved_ref = resolved[0][-1]
  5312. if resolved_ref and resolved_ref != b"HEAD":
  5313. refs = [resolved_ref]
  5314. else:
  5315. # HEAD points directly to a commit
  5316. refs = [b"HEAD"]
  5317. else:
  5318. refs = [b"HEAD"]
  5319. except SymrefLoop:
  5320. refs = [b"HEAD"]
  5321. else:
  5322. # Convert branch name to full ref if needed
  5323. if not branch.startswith(b"refs/"):
  5324. branch = b"refs/heads/" + branch
  5325. refs = [branch]
  5326. # Convert subdirectory filter to bytes if needed
  5327. if subdirectory_filter:
  5328. if isinstance(subdirectory_filter, str):
  5329. subdirectory_filter = subdirectory_filter.encode()
  5330. else:
  5331. subdirectory_filter = None
  5332. # Create commit filter
  5333. filter_obj = CommitFilter(
  5334. r.object_store,
  5335. filter_fn=filter_fn,
  5336. filter_author=filter_author,
  5337. filter_committer=filter_committer,
  5338. filter_message=filter_message,
  5339. tree_filter=tree_filter,
  5340. index_filter=index_filter,
  5341. parent_filter=parent_filter,
  5342. commit_filter=commit_filter,
  5343. subdirectory_filter=subdirectory_filter,
  5344. prune_empty=prune_empty,
  5345. tag_name_filter=tag_name_filter,
  5346. )
  5347. # Tag callback for renaming tags
  5348. def rename_tag(old_ref: bytes, new_ref: bytes) -> None:
  5349. # Copy tag to new name
  5350. r.refs[new_ref] = r.refs[old_ref]
  5351. # Delete old tag
  5352. del r.refs[old_ref]
  5353. # Filter refs
  5354. try:
  5355. return filter_refs(
  5356. r.refs,
  5357. r.object_store,
  5358. refs,
  5359. filter_obj,
  5360. keep_original=keep_original,
  5361. force=force,
  5362. tag_callback=rename_tag if tag_name_filter else None,
  5363. )
  5364. except ValueError as e:
  5365. raise Error(str(e)) from e
  5366. def format_patch(
  5367. repo: RepoPath = ".",
  5368. committish: Optional[Union[bytes, tuple[bytes, bytes]]] = None,
  5369. outstream: TextIO = sys.stdout,
  5370. outdir: Optional[Union[str, os.PathLike[str]]] = None,
  5371. n: int = 1,
  5372. stdout: bool = False,
  5373. version: Optional[str] = None,
  5374. ) -> list[str]:
  5375. """Generate patches suitable for git am.
  5376. Args:
  5377. repo: Path to repository
  5378. committish: Commit-ish or commit range to generate patches for.
  5379. Can be a single commit id, or a tuple of (start, end) commit ids
  5380. for a range. If None, formats the last n commits from HEAD.
  5381. outstream: Stream to write to if stdout=True
  5382. outdir: Directory to write patch files to (default: current directory)
  5383. n: Number of patches to generate if committish is None
  5384. stdout: Write patches to stdout instead of files
  5385. version: Version string to include in patches (default: Dulwich version)
  5386. Returns:
  5387. List of patch filenames that were created (empty if stdout=True)
  5388. """
  5389. if outdir is None:
  5390. outdir = "."
  5391. filenames = []
  5392. with open_repo_closing(repo) as r:
  5393. # Determine which commits to format
  5394. commits_to_format = []
  5395. if committish is None:
  5396. # Get the last n commits from HEAD
  5397. try:
  5398. walker = r.get_walker()
  5399. for entry in walker:
  5400. commits_to_format.append(entry.commit)
  5401. if len(commits_to_format) >= n:
  5402. break
  5403. commits_to_format.reverse()
  5404. except KeyError:
  5405. # No HEAD or empty repository
  5406. pass
  5407. elif isinstance(committish, tuple):
  5408. # Handle commit range (start, end)
  5409. start_commit, end_commit = committish
  5410. # Extract commit IDs from commit objects if needed
  5411. start_id = (
  5412. start_commit.id if isinstance(start_commit, Commit) else start_commit
  5413. )
  5414. end_id = end_commit.id if isinstance(end_commit, Commit) else end_commit
  5415. # Walk from end back to start
  5416. walker = r.get_walker(include=[end_id], exclude=[start_id])
  5417. for entry in walker:
  5418. commits_to_format.append(entry.commit)
  5419. commits_to_format.reverse()
  5420. else:
  5421. # Single commit
  5422. commit = r.object_store[committish]
  5423. assert isinstance(commit, Commit)
  5424. commits_to_format.append(commit)
  5425. # Generate patches
  5426. total = len(commits_to_format)
  5427. for i, commit in enumerate(commits_to_format, 1):
  5428. assert isinstance(commit, Commit)
  5429. # Get the parent
  5430. if commit.parents:
  5431. parent_id = commit.parents[0]
  5432. parent = r.object_store[parent_id]
  5433. assert isinstance(parent, Commit)
  5434. else:
  5435. parent = None
  5436. # Generate the diff
  5437. from io import BytesIO
  5438. diff_content = BytesIO()
  5439. if parent:
  5440. write_tree_diff(
  5441. diff_content,
  5442. r.object_store,
  5443. parent.tree,
  5444. commit.tree,
  5445. )
  5446. else:
  5447. # Initial commit - diff against empty tree
  5448. write_tree_diff(
  5449. diff_content,
  5450. r.object_store,
  5451. None,
  5452. commit.tree,
  5453. )
  5454. # Generate patch with commit metadata
  5455. if stdout:
  5456. # Get binary stream from TextIO
  5457. if hasattr(outstream, "buffer"):
  5458. binary_out: IO[bytes] = outstream.buffer
  5459. else:
  5460. # Fallback for non-text streams
  5461. binary_out = outstream # type: ignore[assignment]
  5462. write_commit_patch(
  5463. binary_out,
  5464. commit,
  5465. diff_content.getvalue(),
  5466. (i, total),
  5467. version=version,
  5468. )
  5469. else:
  5470. # Generate filename
  5471. summary = get_summary(commit)
  5472. filename = os.path.join(outdir, f"{i:04d}-{summary}.patch")
  5473. with open(filename, "wb") as f:
  5474. write_commit_patch(
  5475. f,
  5476. commit,
  5477. diff_content.getvalue(),
  5478. (i, total),
  5479. version=version,
  5480. )
  5481. filenames.append(filename)
  5482. return filenames
  5483. def bisect_start(
  5484. repo: Union[str, os.PathLike[str], Repo] = ".",
  5485. bad: Optional[Union[str, bytes, Commit, Tag]] = None,
  5486. good: Optional[
  5487. Union[str, bytes, Commit, Tag, Sequence[Union[str, bytes, Commit, Tag]]]
  5488. ] = None,
  5489. paths: Optional[Sequence[bytes]] = None,
  5490. no_checkout: bool = False,
  5491. term_bad: str = "bad",
  5492. term_good: str = "good",
  5493. ) -> Optional[bytes]:
  5494. """Start a new bisect session.
  5495. Args:
  5496. repo: Path to repository or a Repo object
  5497. bad: The bad commit (defaults to HEAD)
  5498. good: List of good commits or a single good commit
  5499. paths: Optional paths to limit bisect to
  5500. no_checkout: If True, don't checkout commits during bisect
  5501. term_bad: Term to use for bad commits (default: "bad")
  5502. term_good: Term to use for good commits (default: "good")
  5503. """
  5504. with open_repo_closing(repo) as r:
  5505. state = BisectState(r)
  5506. # Convert single good commit to sequence
  5507. if good is not None and isinstance(good, (str, bytes, Commit, Tag)):
  5508. good = [good]
  5509. # Parse commits
  5510. bad_sha = parse_commit(r, bad).id if bad else None
  5511. good_shas = [parse_commit(r, g).id for g in good] if good else None
  5512. state.start(bad_sha, good_shas, paths, no_checkout, term_bad, term_good)
  5513. # Return the next commit to test if we have both good and bad
  5514. if bad_sha and good_shas:
  5515. next_sha = state._find_next_commit()
  5516. if next_sha and not no_checkout:
  5517. # Checkout the next commit
  5518. old_commit = r[r.head()]
  5519. assert isinstance(old_commit, Commit)
  5520. old_tree = old_commit.tree if r.head() else None
  5521. r.refs[b"HEAD"] = next_sha
  5522. commit = r[next_sha]
  5523. assert isinstance(commit, Commit)
  5524. changes = tree_changes(r.object_store, old_tree, commit.tree)
  5525. update_working_tree(r, old_tree, commit.tree, change_iterator=changes)
  5526. return next_sha
  5527. return None
  5528. def bisect_bad(
  5529. repo: Union[str, os.PathLike[str], Repo] = ".",
  5530. rev: Optional[Union[str, bytes, Commit, Tag]] = None,
  5531. ) -> Optional[bytes]:
  5532. """Mark a commit as bad.
  5533. Args:
  5534. repo: Path to repository or a Repo object
  5535. rev: Commit to mark as bad (defaults to HEAD)
  5536. Returns:
  5537. The SHA of the next commit to test, or None if bisect is complete
  5538. """
  5539. with open_repo_closing(repo) as r:
  5540. state = BisectState(r)
  5541. rev_sha = parse_commit(r, rev).id if rev else None
  5542. next_sha = state.mark_bad(rev_sha)
  5543. if next_sha:
  5544. # Checkout the next commit
  5545. old_commit = r[r.head()]
  5546. assert isinstance(old_commit, Commit)
  5547. old_tree = old_commit.tree if r.head() else None
  5548. r.refs[b"HEAD"] = next_sha
  5549. commit = r[next_sha]
  5550. assert isinstance(commit, Commit)
  5551. changes = tree_changes(r.object_store, old_tree, commit.tree)
  5552. update_working_tree(r, old_tree, commit.tree, change_iterator=changes)
  5553. return next_sha
  5554. def bisect_good(
  5555. repo: Union[str, os.PathLike[str], Repo] = ".",
  5556. rev: Optional[Union[str, bytes, Commit, Tag]] = None,
  5557. ) -> Optional[bytes]:
  5558. """Mark a commit as good.
  5559. Args:
  5560. repo: Path to repository or a Repo object
  5561. rev: Commit to mark as good (defaults to HEAD)
  5562. Returns:
  5563. The SHA of the next commit to test, or None if bisect is complete
  5564. """
  5565. with open_repo_closing(repo) as r:
  5566. state = BisectState(r)
  5567. rev_sha = parse_commit(r, rev).id if rev else None
  5568. next_sha = state.mark_good(rev_sha)
  5569. if next_sha:
  5570. # Checkout the next commit
  5571. old_commit = r[r.head()]
  5572. assert isinstance(old_commit, Commit)
  5573. old_tree = old_commit.tree if r.head() else None
  5574. r.refs[b"HEAD"] = next_sha
  5575. commit = r[next_sha]
  5576. assert isinstance(commit, Commit)
  5577. changes = tree_changes(r.object_store, old_tree, commit.tree)
  5578. update_working_tree(r, old_tree, commit.tree, change_iterator=changes)
  5579. return next_sha
  5580. def bisect_skip(
  5581. repo: Union[str, os.PathLike[str], Repo] = ".",
  5582. revs: Optional[
  5583. Union[str, bytes, Commit, Tag, Sequence[Union[str, bytes, Commit, Tag]]]
  5584. ] = None,
  5585. ) -> Optional[bytes]:
  5586. """Skip one or more commits.
  5587. Args:
  5588. repo: Path to repository or a Repo object
  5589. revs: List of commits to skip (defaults to [HEAD])
  5590. Returns:
  5591. The SHA of the next commit to test, or None if bisect is complete
  5592. """
  5593. with open_repo_closing(repo) as r:
  5594. state = BisectState(r)
  5595. if revs is None:
  5596. rev_shas = None
  5597. else:
  5598. # Convert single rev to sequence
  5599. if isinstance(revs, (str, bytes, Commit, Tag)):
  5600. revs = [revs]
  5601. rev_shas = [parse_commit(r, rev).id for rev in revs]
  5602. next_sha = state.skip(rev_shas)
  5603. if next_sha:
  5604. # Checkout the next commit
  5605. old_commit = r[r.head()]
  5606. assert isinstance(old_commit, Commit)
  5607. old_tree = old_commit.tree if r.head() else None
  5608. r.refs[b"HEAD"] = next_sha
  5609. commit = r[next_sha]
  5610. assert isinstance(commit, Commit)
  5611. changes = tree_changes(r.object_store, old_tree, commit.tree)
  5612. update_working_tree(r, old_tree, commit.tree, change_iterator=changes)
  5613. return next_sha
  5614. def bisect_reset(
  5615. repo: Union[str, os.PathLike[str], Repo] = ".",
  5616. commit: Optional[Union[str, bytes, Commit, Tag]] = None,
  5617. ) -> None:
  5618. """Reset bisect state and return to original branch/commit.
  5619. Args:
  5620. repo: Path to repository or a Repo object
  5621. commit: Optional commit to reset to (defaults to original branch/commit)
  5622. """
  5623. with open_repo_closing(repo) as r:
  5624. state = BisectState(r)
  5625. # Get old tree before reset
  5626. try:
  5627. old_commit = r[r.head()]
  5628. assert isinstance(old_commit, Commit)
  5629. old_tree = old_commit.tree
  5630. except KeyError:
  5631. old_tree = None
  5632. commit_sha = parse_commit(r, commit).id if commit else None
  5633. state.reset(commit_sha)
  5634. # Update working tree to new HEAD
  5635. try:
  5636. new_head = r.head()
  5637. if new_head:
  5638. new_commit = r[new_head]
  5639. assert isinstance(new_commit, Commit)
  5640. changes = tree_changes(r.object_store, old_tree, new_commit.tree)
  5641. update_working_tree(
  5642. r, old_tree, new_commit.tree, change_iterator=changes
  5643. )
  5644. except KeyError:
  5645. # No HEAD after reset
  5646. pass
  5647. def bisect_log(repo: Union[str, os.PathLike[str], Repo] = ".") -> str:
  5648. """Get the bisect log.
  5649. Args:
  5650. repo: Path to repository or a Repo object
  5651. Returns:
  5652. The bisect log as a string
  5653. """
  5654. with open_repo_closing(repo) as r:
  5655. state = BisectState(r)
  5656. return state.get_log()
  5657. def bisect_replay(
  5658. repo: Union[str, os.PathLike[str], Repo],
  5659. log_file: Union[str, os.PathLike[str], BinaryIO],
  5660. ) -> None:
  5661. """Replay a bisect log.
  5662. Args:
  5663. repo: Path to repository or a Repo object
  5664. log_file: Path to the log file or file-like object
  5665. """
  5666. with open_repo_closing(repo) as r:
  5667. state = BisectState(r)
  5668. if isinstance(log_file, (str, os.PathLike)):
  5669. with open(log_file) as f:
  5670. log_content = f.read()
  5671. else:
  5672. content = log_file.read()
  5673. log_content = content.decode() if isinstance(content, bytes) else content
  5674. state.replay(log_content)
  5675. def reflog(
  5676. repo: RepoPath = ".", ref: Union[str, bytes] = b"HEAD", all: bool = False
  5677. ) -> Iterator[Union[Any, tuple[bytes, Any]]]:
  5678. """Show reflog entries for a reference or all references.
  5679. Args:
  5680. repo: Path to repository or a Repo object
  5681. ref: Reference name (defaults to HEAD)
  5682. all: If True, show reflogs for all refs (ignores ref parameter)
  5683. Yields:
  5684. If all=False: ReflogEntry objects
  5685. If all=True: Tuples of (ref_name, ReflogEntry) for all refs with reflogs
  5686. """
  5687. import os
  5688. from .reflog import iter_reflogs
  5689. if isinstance(ref, str):
  5690. ref = ref.encode("utf-8")
  5691. with open_repo_closing(repo) as r:
  5692. if not all:
  5693. yield from r.read_reflog(ref)
  5694. else:
  5695. logs_dir = os.path.join(r.controldir(), "logs")
  5696. # Use iter_reflogs to discover all reflogs
  5697. for ref_bytes in iter_reflogs(logs_dir):
  5698. # Read the reflog entries for this ref
  5699. for entry in r.read_reflog(ref_bytes):
  5700. yield (ref_bytes, entry)
  5701. def lfs_track(
  5702. repo: Union[str, os.PathLike[str], Repo] = ".",
  5703. patterns: Optional[Sequence[str]] = None,
  5704. ) -> list[str]:
  5705. """Track file patterns with Git LFS.
  5706. Args:
  5707. repo: Path to repository
  5708. patterns: List of file patterns to track (e.g., ["*.bin", "*.pdf"])
  5709. If None, returns current tracked patterns
  5710. Returns:
  5711. List of tracked patterns
  5712. """
  5713. from .attrs import GitAttributes
  5714. with open_repo_closing(repo) as r:
  5715. gitattributes_path = os.path.join(r.path, ".gitattributes")
  5716. # Load existing GitAttributes
  5717. if os.path.exists(gitattributes_path):
  5718. gitattributes = GitAttributes.from_file(gitattributes_path)
  5719. else:
  5720. gitattributes = GitAttributes()
  5721. if patterns is None:
  5722. # Return current LFS tracked patterns
  5723. tracked = []
  5724. for pattern_obj, attrs in gitattributes:
  5725. if attrs.get(b"filter") == b"lfs":
  5726. tracked.append(pattern_obj.pattern.decode())
  5727. return tracked
  5728. # Add new patterns
  5729. for pattern in patterns:
  5730. # Ensure pattern is bytes
  5731. pattern_bytes = pattern.encode() if isinstance(pattern, str) else pattern
  5732. # Set LFS attributes for the pattern
  5733. gitattributes.set_attribute(pattern_bytes, b"filter", b"lfs")
  5734. gitattributes.set_attribute(pattern_bytes, b"diff", b"lfs")
  5735. gitattributes.set_attribute(pattern_bytes, b"merge", b"lfs")
  5736. gitattributes.set_attribute(pattern_bytes, b"text", False)
  5737. # Write updated attributes
  5738. gitattributes.write_to_file(gitattributes_path)
  5739. # Stage the .gitattributes file
  5740. add(r, [".gitattributes"])
  5741. return lfs_track(r) # Return updated list
  5742. def lfs_untrack(
  5743. repo: Union[str, os.PathLike[str], Repo] = ".",
  5744. patterns: Optional[Sequence[str]] = None,
  5745. ) -> list[str]:
  5746. """Untrack file patterns from Git LFS.
  5747. Args:
  5748. repo: Path to repository
  5749. patterns: List of file patterns to untrack
  5750. Returns:
  5751. List of remaining tracked patterns
  5752. """
  5753. from .attrs import GitAttributes
  5754. if not patterns:
  5755. return lfs_track(repo)
  5756. with open_repo_closing(repo) as r:
  5757. gitattributes_path = os.path.join(r.path, ".gitattributes")
  5758. if not os.path.exists(gitattributes_path):
  5759. return []
  5760. # Load existing GitAttributes
  5761. gitattributes = GitAttributes.from_file(gitattributes_path)
  5762. # Remove specified patterns
  5763. for pattern in patterns:
  5764. pattern_bytes = pattern.encode() if isinstance(pattern, str) else pattern
  5765. # Check if pattern is tracked by LFS
  5766. for pattern_obj, attrs in list(gitattributes):
  5767. if (
  5768. pattern_obj.pattern == pattern_bytes
  5769. and attrs.get(b"filter") == b"lfs"
  5770. ):
  5771. gitattributes.remove_pattern(pattern_bytes)
  5772. break
  5773. # Write updated attributes
  5774. gitattributes.write_to_file(gitattributes_path)
  5775. # Stage the .gitattributes file
  5776. add(r, [".gitattributes"])
  5777. return lfs_track(r) # Return updated list
  5778. def lfs_init(repo: Union[str, os.PathLike[str], Repo] = ".") -> None:
  5779. """Initialize Git LFS in a repository.
  5780. Args:
  5781. repo: Path to repository
  5782. Returns:
  5783. None
  5784. """
  5785. from .lfs import LFSStore
  5786. with open_repo_closing(repo) as r:
  5787. # Create LFS store
  5788. LFSStore.from_repo(r, create=True)
  5789. # Set up Git config for LFS
  5790. config = r.get_config()
  5791. config.set((b"filter", b"lfs"), b"process", b"git-lfs filter-process")
  5792. config.set((b"filter", b"lfs"), b"required", b"true")
  5793. config.set((b"filter", b"lfs"), b"clean", b"git-lfs clean -- %f")
  5794. config.set((b"filter", b"lfs"), b"smudge", b"git-lfs smudge -- %f")
  5795. config.write_to_path()
  5796. def lfs_clean(
  5797. repo: Union[str, os.PathLike[str], Repo] = ".",
  5798. path: Optional[Union[str, os.PathLike[str]]] = None,
  5799. ) -> bytes:
  5800. """Clean a file by converting it to an LFS pointer.
  5801. Args:
  5802. repo: Path to repository
  5803. path: Path to file to clean (relative to repo root)
  5804. Returns:
  5805. LFS pointer content as bytes
  5806. """
  5807. from .lfs import LFSFilterDriver, LFSStore
  5808. with open_repo_closing(repo) as r:
  5809. if path is None:
  5810. raise ValueError("Path must be specified")
  5811. # Get LFS store
  5812. lfs_store = LFSStore.from_repo(r)
  5813. filter_driver = LFSFilterDriver(lfs_store, config=r.get_config())
  5814. # Read file content
  5815. full_path = os.path.join(r.path, path)
  5816. with open(full_path, "rb") as f:
  5817. content = f.read()
  5818. # Clean the content (convert to LFS pointer)
  5819. return filter_driver.clean(content)
  5820. def lfs_smudge(
  5821. repo: Union[str, os.PathLike[str], Repo] = ".",
  5822. pointer_content: Optional[bytes] = None,
  5823. ) -> bytes:
  5824. """Smudge an LFS pointer by retrieving the actual content.
  5825. Args:
  5826. repo: Path to repository
  5827. pointer_content: LFS pointer content as bytes
  5828. Returns:
  5829. Actual file content as bytes
  5830. """
  5831. from .lfs import LFSFilterDriver, LFSStore
  5832. with open_repo_closing(repo) as r:
  5833. if pointer_content is None:
  5834. raise ValueError("Pointer content must be specified")
  5835. # Get LFS store
  5836. lfs_store = LFSStore.from_repo(r)
  5837. filter_driver = LFSFilterDriver(lfs_store, config=r.get_config())
  5838. # Smudge the pointer (retrieve actual content)
  5839. return filter_driver.smudge(pointer_content)
  5840. def lfs_ls_files(
  5841. repo: Union[str, os.PathLike[str], Repo] = ".",
  5842. ref: Optional[Union[str, bytes]] = None,
  5843. ) -> list[tuple[bytes, str, int]]:
  5844. """List files tracked by Git LFS.
  5845. Args:
  5846. repo: Path to repository
  5847. ref: Git ref to check (defaults to HEAD)
  5848. Returns:
  5849. List of (path, oid, size) tuples for LFS files
  5850. """
  5851. from .lfs import LFSPointer
  5852. from .object_store import iter_tree_contents
  5853. with open_repo_closing(repo) as r:
  5854. if ref is None:
  5855. ref = b"HEAD"
  5856. elif isinstance(ref, str):
  5857. ref = ref.encode()
  5858. # Get the commit and tree
  5859. try:
  5860. commit = r[ref]
  5861. assert isinstance(commit, Commit)
  5862. tree = r[commit.tree]
  5863. assert isinstance(tree, Tree)
  5864. except KeyError:
  5865. return []
  5866. lfs_files = []
  5867. # Walk the tree
  5868. for path, mode, sha in iter_tree_contents(r.object_store, tree.id):
  5869. assert path is not None
  5870. assert mode is not None
  5871. assert sha is not None
  5872. if not stat.S_ISREG(mode):
  5873. continue
  5874. # Check if it's an LFS pointer
  5875. obj = r.object_store[sha]
  5876. if not isinstance(obj, Blob):
  5877. raise AssertionError(f"Expected Blob object, got {type(obj).__name__}")
  5878. pointer = LFSPointer.from_bytes(obj.data)
  5879. if pointer is not None:
  5880. lfs_files.append((path, pointer.oid, pointer.size))
  5881. return lfs_files
  5882. def lfs_migrate(
  5883. repo: Union[str, os.PathLike[str], Repo] = ".",
  5884. include: Optional[list[str]] = None,
  5885. exclude: Optional[list[str]] = None,
  5886. everything: bool = False,
  5887. ) -> int:
  5888. """Migrate files to Git LFS.
  5889. Args:
  5890. repo: Path to repository
  5891. include: Patterns of files to include
  5892. exclude: Patterns of files to exclude
  5893. everything: Migrate all files above a certain size
  5894. Returns:
  5895. Number of migrated files
  5896. """
  5897. from .lfs import LFSFilterDriver, LFSStore
  5898. with open_repo_closing(repo) as r:
  5899. # Initialize LFS if needed
  5900. lfs_store = LFSStore.from_repo(r, create=True)
  5901. filter_driver = LFSFilterDriver(lfs_store, config=r.get_config())
  5902. # Get current index
  5903. index = r.open_index()
  5904. migrated = 0
  5905. # Determine files to migrate
  5906. files_to_migrate = []
  5907. if everything:
  5908. # Migrate all files above 100MB
  5909. for path, entry in index.items():
  5910. full_path = os.path.join(r.path, path.decode())
  5911. if os.path.exists(full_path):
  5912. size = os.path.getsize(full_path)
  5913. if size > 100 * 1024 * 1024: # 100MB
  5914. files_to_migrate.append(path.decode())
  5915. else:
  5916. # Use include/exclude patterns
  5917. for path, entry in index.items():
  5918. path_str = path.decode()
  5919. # Check include patterns
  5920. if include:
  5921. matched = any(
  5922. fnmatch.fnmatch(path_str, pattern) for pattern in include
  5923. )
  5924. if not matched:
  5925. continue
  5926. # Check exclude patterns
  5927. if exclude:
  5928. excluded = any(
  5929. fnmatch.fnmatch(path_str, pattern) for pattern in exclude
  5930. )
  5931. if excluded:
  5932. continue
  5933. files_to_migrate.append(path_str)
  5934. # Migrate files
  5935. for path_str in files_to_migrate:
  5936. full_path = os.path.join(r.path, path_str)
  5937. if not os.path.exists(full_path):
  5938. continue
  5939. # Read file content
  5940. with open(full_path, "rb") as f:
  5941. content = f.read()
  5942. # Convert to LFS pointer
  5943. pointer_content = filter_driver.clean(content)
  5944. # Write pointer back to file
  5945. with open(full_path, "wb") as f:
  5946. f.write(pointer_content)
  5947. # Create blob for pointer content and update index
  5948. blob = Blob()
  5949. blob.data = pointer_content
  5950. r.object_store.add_object(blob)
  5951. st = os.stat(full_path)
  5952. index_entry = index_entry_from_stat(st, blob.id, 0)
  5953. path_bytes = path_str.encode() if isinstance(path_str, str) else path_str
  5954. index[path_bytes] = index_entry
  5955. migrated += 1
  5956. # Write updated index
  5957. index.write()
  5958. # Track patterns if include was specified
  5959. if include:
  5960. lfs_track(r, include)
  5961. return migrated
  5962. def lfs_pointer_check(
  5963. repo: Union[str, os.PathLike[str], Repo] = ".",
  5964. paths: Optional[Sequence[str]] = None,
  5965. ) -> dict[str, Optional[Any]]:
  5966. """Check if files are valid LFS pointers.
  5967. Args:
  5968. repo: Path to repository
  5969. paths: List of file paths to check (if None, check all files)
  5970. Returns:
  5971. Dict mapping paths to LFSPointer objects (or None if not a pointer)
  5972. """
  5973. from .lfs import LFSPointer
  5974. with open_repo_closing(repo) as r:
  5975. results = {}
  5976. if paths is None:
  5977. # Check all files in index
  5978. index = r.open_index()
  5979. paths = [path.decode() for path in index]
  5980. for path in paths:
  5981. full_path = os.path.join(r.path, path)
  5982. if os.path.exists(full_path):
  5983. try:
  5984. with open(full_path, "rb") as f:
  5985. content = f.read()
  5986. pointer = LFSPointer.from_bytes(content)
  5987. results[path] = pointer
  5988. except OSError:
  5989. results[path] = None
  5990. else:
  5991. results[path] = None
  5992. return results
  5993. def lfs_fetch(
  5994. repo: Union[str, os.PathLike[str], Repo] = ".",
  5995. remote: str = "origin",
  5996. refs: Optional[list[Union[str, bytes]]] = None,
  5997. ) -> int:
  5998. """Fetch LFS objects from remote.
  5999. Args:
  6000. repo: Path to repository
  6001. remote: Remote name (default: origin)
  6002. refs: Specific refs to fetch LFS objects for (default: all refs)
  6003. Returns:
  6004. Number of objects fetched
  6005. """
  6006. from .lfs import LFSClient, LFSPointer, LFSStore
  6007. with open_repo_closing(repo) as r:
  6008. # Get LFS server URL from config
  6009. config = r.get_config()
  6010. lfs_url_bytes = config.get((b"lfs",), b"url")
  6011. if not lfs_url_bytes:
  6012. # Try remote URL
  6013. remote_url = config.get((b"remote", remote.encode()), b"url")
  6014. if remote_url:
  6015. # Append /info/lfs to remote URL
  6016. remote_url_str = remote_url.decode()
  6017. if remote_url_str.endswith(".git"):
  6018. remote_url_str = remote_url_str[:-4]
  6019. lfs_url = f"{remote_url_str}/info/lfs"
  6020. else:
  6021. raise ValueError(f"No LFS URL configured for remote {remote}")
  6022. else:
  6023. lfs_url = lfs_url_bytes.decode()
  6024. # Get authentication
  6025. auth = None
  6026. # TODO: Support credential helpers and other auth methods
  6027. # Create LFS client and store
  6028. client = LFSClient(lfs_url, auth)
  6029. store = LFSStore.from_repo(r)
  6030. # Find all LFS pointers in the refs
  6031. pointers_to_fetch = []
  6032. if refs is None:
  6033. # Get all refs
  6034. refs = list(r.refs.keys())
  6035. for ref in refs:
  6036. if isinstance(ref, str):
  6037. ref = ref.encode()
  6038. try:
  6039. commit = r[r.refs[ref]]
  6040. except KeyError:
  6041. continue
  6042. # Walk the commit tree
  6043. assert isinstance(commit, Commit)
  6044. for path, mode, sha in r.object_store.iter_tree_contents(commit.tree):
  6045. assert sha is not None
  6046. try:
  6047. obj = r.object_store[sha]
  6048. except KeyError:
  6049. pass
  6050. else:
  6051. if isinstance(obj, Blob):
  6052. pointer = LFSPointer.from_bytes(obj.data)
  6053. if pointer and pointer.is_valid_oid():
  6054. # Check if we already have it
  6055. try:
  6056. store.open_object(pointer.oid)
  6057. except KeyError:
  6058. pointers_to_fetch.append((pointer.oid, pointer.size))
  6059. # Fetch missing objects
  6060. fetched = 0
  6061. for oid, size in pointers_to_fetch:
  6062. content = client.download(oid, size)
  6063. store.write_object([content])
  6064. fetched += 1
  6065. return fetched
  6066. def lfs_pull(
  6067. repo: Union[str, os.PathLike[str], Repo] = ".", remote: str = "origin"
  6068. ) -> int:
  6069. """Pull LFS objects for current checkout.
  6070. Args:
  6071. repo: Path to repository
  6072. remote: Remote name (default: origin)
  6073. Returns:
  6074. Number of objects fetched
  6075. """
  6076. from .lfs import LFSPointer, LFSStore
  6077. with open_repo_closing(repo) as r:
  6078. # First do a fetch for HEAD
  6079. fetched = lfs_fetch(repo, remote, [b"HEAD"])
  6080. # Then checkout LFS files in working directory
  6081. store = LFSStore.from_repo(r)
  6082. index = r.open_index()
  6083. for path, entry in index.items():
  6084. full_path = os.path.join(r.path, path.decode())
  6085. if os.path.exists(full_path):
  6086. with open(full_path, "rb") as f:
  6087. content = f.read()
  6088. pointer = LFSPointer.from_bytes(content)
  6089. if pointer and pointer.is_valid_oid():
  6090. try:
  6091. # Replace pointer with actual content
  6092. with store.open_object(pointer.oid) as lfs_file:
  6093. lfs_content = lfs_file.read()
  6094. with open(full_path, "wb") as f:
  6095. f.write(lfs_content)
  6096. except KeyError:
  6097. # Object not available
  6098. pass
  6099. return fetched
  6100. def lfs_push(
  6101. repo: Union[str, os.PathLike[str], Repo] = ".",
  6102. remote: str = "origin",
  6103. refs: Optional[list[Union[str, bytes]]] = None,
  6104. ) -> int:
  6105. """Push LFS objects to remote.
  6106. Args:
  6107. repo: Path to repository
  6108. remote: Remote name (default: origin)
  6109. refs: Specific refs to push LFS objects for (default: current branch)
  6110. Returns:
  6111. Number of objects pushed
  6112. """
  6113. from .lfs import LFSClient, LFSPointer, LFSStore
  6114. with open_repo_closing(repo) as r:
  6115. # Get LFS server URL from config
  6116. config = r.get_config()
  6117. lfs_url_bytes = config.get((b"lfs",), b"url")
  6118. if not lfs_url_bytes:
  6119. # Try remote URL
  6120. remote_url = config.get((b"remote", remote.encode()), b"url")
  6121. if remote_url:
  6122. # Append /info/lfs to remote URL
  6123. remote_url_str = remote_url.decode()
  6124. if remote_url_str.endswith(".git"):
  6125. remote_url_str = remote_url_str[:-4]
  6126. lfs_url = f"{remote_url_str}/info/lfs"
  6127. else:
  6128. raise ValueError(f"No LFS URL configured for remote {remote}")
  6129. else:
  6130. lfs_url = lfs_url_bytes.decode()
  6131. # Get authentication
  6132. auth = None
  6133. # TODO: Support credential helpers and other auth methods
  6134. # Create LFS client and store
  6135. client = LFSClient(lfs_url, auth)
  6136. store = LFSStore.from_repo(r)
  6137. # Find all LFS objects to push
  6138. if refs is None:
  6139. # Push current branch
  6140. head_ref = r.refs.read_ref(b"HEAD")
  6141. refs = [head_ref] if head_ref else []
  6142. objects_to_push = set()
  6143. for ref in refs:
  6144. if isinstance(ref, str):
  6145. ref = ref.encode()
  6146. try:
  6147. if ref.startswith(b"refs/"):
  6148. commit = r[r.refs[ref]]
  6149. else:
  6150. commit = r[ref]
  6151. except KeyError:
  6152. continue
  6153. # Walk the commit tree
  6154. assert isinstance(commit, Commit)
  6155. for path, mode, sha in r.object_store.iter_tree_contents(commit.tree):
  6156. assert sha is not None
  6157. try:
  6158. obj = r.object_store[sha]
  6159. except KeyError:
  6160. pass
  6161. else:
  6162. if isinstance(obj, Blob):
  6163. pointer = LFSPointer.from_bytes(obj.data)
  6164. if pointer and pointer.is_valid_oid():
  6165. objects_to_push.add((pointer.oid, pointer.size))
  6166. # Push objects
  6167. pushed = 0
  6168. for oid, size in objects_to_push:
  6169. try:
  6170. with store.open_object(oid) as f:
  6171. content = f.read()
  6172. except KeyError:
  6173. # Object not in local store
  6174. logging.warn("LFS object %s not found locally", oid)
  6175. else:
  6176. client.upload(oid, size, content)
  6177. pushed += 1
  6178. return pushed
  6179. def lfs_status(repo: Union[str, os.PathLike[str], Repo] = ".") -> dict[str, list[str]]:
  6180. """Show status of LFS files.
  6181. Args:
  6182. repo: Path to repository
  6183. Returns:
  6184. Dict with status information
  6185. """
  6186. from .lfs import LFSPointer, LFSStore
  6187. with open_repo_closing(repo) as r:
  6188. store = LFSStore.from_repo(r)
  6189. index = r.open_index()
  6190. status: dict[str, list[str]] = {
  6191. "tracked": [],
  6192. "not_staged": [],
  6193. "not_committed": [],
  6194. "not_pushed": [],
  6195. "missing": [],
  6196. }
  6197. # Check working directory files
  6198. for path, entry in index.items():
  6199. path_str = path.decode()
  6200. full_path = os.path.join(r.path, path_str)
  6201. if os.path.exists(full_path):
  6202. with open(full_path, "rb") as f:
  6203. content = f.read()
  6204. pointer = LFSPointer.from_bytes(content)
  6205. if pointer and pointer.is_valid_oid():
  6206. status["tracked"].append(path_str)
  6207. # Check if object exists locally
  6208. try:
  6209. store.open_object(pointer.oid)
  6210. except KeyError:
  6211. status["missing"].append(path_str)
  6212. # Check if file has been modified
  6213. if isinstance(entry, ConflictedIndexEntry):
  6214. continue # Skip conflicted entries
  6215. try:
  6216. staged_obj = r.object_store[entry.sha]
  6217. except KeyError:
  6218. pass
  6219. else:
  6220. if not isinstance(staged_obj, Blob):
  6221. raise AssertionError(
  6222. f"Expected Blob object, got {type(staged_obj).__name__}"
  6223. )
  6224. staged_pointer = LFSPointer.from_bytes(staged_obj.data)
  6225. if staged_pointer and staged_pointer.oid != pointer.oid:
  6226. status["not_staged"].append(path_str)
  6227. # TODO: Check for not committed and not pushed files
  6228. return status
  6229. def worktree_list(repo: RepoPath = ".") -> list[Any]:
  6230. """List all worktrees for a repository.
  6231. Args:
  6232. repo: Path to repository
  6233. Returns:
  6234. List of WorkTreeInfo objects
  6235. """
  6236. from .worktree import list_worktrees
  6237. with open_repo_closing(repo) as r:
  6238. return list_worktrees(r)
  6239. def worktree_add(
  6240. repo: RepoPath = ".",
  6241. path: Optional[Union[str, os.PathLike[str]]] = None,
  6242. branch: Optional[Union[str, bytes]] = None,
  6243. commit: Optional[Union[str, bytes]] = None,
  6244. detach: bool = False,
  6245. force: bool = False,
  6246. ) -> str:
  6247. """Add a new worktree.
  6248. Args:
  6249. repo: Path to repository
  6250. path: Path for new worktree
  6251. branch: Branch to checkout (creates if doesn't exist)
  6252. commit: Specific commit to checkout
  6253. detach: Create with detached HEAD
  6254. force: Force creation even if branch is already checked out
  6255. Returns:
  6256. Path to the newly created worktree
  6257. """
  6258. from .worktree import add_worktree
  6259. if path is None:
  6260. raise ValueError("Path is required for worktree add")
  6261. with open_repo_closing(repo) as r:
  6262. commit_bytes = commit.encode() if isinstance(commit, str) else commit
  6263. wt_repo = add_worktree(
  6264. r, path, branch=branch, commit=commit_bytes, detach=detach, force=force
  6265. )
  6266. return wt_repo.path
  6267. def worktree_remove(
  6268. repo: RepoPath = ".",
  6269. path: Optional[Union[str, os.PathLike[str]]] = None,
  6270. force: bool = False,
  6271. ) -> None:
  6272. """Remove a worktree.
  6273. Args:
  6274. repo: Path to repository
  6275. path: Path to worktree to remove
  6276. force: Force removal even if there are local changes
  6277. """
  6278. from .worktree import remove_worktree
  6279. if path is None:
  6280. raise ValueError("Path is required for worktree remove")
  6281. with open_repo_closing(repo) as r:
  6282. remove_worktree(r, path, force=force)
  6283. def worktree_prune(
  6284. repo: RepoPath = ".", dry_run: bool = False, expire: Optional[int] = None
  6285. ) -> list[str]:
  6286. """Prune worktree administrative files.
  6287. Args:
  6288. repo: Path to repository
  6289. dry_run: Only show what would be removed
  6290. expire: Only prune worktrees older than this many seconds
  6291. Returns:
  6292. List of pruned worktree names
  6293. """
  6294. from .worktree import prune_worktrees
  6295. with open_repo_closing(repo) as r:
  6296. return prune_worktrees(r, expire=expire, dry_run=dry_run)
  6297. def worktree_lock(
  6298. repo: RepoPath = ".",
  6299. path: Optional[Union[str, os.PathLike[str]]] = None,
  6300. reason: Optional[str] = None,
  6301. ) -> None:
  6302. """Lock a worktree to prevent it from being pruned.
  6303. Args:
  6304. repo: Path to repository
  6305. path: Path to worktree to lock
  6306. reason: Optional reason for locking
  6307. """
  6308. from .worktree import lock_worktree
  6309. if path is None:
  6310. raise ValueError("Path is required for worktree lock")
  6311. with open_repo_closing(repo) as r:
  6312. lock_worktree(r, path, reason=reason)
  6313. def worktree_unlock(
  6314. repo: RepoPath = ".", path: Optional[Union[str, os.PathLike[str]]] = None
  6315. ) -> None:
  6316. """Unlock a worktree.
  6317. Args:
  6318. repo: Path to repository
  6319. path: Path to worktree to unlock
  6320. """
  6321. from .worktree import unlock_worktree
  6322. if path is None:
  6323. raise ValueError("Path is required for worktree unlock")
  6324. with open_repo_closing(repo) as r:
  6325. unlock_worktree(r, path)
  6326. def worktree_move(
  6327. repo: RepoPath = ".",
  6328. old_path: Optional[Union[str, os.PathLike[str]]] = None,
  6329. new_path: Optional[Union[str, os.PathLike[str]]] = None,
  6330. ) -> None:
  6331. """Move a worktree to a new location.
  6332. Args:
  6333. repo: Path to repository
  6334. old_path: Current path of worktree
  6335. new_path: New path for worktree
  6336. """
  6337. from .worktree import move_worktree
  6338. if old_path is None or new_path is None:
  6339. raise ValueError("Both old_path and new_path are required for worktree move")
  6340. with open_repo_closing(repo) as r:
  6341. move_worktree(r, old_path, new_path)
  6342. def worktree_repair(
  6343. repo: RepoPath = ".",
  6344. paths: Optional[list[Union[str, os.PathLike[str]]]] = None,
  6345. ) -> list[str]:
  6346. """Repair worktree administrative files.
  6347. Args:
  6348. repo: Path to repository
  6349. paths: Optional list of worktree paths to repair. If None, repairs
  6350. connections from the main repository to all linked worktrees.
  6351. Returns:
  6352. List of repaired worktree paths
  6353. """
  6354. from .worktree import repair_worktree
  6355. with open_repo_closing(repo) as r:
  6356. return repair_worktree(r, paths=paths)
  6357. def merge_base(
  6358. repo: RepoPath = ".",
  6359. committishes: Optional[Sequence[Union[str, bytes]]] = None,
  6360. all: bool = False,
  6361. octopus: bool = False,
  6362. ) -> list[bytes]:
  6363. """Find the best common ancestor(s) between commits.
  6364. Args:
  6365. repo: Path to repository
  6366. committishes: List of commit references (branches, tags, commit IDs)
  6367. all: If True, return all merge bases, not just one
  6368. octopus: If True, find merge base of all commits (n-way merge)
  6369. Returns:
  6370. List of commit IDs that are merge bases
  6371. """
  6372. from .graph import find_merge_base, find_octopus_base
  6373. from .objects import Commit
  6374. from .objectspec import parse_object
  6375. if committishes is None or len(committishes) < 2:
  6376. raise ValueError("At least two commits are required")
  6377. with open_repo_closing(repo) as r:
  6378. # Resolve committish references to commit IDs
  6379. commit_ids = []
  6380. for committish in committishes:
  6381. obj = parse_object(r, committish)
  6382. if not isinstance(obj, Commit):
  6383. raise ValueError(f"Expected commit, got {obj.type_name.decode()}")
  6384. commit_ids.append(obj.id)
  6385. # Find merge base
  6386. if octopus:
  6387. result = find_octopus_base(r, commit_ids)
  6388. else:
  6389. result = find_merge_base(r, commit_ids)
  6390. # Return first result only if all=False
  6391. if not all and result:
  6392. return [result[0]]
  6393. return result
  6394. def is_ancestor(
  6395. repo: RepoPath = ".",
  6396. ancestor: Optional[Union[str, bytes]] = None,
  6397. descendant: Optional[Union[str, bytes]] = None,
  6398. ) -> bool:
  6399. """Check if one commit is an ancestor of another.
  6400. Args:
  6401. repo: Path to repository
  6402. ancestor: Commit that might be the ancestor
  6403. descendant: Commit that might be the descendant
  6404. Returns:
  6405. True if ancestor is an ancestor of descendant, False otherwise
  6406. """
  6407. from .graph import find_merge_base
  6408. from .objects import Commit
  6409. from .objectspec import parse_object
  6410. if ancestor is None or descendant is None:
  6411. raise ValueError("Both ancestor and descendant are required")
  6412. with open_repo_closing(repo) as r:
  6413. # Resolve committish references to commit IDs
  6414. ancestor_obj = parse_object(r, ancestor)
  6415. if not isinstance(ancestor_obj, Commit):
  6416. raise ValueError(f"Expected commit, got {ancestor_obj.type_name.decode()}")
  6417. descendant_obj = parse_object(r, descendant)
  6418. if not isinstance(descendant_obj, Commit):
  6419. raise ValueError(
  6420. f"Expected commit, got {descendant_obj.type_name.decode()}"
  6421. )
  6422. # If ancestor is the merge base of (ancestor, descendant), then it's an ancestor
  6423. merge_bases = find_merge_base(r, [ancestor_obj.id, descendant_obj.id])
  6424. return merge_bases == [ancestor_obj.id]
  6425. def independent_commits(
  6426. repo: RepoPath = ".",
  6427. committishes: Optional[Sequence[Union[str, bytes]]] = None,
  6428. ) -> list[bytes]:
  6429. """Filter commits to only those that are not reachable from others.
  6430. Args:
  6431. repo: Path to repository
  6432. committishes: List of commit references to filter
  6433. Returns:
  6434. List of commit IDs that are not ancestors of any other commits in the list
  6435. """
  6436. from .graph import independent
  6437. from .objects import Commit
  6438. from .objectspec import parse_object
  6439. if committishes is None or len(committishes) == 0:
  6440. return []
  6441. with open_repo_closing(repo) as r:
  6442. # Resolve committish references to commit IDs
  6443. commit_ids = []
  6444. for committish in committishes:
  6445. obj = parse_object(r, committish)
  6446. if not isinstance(obj, Commit):
  6447. raise ValueError(f"Expected commit, got {obj.type_name.decode()}")
  6448. commit_ids.append(obj.id)
  6449. # Filter to independent commits
  6450. return independent(r, commit_ids)