porcelain.py 312 KB

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