porcelain.py 312 KB

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