cli.py 223 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829
  1. #
  2. # dulwich - Simple command-line interface to Dulwich
  3. # Copyright (C) 2008-2011 Jelmer Vernooij <jelmer@jelmer.uk>
  4. # vim: expandtab
  5. #
  6. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  7. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  8. # General Public License as published by the Free Software Foundation; version 2.0
  9. # or (at your option) any later version. You can redistribute it and/or
  10. # modify it under the terms of either of these two licenses.
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. #
  18. # You should have received a copy of the licenses; if not, see
  19. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  20. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  21. # License, Version 2.0.
  22. #
  23. """Simple command-line interface to Dulwich>.
  24. This is a very simple command-line wrapper for Dulwich. It is by
  25. no means intended to be a full-blown Git command-line interface but just
  26. a way to test Dulwich.
  27. """
  28. __all__ = [
  29. "AutoFlushBinaryIOWrapper",
  30. "AutoFlushTextIOWrapper",
  31. "Command",
  32. "CommitMessageError",
  33. "Pager",
  34. "PagerBuffer",
  35. "SuperCommand",
  36. "detect_terminal_width",
  37. "disable_pager",
  38. "enable_pager",
  39. "format_bytes",
  40. "format_columns",
  41. "get_pager",
  42. "launch_editor",
  43. "main",
  44. "parse_time_to_timestamp",
  45. "signal_int",
  46. "signal_quit",
  47. "to_display_str",
  48. "write_columns",
  49. ]
  50. # TODO: Add support for GIT_NAMESPACE environment variable by wrapping
  51. # repository refs with NamespacedRefsContainer when the environment
  52. # variable is set. See issue #1809 and dulwich.refs.NamespacedRefsContainer.
  53. import argparse
  54. import io
  55. import logging
  56. import os
  57. import shutil
  58. import signal
  59. import subprocess
  60. import sys
  61. import tempfile
  62. import types
  63. from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
  64. from pathlib import Path
  65. from types import TracebackType
  66. from typing import (
  67. BinaryIO,
  68. ClassVar,
  69. TextIO,
  70. )
  71. from dulwich import porcelain
  72. from dulwich._typing import Buffer
  73. from dulwich.refs import HEADREF, Ref
  74. from .bundle import Bundle, create_bundle_from_repo, read_bundle, write_bundle
  75. from .client import get_transport_and_path
  76. from .config import Config
  77. from .errors import (
  78. ApplyDeltaError,
  79. FileFormatException,
  80. GitProtocolError,
  81. NotGitRepository,
  82. )
  83. from .index import Index
  84. from .log_utils import _configure_logging_from_trace
  85. from .objects import Commit, ObjectID, RawObjectID, sha_to_hex, valid_hexsha
  86. from .objectspec import parse_commit_range
  87. from .pack import Pack
  88. from .patch import DiffAlgorithmNotAvailable
  89. from .repo import Repo
  90. logger = logging.getLogger(__name__)
  91. def to_display_str(value: bytes | str) -> str:
  92. """Convert a bytes or string value to a display string.
  93. Args:
  94. value: The value to convert (bytes or str)
  95. Returns:
  96. A string suitable for display
  97. """
  98. if isinstance(value, bytes):
  99. return value.decode("utf-8", "replace")
  100. return value
  101. def _should_auto_flush(
  102. stream: TextIO | BinaryIO, env: Mapping[str, str] | None = None
  103. ) -> bool:
  104. """Determine if output should be auto-flushed based on GIT_FLUSH environment variable.
  105. Args:
  106. stream: The output stream to check
  107. env: Environment variables dict (defaults to os.environ)
  108. Returns:
  109. True if output should be flushed after each write, False otherwise
  110. """
  111. if env is None:
  112. env = os.environ
  113. git_flush = env.get("GIT_FLUSH", "").strip()
  114. if git_flush == "1":
  115. return True
  116. elif git_flush == "0":
  117. return False
  118. else:
  119. # Auto-detect: don't flush if redirected to a file
  120. return hasattr(stream, "isatty") and not stream.isatty()
  121. class AutoFlushTextIOWrapper:
  122. """Wrapper that automatically flushes a TextIO stream based on configuration.
  123. This wrapper can be configured to flush after each write operation,
  124. which is useful for real-time output monitoring in CI/CD systems.
  125. """
  126. def __init__(self, stream: TextIO) -> None:
  127. """Initialize the wrapper.
  128. Args:
  129. stream: The stream to wrap
  130. """
  131. self._stream = stream
  132. @classmethod
  133. def env(
  134. cls, stream: TextIO, env: Mapping[str, str] | None = None
  135. ) -> "AutoFlushTextIOWrapper | TextIO":
  136. """Create wrapper respecting the GIT_FLUSH environment variable.
  137. Respects the GIT_FLUSH environment variable:
  138. - GIT_FLUSH=1: Always flush after each write
  139. - GIT_FLUSH=0: Never auto-flush (use buffered I/O)
  140. - Not set: Auto-detect based on whether output is redirected
  141. Args:
  142. stream: The stream to wrap
  143. env: Environment variables dict (defaults to os.environ)
  144. Returns:
  145. AutoFlushTextIOWrapper instance configured based on GIT_FLUSH
  146. """
  147. if _should_auto_flush(stream, env):
  148. return cls(stream)
  149. else:
  150. return stream
  151. def write(self, data: str) -> int:
  152. """Write data to the stream and optionally flush.
  153. Args:
  154. data: Data to write
  155. Returns:
  156. Number of characters written
  157. """
  158. result = self._stream.write(data)
  159. self._stream.flush()
  160. return result
  161. def writelines(self, lines: Iterable[str]) -> None:
  162. """Write multiple lines to the stream and optionally flush.
  163. Args:
  164. lines: Lines to write
  165. """
  166. self._stream.writelines(lines)
  167. self._stream.flush()
  168. def flush(self) -> None:
  169. """Flush the underlying stream."""
  170. self._stream.flush()
  171. def __getattr__(self, name: str) -> object:
  172. """Delegate all other attributes to the underlying stream."""
  173. return getattr(self._stream, name)
  174. def __enter__(self) -> "AutoFlushTextIOWrapper":
  175. """Support context manager protocol."""
  176. return self
  177. def __exit__(
  178. self,
  179. exc_type: type[BaseException] | None,
  180. exc_val: BaseException | None,
  181. exc_tb: TracebackType | None,
  182. ) -> None:
  183. """Support context manager protocol."""
  184. if hasattr(self._stream, "__exit__"):
  185. self._stream.__exit__(exc_type, exc_val, exc_tb)
  186. class AutoFlushBinaryIOWrapper:
  187. """Wrapper that automatically flushes a BinaryIO stream based on configuration.
  188. This wrapper can be configured to flush after each write operation,
  189. which is useful for real-time output monitoring in CI/CD systems.
  190. """
  191. def __init__(self, stream: BinaryIO) -> None:
  192. """Initialize the wrapper.
  193. Args:
  194. stream: The stream to wrap
  195. """
  196. self._stream = stream
  197. @classmethod
  198. def env(
  199. cls, stream: BinaryIO, env: Mapping[str, str] | None = None
  200. ) -> "AutoFlushBinaryIOWrapper | BinaryIO":
  201. """Create wrapper respecting the GIT_FLUSH environment variable.
  202. Respects the GIT_FLUSH environment variable:
  203. - GIT_FLUSH=1: Always flush after each write
  204. - GIT_FLUSH=0: Never auto-flush (use buffered I/O)
  205. - Not set: Auto-detect based on whether output is redirected
  206. Args:
  207. stream: The stream to wrap
  208. env: Environment variables dict (defaults to os.environ)
  209. Returns:
  210. AutoFlushBinaryIOWrapper instance configured based on GIT_FLUSH
  211. """
  212. if _should_auto_flush(stream, env):
  213. return cls(stream)
  214. else:
  215. return stream
  216. def write(self, data: Buffer) -> int:
  217. """Write data to the stream and optionally flush.
  218. Args:
  219. data: Data to write
  220. Returns:
  221. Number of bytes written
  222. """
  223. result = self._stream.write(data)
  224. self._stream.flush()
  225. return result
  226. def writelines(self, lines: Iterable[Buffer]) -> None:
  227. """Write multiple lines to the stream and optionally flush.
  228. Args:
  229. lines: Lines to write
  230. """
  231. self._stream.writelines(lines)
  232. self._stream.flush()
  233. def flush(self) -> None:
  234. """Flush the underlying stream."""
  235. self._stream.flush()
  236. def __getattr__(self, name: str) -> object:
  237. """Delegate all other attributes to the underlying stream."""
  238. return getattr(self._stream, name)
  239. def __enter__(self) -> "AutoFlushBinaryIOWrapper":
  240. """Support context manager protocol."""
  241. return self
  242. def __exit__(
  243. self,
  244. exc_type: type[BaseException] | None,
  245. exc_val: BaseException | None,
  246. exc_tb: TracebackType | None,
  247. ) -> None:
  248. """Support context manager protocol."""
  249. if hasattr(self._stream, "__exit__"):
  250. self._stream.__exit__(exc_type, exc_val, exc_tb)
  251. class CommitMessageError(Exception):
  252. """Raised when there's an issue with the commit message."""
  253. def signal_int(signal: int, frame: types.FrameType | None) -> None:
  254. """Handle interrupt signal by exiting.
  255. Args:
  256. signal: Signal number
  257. frame: Current stack frame
  258. """
  259. sys.exit(1)
  260. def signal_quit(signal: int, frame: types.FrameType | None) -> None:
  261. """Handle quit signal by entering debugger.
  262. Args:
  263. signal: Signal number
  264. frame: Current stack frame
  265. """
  266. import pdb
  267. pdb.set_trace()
  268. def parse_time_to_timestamp(time_spec: str) -> int:
  269. """Parse a time specification and return a Unix timestamp.
  270. Args:
  271. time_spec: Time specification. Can be:
  272. - A Unix timestamp (integer as string)
  273. - A relative time like "2 weeks ago"
  274. - "now" for current time
  275. - "all" to expire all entries (returns future time)
  276. - "never" to never expire (returns 0 - epoch start)
  277. Returns:
  278. Unix timestamp
  279. Raises:
  280. ValueError: If the time specification cannot be parsed
  281. """
  282. import time
  283. from .approxidate import parse_approxidate
  284. # Handle special cases specific to CLI
  285. if time_spec == "all":
  286. # Expire all entries - set to future time so everything is "older"
  287. return int(time.time()) + (100 * 365 * 24 * 60 * 60) # 100 years in future
  288. if time_spec == "never":
  289. # Never expire - set to epoch start so nothing is older
  290. return 0
  291. # Use approxidate parser for everything else
  292. return parse_approxidate(time_spec)
  293. def format_bytes(bytes: float) -> str:
  294. """Format bytes as human-readable string.
  295. Args:
  296. bytes: Number of bytes
  297. Returns:
  298. Human-readable string like "1.5 MB"
  299. """
  300. for unit in ["B", "KB", "MB", "GB"]:
  301. if bytes < 1024.0:
  302. return f"{bytes:.1f} {unit}"
  303. bytes /= 1024.0
  304. return f"{bytes:.1f} TB"
  305. def launch_editor(template_content: bytes = b"") -> bytes:
  306. """Launch an editor for the user to enter text.
  307. Args:
  308. template_content: Initial content for the editor
  309. Returns:
  310. The edited content as bytes
  311. """
  312. # Determine which editor to use
  313. editor = os.environ.get("GIT_EDITOR") or os.environ.get("EDITOR") or "vi"
  314. # Create a temporary file
  315. with tempfile.NamedTemporaryFile(mode="wb", delete=False, suffix=".txt") as f:
  316. temp_file = f.name
  317. f.write(template_content)
  318. try:
  319. # Launch the editor
  320. subprocess.run([editor, temp_file], check=True)
  321. # Read the edited content
  322. with open(temp_file, "rb") as f:
  323. content = f.read()
  324. return content
  325. finally:
  326. # Clean up the temporary file
  327. os.unlink(temp_file)
  328. def detect_terminal_width() -> int:
  329. """Detect the width of the terminal.
  330. Returns:
  331. Width of the terminal in characters, or 80 if it cannot be determined
  332. """
  333. try:
  334. return os.get_terminal_size().columns
  335. except OSError:
  336. return 80
  337. def write_columns(
  338. items: Iterator[bytes] | Sequence[bytes],
  339. out: TextIO,
  340. width: int | None = None,
  341. ) -> None:
  342. """Display items in formatted columns based on terminal width.
  343. Args:
  344. items: List or iterator of bytes objects to display in columns
  345. out: Output stream to write to
  346. width: Optional width of the terminal (if None, auto-detect)
  347. The function calculates the optimal number of columns to fit the terminal
  348. width and displays the items in a formatted column layout with proper
  349. padding and alignment.
  350. """
  351. if width is None:
  352. ter_width = detect_terminal_width()
  353. else:
  354. ter_width = width
  355. item_names = [item.decode() for item in items]
  356. def columns(
  357. names: Sequence[str], width: int, num_cols: int
  358. ) -> tuple[bool, list[int]]:
  359. if num_cols <= 0:
  360. return False, []
  361. num_rows = (len(names) + num_cols - 1) // num_cols
  362. col_widths = []
  363. for col in range(num_cols):
  364. max_width = 0
  365. for row in range(num_rows):
  366. idx = row + col * num_rows
  367. if idx < len(names):
  368. max_width = max(max_width, len(names[idx]))
  369. col_widths.append(max_width + 2) # add padding
  370. total_width = sum(col_widths)
  371. if total_width <= width:
  372. return True, col_widths
  373. return False, []
  374. best_cols = 1
  375. best_widths = []
  376. for num_cols in range(min(8, len(item_names)), 0, -1):
  377. fits, widths = columns(item_names, ter_width, num_cols)
  378. if fits:
  379. best_cols = num_cols
  380. best_widths = widths
  381. break
  382. if not best_widths:
  383. best_cols = 1
  384. best_widths = [max(len(name) for name in item_names) + 2]
  385. num_rows = (len(item_names) + best_cols - 1) // best_cols
  386. for row in range(num_rows):
  387. lines = []
  388. for col in range(best_cols):
  389. idx = row + col * num_rows
  390. if idx < len(item_names):
  391. branch_name = item_names[idx]
  392. if col < len(best_widths):
  393. lines.append(branch_name.ljust(best_widths[col]))
  394. else:
  395. lines.append(branch_name)
  396. if lines:
  397. out.write("".join(lines).rstrip() + "\n")
  398. def format_columns(
  399. items: list[str],
  400. width: int | None = None,
  401. mode: str = "column",
  402. padding: int = 1,
  403. indent: str = "",
  404. nl: str = "\n",
  405. ) -> str:
  406. r"""Format items into columns with various layout modes.
  407. Args:
  408. items: List of strings to format
  409. width: Terminal width (auto-detected if None)
  410. mode: Layout mode - "column" (fill columns first), "row" (fill rows first),
  411. "plain" (one column), or add ",dense" for unequal column widths
  412. padding: Number of spaces between columns
  413. indent: String to prepend to each line
  414. nl: String to append to each line (including newline)
  415. Returns:
  416. Formatted string with items in columns
  417. Examples:
  418. >>> format_columns(["a", "b", "c"], width=20, mode="column")
  419. "a b\\nc\\n"
  420. >>> format_columns(["a", "b", "c"], width=20, mode="row")
  421. "a b c\\n"
  422. """
  423. if not items:
  424. return ""
  425. if width is None:
  426. width = detect_terminal_width()
  427. # Parse mode
  428. mode_parts = mode.split(",")
  429. layout_mode = "column"
  430. dense = False
  431. for part in mode_parts:
  432. part = part.strip()
  433. if part in ("column", "row", "plain"):
  434. layout_mode = part
  435. elif part == "dense":
  436. dense = True
  437. elif part == "nodense":
  438. dense = False
  439. # Plain mode - one item per line
  440. if layout_mode == "plain":
  441. return "".join(indent + item + nl for item in items)
  442. # Calculate available width for content (excluding indent)
  443. available_width = width - len(indent)
  444. if available_width <= 0:
  445. available_width = width
  446. # Find optimal number of columns
  447. max_item_len = max(len(item) for item in items)
  448. # Start with maximum possible columns and work down
  449. best_num_cols = 1
  450. best_col_widths: list[int] = []
  451. for num_cols in range(min(len(items), 20), 0, -1):
  452. if layout_mode == "column":
  453. # Column mode: fill columns first (items go down, then across)
  454. num_rows = (len(items) + num_cols - 1) // num_cols
  455. else: # row mode
  456. # Row mode: fill rows first (items go across, then down)
  457. num_rows = (len(items) + num_cols - 1) // num_cols
  458. col_widths: list[int] = []
  459. if dense:
  460. # Calculate width for each column based on its contents
  461. for col in range(num_cols):
  462. max_width = 0
  463. for row in range(num_rows):
  464. if layout_mode == "column":
  465. idx = row + col * num_rows
  466. else: # row mode
  467. idx = row * num_cols + col
  468. if idx < len(items):
  469. max_width = max(max_width, len(items[idx]))
  470. if max_width > 0:
  471. col_widths.append(max_width)
  472. else:
  473. # All columns same width (nodense)
  474. max_width = 0
  475. for col in range(num_cols):
  476. for row in range(num_rows):
  477. if layout_mode == "column":
  478. idx = row + col * num_rows
  479. else: # row mode
  480. idx = row * num_cols + col
  481. if idx < len(items):
  482. max_width = max(max_width, len(items[idx]))
  483. col_widths = [max_width] * num_cols
  484. # Calculate total width including padding (but not after last column)
  485. total_width = sum(col_widths) + padding * (len(col_widths) - 1)
  486. if total_width <= available_width:
  487. best_num_cols = num_cols
  488. best_col_widths = col_widths
  489. break
  490. # If no fit found, use single column
  491. if not best_col_widths:
  492. best_num_cols = 1
  493. best_col_widths = [max_item_len]
  494. # Format output
  495. num_rows = (len(items) + best_num_cols - 1) // best_num_cols
  496. lines = []
  497. for row in range(num_rows):
  498. line_parts = []
  499. for col in range(best_num_cols):
  500. if layout_mode == "column":
  501. idx = row + col * num_rows
  502. else: # row mode
  503. idx = row * best_num_cols + col
  504. if idx < len(items):
  505. item = items[idx]
  506. # Pad item to column width, except for last column in row
  507. if col < best_num_cols - 1 and col < len(best_col_widths) - 1:
  508. item = item.ljust(best_col_widths[col] + padding)
  509. line_parts.append(item)
  510. if line_parts:
  511. lines.append(indent + "".join(line_parts).rstrip() + nl)
  512. return "".join(lines)
  513. class PagerBuffer(BinaryIO):
  514. """Binary buffer wrapper for Pager to mimic sys.stdout.buffer."""
  515. def __init__(self, pager: "Pager") -> None:
  516. """Initialize PagerBuffer.
  517. Args:
  518. pager: Pager instance to wrap
  519. """
  520. self.pager = pager
  521. def write(self, data: bytes | bytearray | memoryview) -> int: # type: ignore[override]
  522. """Write bytes to pager."""
  523. # Convert to bytes and decode to string for the pager
  524. text = bytes(data).decode("utf-8", errors="replace")
  525. return self.pager.write(text)
  526. def flush(self) -> None:
  527. """Flush the pager."""
  528. return self.pager.flush()
  529. def writelines(self, lines: Iterable[bytes | bytearray | memoryview]) -> None: # type: ignore[override]
  530. """Write multiple lines to pager."""
  531. for line in lines:
  532. self.write(line)
  533. def readable(self) -> bool:
  534. """Return whether the buffer is readable (it's not)."""
  535. return False
  536. def writable(self) -> bool:
  537. """Return whether the buffer is writable."""
  538. return not self.pager._closed
  539. def seekable(self) -> bool:
  540. """Return whether the buffer is seekable (it's not)."""
  541. return False
  542. def close(self) -> None:
  543. """Close the pager."""
  544. return self.pager.close()
  545. @property
  546. def closed(self) -> bool:
  547. """Return whether the buffer is closed."""
  548. return self.pager.closed
  549. @property
  550. def mode(self) -> str:
  551. """Return the mode."""
  552. return "wb"
  553. @property
  554. def name(self) -> str:
  555. """Return the name."""
  556. return "<pager.buffer>"
  557. def fileno(self) -> int:
  558. """Return the file descriptor (not supported)."""
  559. raise io.UnsupportedOperation("PagerBuffer does not support fileno()")
  560. def isatty(self) -> bool:
  561. """Return whether the buffer is a TTY."""
  562. return False
  563. def read(self, size: int = -1) -> bytes:
  564. """Read from the buffer (not supported)."""
  565. raise io.UnsupportedOperation("PagerBuffer does not support reading")
  566. def read1(self, size: int = -1) -> bytes:
  567. """Read from the buffer (not supported)."""
  568. raise io.UnsupportedOperation("PagerBuffer does not support reading")
  569. def readinto(self, b: bytearray) -> int:
  570. """Read into buffer (not supported)."""
  571. raise io.UnsupportedOperation("PagerBuffer does not support reading")
  572. def readinto1(self, b: bytearray) -> int:
  573. """Read into buffer (not supported)."""
  574. raise io.UnsupportedOperation("PagerBuffer does not support reading")
  575. def readline(self, size: int = -1) -> bytes:
  576. """Read a line from the buffer (not supported)."""
  577. raise io.UnsupportedOperation("PagerBuffer does not support reading")
  578. def readlines(self, hint: int = -1) -> list[bytes]:
  579. """Read lines from the buffer (not supported)."""
  580. raise io.UnsupportedOperation("PagerBuffer does not support reading")
  581. def seek(self, offset: int, whence: int = 0) -> int:
  582. """Seek in the buffer (not supported)."""
  583. raise io.UnsupportedOperation("PagerBuffer does not support seeking")
  584. def tell(self) -> int:
  585. """Return the current position (not supported)."""
  586. raise io.UnsupportedOperation("PagerBuffer does not support tell()")
  587. def truncate(self, size: int | None = None) -> int:
  588. """Truncate the buffer (not supported)."""
  589. raise io.UnsupportedOperation("PagerBuffer does not support truncation")
  590. def __iter__(self) -> "PagerBuffer":
  591. """Return iterator (not supported)."""
  592. raise io.UnsupportedOperation("PagerBuffer does not support iteration")
  593. def __next__(self) -> bytes:
  594. """Return next line (not supported)."""
  595. raise io.UnsupportedOperation("PagerBuffer does not support iteration")
  596. def __enter__(self) -> "PagerBuffer":
  597. """Enter context manager."""
  598. return self
  599. def __exit__(
  600. self,
  601. exc_type: type[BaseException] | None,
  602. exc_val: BaseException | None,
  603. exc_tb: TracebackType | None,
  604. ) -> None:
  605. """Exit context manager."""
  606. self.close()
  607. class Pager(TextIO):
  608. """File-like object that pages output through external pager programs."""
  609. def __init__(self, pager_cmd: str = "cat") -> None:
  610. """Initialize Pager.
  611. Args:
  612. pager_cmd: Command to use for paging (default: "cat")
  613. """
  614. self.pager_process: subprocess.Popen[str] | None = None
  615. self._buffer = PagerBuffer(self)
  616. self._closed = False
  617. self.pager_cmd = pager_cmd
  618. self._pager_died = False
  619. def _get_pager_command(self) -> str:
  620. """Get the pager command to use."""
  621. return self.pager_cmd
  622. def _ensure_pager_started(self) -> None:
  623. """Start the pager process if not already started."""
  624. if self.pager_process is None and not self._closed:
  625. try:
  626. pager_cmd = self._get_pager_command()
  627. self.pager_process = subprocess.Popen(
  628. pager_cmd,
  629. shell=True,
  630. stdin=subprocess.PIPE,
  631. stdout=sys.stdout,
  632. stderr=sys.stderr,
  633. text=True,
  634. )
  635. except (OSError, subprocess.SubprocessError):
  636. # Pager failed to start, fall back to direct output
  637. self.pager_process = None
  638. def write(self, text: str) -> int:
  639. """Write text to the pager."""
  640. if self._closed:
  641. raise ValueError("I/O operation on closed file")
  642. # If pager died (user quit), stop writing output
  643. if self._pager_died:
  644. return len(text)
  645. self._ensure_pager_started()
  646. if self.pager_process and self.pager_process.stdin:
  647. try:
  648. result = self.pager_process.stdin.write(text)
  649. assert isinstance(result, int)
  650. return result
  651. except (OSError, subprocess.SubprocessError, BrokenPipeError):
  652. # Pager died (user quit), stop writing output
  653. self._pager_died = True
  654. return len(text)
  655. else:
  656. # No pager available, write directly to stdout
  657. return sys.stdout.write(text)
  658. def flush(self) -> None:
  659. """Flush the pager."""
  660. if self._closed or self._pager_died:
  661. return
  662. if self.pager_process and self.pager_process.stdin:
  663. try:
  664. self.pager_process.stdin.flush()
  665. except (OSError, subprocess.SubprocessError, BrokenPipeError):
  666. self._pager_died = True
  667. else:
  668. sys.stdout.flush()
  669. def close(self) -> None:
  670. """Close the pager."""
  671. if self._closed:
  672. return
  673. self._closed = True
  674. if self.pager_process:
  675. try:
  676. if self.pager_process.stdin:
  677. self.pager_process.stdin.close()
  678. self.pager_process.wait()
  679. except (OSError, subprocess.SubprocessError):
  680. pass
  681. self.pager_process = None
  682. def __enter__(self) -> "Pager":
  683. """Context manager entry."""
  684. return self
  685. def __exit__(
  686. self,
  687. exc_type: type | None,
  688. exc_val: BaseException | None,
  689. exc_tb: types.TracebackType | None,
  690. ) -> None:
  691. """Context manager exit."""
  692. self.close()
  693. # Additional file-like methods for compatibility
  694. def writelines(self, lines: Iterable[str]) -> None:
  695. """Write a list of lines to the pager."""
  696. if self._pager_died:
  697. return
  698. for line in lines:
  699. self.write(line)
  700. @property
  701. def closed(self) -> bool:
  702. """Return whether the pager is closed."""
  703. return self._closed
  704. def readable(self) -> bool:
  705. """Return whether the pager is readable (it's not)."""
  706. return False
  707. def writable(self) -> bool:
  708. """Return whether the pager is writable."""
  709. return not self._closed
  710. def seekable(self) -> bool:
  711. """Return whether the pager is seekable (it's not)."""
  712. return False
  713. @property
  714. def buffer(self) -> BinaryIO:
  715. """Return the underlying binary buffer."""
  716. return self._buffer
  717. @property
  718. def encoding(self) -> str:
  719. """Return the encoding used."""
  720. return "utf-8"
  721. @property
  722. def errors(self) -> str | None:
  723. """Return the error handling scheme."""
  724. return "replace"
  725. def fileno(self) -> int:
  726. """Return the file descriptor (not supported)."""
  727. raise io.UnsupportedOperation("Pager does not support fileno()")
  728. def isatty(self) -> bool:
  729. """Return whether the pager is a TTY."""
  730. return False
  731. @property
  732. def line_buffering(self) -> bool:
  733. """Return whether line buffering is enabled."""
  734. return True
  735. @property
  736. def mode(self) -> str:
  737. """Return the mode."""
  738. return "w"
  739. @property
  740. def name(self) -> str:
  741. """Return the name."""
  742. return "<pager>"
  743. @property
  744. def newlines(self) -> str | tuple[str, ...] | None:
  745. """Return the newlines mode."""
  746. return None
  747. def read(self, size: int = -1) -> str:
  748. """Read from the pager (not supported)."""
  749. raise io.UnsupportedOperation("Pager does not support reading")
  750. def readline(self, size: int = -1) -> str:
  751. """Read a line from the pager (not supported)."""
  752. raise io.UnsupportedOperation("Pager does not support reading")
  753. def readlines(self, hint: int = -1) -> list[str]:
  754. """Read lines from the pager (not supported)."""
  755. raise io.UnsupportedOperation("Pager does not support reading")
  756. def seek(self, offset: int, whence: int = 0) -> int:
  757. """Seek in the pager (not supported)."""
  758. raise io.UnsupportedOperation("Pager does not support seeking")
  759. def tell(self) -> int:
  760. """Return the current position (not supported)."""
  761. raise io.UnsupportedOperation("Pager does not support tell()")
  762. def truncate(self, size: int | None = None) -> int:
  763. """Truncate the pager (not supported)."""
  764. raise io.UnsupportedOperation("Pager does not support truncation")
  765. def __iter__(self) -> "Pager":
  766. """Return iterator (not supported)."""
  767. raise io.UnsupportedOperation("Pager does not support iteration")
  768. def __next__(self) -> str:
  769. """Return next line (not supported)."""
  770. raise io.UnsupportedOperation("Pager does not support iteration")
  771. class _StreamContextAdapter:
  772. """Adapter to make streams work with context manager protocol."""
  773. def __init__(self, stream: TextIO | BinaryIO) -> None:
  774. self.stream = stream
  775. # Expose buffer if it exists
  776. if hasattr(stream, "buffer"):
  777. self.buffer = stream.buffer
  778. else:
  779. self.buffer = stream
  780. def __enter__(self) -> TextIO:
  781. # We only use this with sys.stdout which is TextIO
  782. return self.stream # type: ignore[return-value]
  783. def __exit__(
  784. self,
  785. exc_type: type[BaseException] | None,
  786. exc_val: BaseException | None,
  787. exc_tb: TracebackType | None,
  788. ) -> None:
  789. # For stdout/stderr, we don't close them
  790. pass
  791. def __getattr__(self, name: str) -> object:
  792. return getattr(self.stream, name)
  793. def get_pager(
  794. config: Config | None = None, cmd_name: str | None = None
  795. ) -> "_StreamContextAdapter | Pager":
  796. """Get a pager instance if paging should be used, otherwise return sys.stdout.
  797. Args:
  798. config: Optional config instance (e.g., StackedConfig) to read settings from
  799. cmd_name: Optional command name for per-command pager settings
  800. Returns:
  801. Either a wrapped sys.stdout or a Pager instance (both context managers)
  802. """
  803. # Check global pager disable flag
  804. if getattr(get_pager, "_disabled", False):
  805. return _StreamContextAdapter(sys.stdout)
  806. # Don't page if stdout is not a terminal
  807. if not sys.stdout.isatty():
  808. return _StreamContextAdapter(sys.stdout)
  809. # Priority order for pager command (following git's behavior):
  810. # 1. Check pager.<cmd> config (if cmd_name provided)
  811. # 2. Check environment variables: DULWICH_PAGER, GIT_PAGER, PAGER
  812. # 3. Check core.pager config
  813. # 4. Fallback to common pagers
  814. pager_cmd = None
  815. # 1. Check per-command pager config (pager.<cmd>)
  816. if config and cmd_name:
  817. try:
  818. pager_value = config.get(
  819. ("pager",), cmd_name.encode() if isinstance(cmd_name, str) else cmd_name
  820. )
  821. except KeyError:
  822. pass
  823. else:
  824. if pager_value == b"false":
  825. return _StreamContextAdapter(sys.stdout)
  826. elif pager_value != b"true":
  827. # It's a custom pager command
  828. pager_cmd = (
  829. pager_value.decode()
  830. if isinstance(pager_value, bytes)
  831. else pager_value
  832. )
  833. # 2. Check environment variables
  834. if not pager_cmd:
  835. for env_var in ["DULWICH_PAGER", "GIT_PAGER", "PAGER"]:
  836. pager = os.environ.get(env_var)
  837. if pager:
  838. if pager == "false":
  839. return _StreamContextAdapter(sys.stdout)
  840. pager_cmd = pager
  841. break
  842. # 3. Check core.pager config
  843. if not pager_cmd and config:
  844. try:
  845. core_pager = config.get(("core",), b"pager")
  846. except KeyError:
  847. pass
  848. else:
  849. if core_pager == b"false" or core_pager == b"":
  850. return _StreamContextAdapter(sys.stdout)
  851. pager_cmd = (
  852. core_pager.decode() if isinstance(core_pager, bytes) else core_pager
  853. )
  854. # 4. Fallback to common pagers
  855. if not pager_cmd:
  856. for pager in ["less", "more", "cat"]:
  857. if shutil.which(pager):
  858. if pager == "less":
  859. pager_cmd = "less -FRX" # -F: quit if one screen, -R: raw control chars, -X: no init/deinit
  860. else:
  861. pager_cmd = pager
  862. break
  863. else:
  864. pager_cmd = "cat" # Ultimate fallback
  865. return Pager(pager_cmd)
  866. def disable_pager() -> None:
  867. """Disable pager for this session."""
  868. get_pager._disabled = True # type: ignore[attr-defined]
  869. def enable_pager() -> None:
  870. """Enable pager for this session."""
  871. get_pager._disabled = False # type: ignore[attr-defined]
  872. class Command:
  873. """A Dulwich subcommand."""
  874. def run(self, args: Sequence[str]) -> int | None:
  875. """Run the command."""
  876. raise NotImplementedError(self.run)
  877. class cmd_archive(Command):
  878. """Create an archive of files from a named tree."""
  879. def run(self, args: Sequence[str]) -> None:
  880. """Execute the archive command.
  881. Args:
  882. args: Command line arguments
  883. """
  884. parser = argparse.ArgumentParser()
  885. parser.add_argument(
  886. "--remote",
  887. type=str,
  888. help="Retrieve archive from specified remote repo",
  889. )
  890. parser.add_argument("committish", type=str, nargs="?")
  891. parsed_args = parser.parse_args(args)
  892. if parsed_args.remote:
  893. client, path = get_transport_and_path(parsed_args.remote)
  894. def stdout_write(data: bytes) -> None:
  895. sys.stdout.buffer.write(data)
  896. def stderr_write(data: bytes) -> None:
  897. sys.stderr.buffer.write(data)
  898. client.archive(
  899. path.encode("utf-8") if isinstance(path, str) else path,
  900. parsed_args.committish.encode("utf-8")
  901. if isinstance(parsed_args.committish, str)
  902. else parsed_args.committish,
  903. stdout_write,
  904. write_error=stderr_write,
  905. )
  906. else:
  907. # Use binary buffer for archive output
  908. outstream: BinaryIO = sys.stdout.buffer
  909. errstream: BinaryIO = sys.stderr.buffer
  910. porcelain.archive(
  911. ".",
  912. parsed_args.committish,
  913. outstream=outstream,
  914. errstream=errstream,
  915. )
  916. class cmd_add(Command):
  917. """Add file contents to the index."""
  918. def run(self, argv: Sequence[str]) -> None:
  919. """Execute the add command.
  920. Args:
  921. argv: Command line arguments
  922. """
  923. parser = argparse.ArgumentParser()
  924. parser.add_argument("path", nargs="+")
  925. args = parser.parse_args(argv)
  926. # Convert '.' to None to add all files
  927. paths = args.path
  928. if len(paths) == 1 and paths[0] == ".":
  929. paths = None
  930. porcelain.add(".", paths=paths)
  931. class cmd_annotate(Command):
  932. """Annotate each line in a file with commit information."""
  933. def run(self, argv: Sequence[str]) -> None:
  934. """Execute the annotate command.
  935. Args:
  936. argv: Command line arguments
  937. """
  938. parser = argparse.ArgumentParser()
  939. parser.add_argument("path", help="Path to file to annotate")
  940. parser.add_argument("committish", nargs="?", help="Commit to start from")
  941. args = parser.parse_args(argv)
  942. with Repo(".") as repo:
  943. config = repo.get_config_stack()
  944. with get_pager(config=config, cmd_name="annotate") as outstream:
  945. results = porcelain.annotate(repo, args.path, args.committish)
  946. for (commit, entry), line in results:
  947. # Show shortened commit hash and line content
  948. commit_hash = commit.id[:8]
  949. outstream.write(f"{commit_hash.decode()} {line.decode()}\n")
  950. class cmd_blame(Command):
  951. """Show what revision and author last modified each line of a file."""
  952. def run(self, argv: Sequence[str]) -> None:
  953. """Execute the blame command.
  954. Args:
  955. argv: Command line arguments
  956. """
  957. # blame is an alias for annotate
  958. cmd_annotate().run(argv)
  959. class cmd_rm(Command):
  960. """Remove files from the working tree and from the index."""
  961. def run(self, argv: Sequence[str]) -> None:
  962. """Execute the rm command.
  963. Args:
  964. argv: Command line arguments
  965. """
  966. parser = argparse.ArgumentParser()
  967. parser.add_argument(
  968. "--cached", action="store_true", help="Remove from index only"
  969. )
  970. parser.add_argument("path", type=Path, nargs="+")
  971. args = parser.parse_args(argv)
  972. porcelain.remove(".", paths=args.path, cached=args.cached)
  973. class cmd_mv(Command):
  974. """Move or rename a file, a directory, or a symlink."""
  975. def run(self, argv: Sequence[str]) -> None:
  976. """Execute the mv command.
  977. Args:
  978. argv: Command line arguments
  979. """
  980. parser = argparse.ArgumentParser()
  981. parser.add_argument(
  982. "-f",
  983. "--force",
  984. action="store_true",
  985. help="Force move even if destination exists",
  986. )
  987. parser.add_argument("source", type=Path)
  988. parser.add_argument("destination", type=Path)
  989. args = parser.parse_args(argv)
  990. porcelain.mv(".", args.source, args.destination, force=args.force)
  991. class cmd_fetch_pack(Command):
  992. """Receive missing objects from another repository."""
  993. def run(self, argv: Sequence[str]) -> None:
  994. """Execute the fetch-pack command.
  995. Args:
  996. argv: Command line arguments
  997. """
  998. parser = argparse.ArgumentParser()
  999. parser.add_argument("--all", action="store_true")
  1000. parser.add_argument("location", nargs="?", type=str)
  1001. parser.add_argument("refs", nargs="*", type=str)
  1002. args = parser.parse_args(argv)
  1003. client, path = get_transport_and_path(args.location)
  1004. r = Repo(".")
  1005. if args.all:
  1006. determine_wants = r.object_store.determine_wants_all
  1007. else:
  1008. def determine_wants(
  1009. refs: Mapping[Ref, ObjectID], depth: int | None = None
  1010. ) -> list[ObjectID]:
  1011. return [
  1012. ObjectID(y.encode("utf-8"))
  1013. for y in args.refs
  1014. if y not in r.object_store
  1015. ]
  1016. client.fetch(path.encode("utf-8"), r, determine_wants)
  1017. class cmd_fetch(Command):
  1018. """Download objects and refs from another repository."""
  1019. def run(self, args: Sequence[str]) -> None:
  1020. """Execute the fetch command.
  1021. Args:
  1022. args: Command line arguments
  1023. """
  1024. parser = argparse.ArgumentParser()
  1025. # Mutually exclusive group for location vs --all
  1026. location_group = parser.add_mutually_exclusive_group(required=True)
  1027. location_group.add_argument(
  1028. "location", nargs="?", default=None, help="Remote location to fetch from"
  1029. )
  1030. location_group.add_argument(
  1031. "--all", action="store_true", help="Fetch all remotes"
  1032. )
  1033. # Mutually exclusive group for tag handling
  1034. tag_group = parser.add_mutually_exclusive_group()
  1035. tag_group.add_argument(
  1036. "--tags", action="store_true", help="Fetch all tags from remote"
  1037. )
  1038. tag_group.add_argument(
  1039. "--no-tags", action="store_true", help="Don't fetch any tags from remote"
  1040. )
  1041. parser.add_argument(
  1042. "--depth",
  1043. type=int,
  1044. help="Create a shallow clone with a history truncated to the specified number of commits",
  1045. )
  1046. parser.add_argument(
  1047. "--shallow-since",
  1048. type=str,
  1049. help="Deepen or shorten the history of a shallow repository to include all reachable commits after <date>",
  1050. )
  1051. parser.add_argument(
  1052. "--shallow-exclude",
  1053. type=str,
  1054. action="append",
  1055. help="Deepen or shorten the history of a shallow repository to exclude commits reachable from a specified remote branch or tag",
  1056. )
  1057. parsed_args = parser.parse_args(args)
  1058. r = Repo(".")
  1059. def progress(msg: bytes) -> None:
  1060. sys.stdout.buffer.write(msg)
  1061. # Determine include_tags setting
  1062. include_tags = False
  1063. if parsed_args.tags:
  1064. include_tags = True
  1065. elif not parsed_args.no_tags:
  1066. # Default behavior - don't force tag inclusion
  1067. include_tags = False
  1068. if parsed_args.all:
  1069. # Fetch from all remotes
  1070. config = r.get_config()
  1071. remotes = set()
  1072. for section in config.sections():
  1073. if len(section) == 2 and section[0] == b"remote":
  1074. remotes.add(section[1].decode())
  1075. if not remotes:
  1076. logger.warning("No remotes configured")
  1077. return
  1078. for remote_name in sorted(remotes):
  1079. logger.info("Fetching %s", remote_name)
  1080. porcelain.fetch(
  1081. r,
  1082. remote_location=remote_name,
  1083. depth=parsed_args.depth,
  1084. include_tags=include_tags,
  1085. shallow_since=parsed_args.shallow_since,
  1086. shallow_exclude=parsed_args.shallow_exclude,
  1087. )
  1088. else:
  1089. # Fetch from specific location
  1090. porcelain.fetch(
  1091. r,
  1092. remote_location=parsed_args.location,
  1093. depth=parsed_args.depth,
  1094. include_tags=include_tags,
  1095. shallow_since=parsed_args.shallow_since,
  1096. shallow_exclude=parsed_args.shallow_exclude,
  1097. )
  1098. class cmd_for_each_ref(Command):
  1099. """Output information on each ref."""
  1100. def run(self, args: Sequence[str]) -> None:
  1101. """Execute the for-each-ref command.
  1102. Args:
  1103. args: Command line arguments
  1104. """
  1105. parser = argparse.ArgumentParser()
  1106. parser.add_argument("pattern", type=str, nargs="?")
  1107. parsed_args = parser.parse_args(args)
  1108. for sha, object_type, ref in porcelain.for_each_ref(".", parsed_args.pattern):
  1109. logger.info("%s %s\t%s", sha.decode(), object_type.decode(), ref.decode())
  1110. class cmd_fsck(Command):
  1111. """Verify the connectivity and validity of objects in the database."""
  1112. def run(self, args: Sequence[str]) -> None:
  1113. """Execute the fsck command.
  1114. Args:
  1115. args: Command line arguments
  1116. """
  1117. parser = argparse.ArgumentParser()
  1118. parser.parse_args(args)
  1119. for obj, msg in porcelain.fsck("."):
  1120. logger.info("%s: %s", obj.decode() if isinstance(obj, bytes) else obj, msg)
  1121. class cmd_log(Command):
  1122. """Show commit logs."""
  1123. def run(self, args: Sequence[str]) -> None:
  1124. """Execute the log command.
  1125. Args:
  1126. args: Command line arguments
  1127. """
  1128. parser = argparse.ArgumentParser()
  1129. parser.add_argument(
  1130. "--reverse",
  1131. action="store_true",
  1132. help="Reverse order in which entries are printed",
  1133. )
  1134. parser.add_argument(
  1135. "--name-status",
  1136. action="store_true",
  1137. help="Print name/status for each changed file",
  1138. )
  1139. parser.add_argument("paths", nargs="*", help="Paths to show log for")
  1140. parsed_args = parser.parse_args(args)
  1141. with Repo(".") as repo:
  1142. config = repo.get_config_stack()
  1143. with get_pager(config=config, cmd_name="log") as outstream:
  1144. porcelain.log(
  1145. repo,
  1146. paths=parsed_args.paths,
  1147. reverse=parsed_args.reverse,
  1148. name_status=parsed_args.name_status,
  1149. outstream=outstream,
  1150. )
  1151. class cmd_diff(Command):
  1152. """Show changes between commits, commit and working tree, etc."""
  1153. def run(self, args: Sequence[str]) -> None:
  1154. """Execute the diff command.
  1155. Args:
  1156. args: Command line arguments
  1157. """
  1158. parser = argparse.ArgumentParser()
  1159. parser.add_argument(
  1160. "committish", nargs="*", default=[], help="Commits or refs to compare"
  1161. )
  1162. parser.add_argument("--staged", action="store_true", help="Show staged changes")
  1163. parser.add_argument(
  1164. "--cached",
  1165. action="store_true",
  1166. help="Show staged changes (same as --staged)",
  1167. )
  1168. parser.add_argument(
  1169. "--color",
  1170. choices=["always", "never", "auto"],
  1171. default="auto",
  1172. help="Use colored output (requires rich)",
  1173. )
  1174. parser.add_argument(
  1175. "--patience",
  1176. action="store_true",
  1177. help="Use patience diff algorithm",
  1178. )
  1179. parser.add_argument(
  1180. "--diff-algorithm",
  1181. choices=["myers", "patience"],
  1182. default="myers",
  1183. help="Choose a diff algorithm",
  1184. )
  1185. parser.add_argument(
  1186. "--stat",
  1187. action="store_true",
  1188. help="Show diffstat instead of full diff",
  1189. )
  1190. parser.add_argument(
  1191. "--", dest="separator", action="store_true", help=argparse.SUPPRESS
  1192. )
  1193. parser.add_argument("paths", nargs="*", default=[], help="Paths to limit diff")
  1194. # Handle the -- separator for paths
  1195. if "--" in args:
  1196. sep_index = args.index("--")
  1197. parsed_args = parser.parse_args(args[:sep_index])
  1198. parsed_args.paths = args[sep_index + 1 :]
  1199. else:
  1200. parsed_args = parser.parse_args(args)
  1201. # Determine diff algorithm
  1202. diff_algorithm = parsed_args.diff_algorithm
  1203. if parsed_args.patience:
  1204. diff_algorithm = "patience"
  1205. # Determine if we should use color
  1206. def _should_use_color() -> bool:
  1207. if parsed_args.color == "always":
  1208. return True
  1209. elif parsed_args.color == "never":
  1210. return False
  1211. else: # auto
  1212. return sys.stdout.isatty()
  1213. def _create_output_stream(outstream: TextIO) -> BinaryIO:
  1214. """Create output stream, optionally with colorization."""
  1215. if not _should_use_color():
  1216. return outstream.buffer
  1217. from .diff import ColorizedDiffStream
  1218. if not ColorizedDiffStream.is_available():
  1219. if parsed_args.color == "always":
  1220. raise ImportError(
  1221. "Rich is required for colored output. Install with: pip install 'dulwich[colordiff]'"
  1222. )
  1223. else:
  1224. logging.warning(
  1225. "Rich not available, disabling colored output. Install with: pip install 'dulwich[colordiff]'"
  1226. )
  1227. return outstream.buffer
  1228. return ColorizedDiffStream(outstream.buffer)
  1229. with Repo(".") as repo:
  1230. config = repo.get_config_stack()
  1231. with get_pager(config=config, cmd_name="diff") as outstream:
  1232. # For --stat mode, capture the diff in a BytesIO buffer
  1233. if parsed_args.stat:
  1234. import io
  1235. from .diffstat import diffstat
  1236. diff_buffer: BinaryIO = io.BytesIO()
  1237. output_stream: BinaryIO = diff_buffer
  1238. else:
  1239. output_stream = _create_output_stream(outstream)
  1240. try:
  1241. if len(parsed_args.committish) == 0:
  1242. # Show diff for working tree or staged changes
  1243. porcelain.diff(
  1244. repo,
  1245. staged=(parsed_args.staged or parsed_args.cached),
  1246. paths=parsed_args.paths or None,
  1247. outstream=output_stream,
  1248. diff_algorithm=diff_algorithm,
  1249. )
  1250. elif len(parsed_args.committish) == 1:
  1251. # Show diff between working tree and specified commit
  1252. if parsed_args.staged or parsed_args.cached:
  1253. parser.error(
  1254. "--staged/--cached cannot be used with commits"
  1255. )
  1256. porcelain.diff(
  1257. repo,
  1258. commit=parsed_args.committish[0],
  1259. staged=False,
  1260. paths=parsed_args.paths or None,
  1261. outstream=output_stream,
  1262. diff_algorithm=diff_algorithm,
  1263. )
  1264. elif len(parsed_args.committish) == 2:
  1265. # Show diff between two commits
  1266. porcelain.diff(
  1267. repo,
  1268. commit=parsed_args.committish[0],
  1269. commit2=parsed_args.committish[1],
  1270. paths=parsed_args.paths or None,
  1271. outstream=output_stream,
  1272. diff_algorithm=diff_algorithm,
  1273. )
  1274. else:
  1275. parser.error("Too many arguments - specify at most two commits")
  1276. except DiffAlgorithmNotAvailable as e:
  1277. sys.stderr.write(f"fatal: {e}\n")
  1278. sys.exit(1)
  1279. if parsed_args.stat:
  1280. # Generate and output diffstat from captured diff
  1281. assert isinstance(diff_buffer, io.BytesIO)
  1282. diff_data = diff_buffer.getvalue()
  1283. lines = diff_data.split(b"\n")
  1284. stat_output = diffstat(lines)
  1285. outstream.buffer.write(stat_output + b"\n")
  1286. else:
  1287. # Flush any remaining output
  1288. if hasattr(output_stream, "flush"):
  1289. output_stream.flush()
  1290. class cmd_dump_pack(Command):
  1291. """Dump the contents of a pack file for debugging."""
  1292. def run(self, args: Sequence[str]) -> None:
  1293. """Execute the dump-pack command.
  1294. Args:
  1295. args: Command line arguments
  1296. """
  1297. parser = argparse.ArgumentParser()
  1298. parser.add_argument("filename", help="Pack file to dump")
  1299. parsed_args = parser.parse_args(args)
  1300. basename, _ = os.path.splitext(parsed_args.filename)
  1301. x = Pack(basename)
  1302. logger.info("Object names checksum: %s", x.name().decode("ascii", "replace"))
  1303. logger.info("Checksum: %r", sha_to_hex(RawObjectID(x.get_stored_checksum())))
  1304. x.check()
  1305. logger.info("Length: %d", len(x))
  1306. for name in x:
  1307. try:
  1308. logger.info("\t%s", x[name])
  1309. except KeyError as k:
  1310. logger.error(
  1311. "\t%s: Unable to resolve base %r",
  1312. name.decode("ascii", "replace"),
  1313. k,
  1314. )
  1315. except ApplyDeltaError as e:
  1316. logger.error(
  1317. "\t%s: Unable to apply delta: %r",
  1318. name.decode("ascii", "replace"),
  1319. e,
  1320. )
  1321. class cmd_dump_index(Command):
  1322. """Show information about a pack index file."""
  1323. def run(self, args: Sequence[str]) -> None:
  1324. """Execute the dump-index command.
  1325. Args:
  1326. args: Command line arguments
  1327. """
  1328. parser = argparse.ArgumentParser()
  1329. parser.add_argument("filename", help="Index file to dump")
  1330. parsed_args = parser.parse_args(args)
  1331. idx = Index(parsed_args.filename)
  1332. for o in idx:
  1333. logger.info("%s %s", o, idx[o])
  1334. class cmd_interpret_trailers(Command):
  1335. """Add or parse structured information in commit messages."""
  1336. def run(self, args: Sequence[str]) -> None:
  1337. """Execute the interpret-trailers command.
  1338. Args:
  1339. args: Command line arguments
  1340. """
  1341. parser = argparse.ArgumentParser()
  1342. parser.add_argument(
  1343. "file",
  1344. nargs="?",
  1345. help="File to read message from. If not specified, reads from stdin.",
  1346. )
  1347. parser.add_argument(
  1348. "--trailer",
  1349. action="append",
  1350. dest="trailers",
  1351. metavar="<token>[(=|:)<value>]",
  1352. help="Trailer to add. Can be specified multiple times.",
  1353. )
  1354. parser.add_argument(
  1355. "--trim-empty",
  1356. action="store_true",
  1357. help="Remove trailers with empty values",
  1358. )
  1359. parser.add_argument(
  1360. "--only-trailers",
  1361. action="store_true",
  1362. help="Output only the trailers, not the message body",
  1363. )
  1364. parser.add_argument(
  1365. "--only-input",
  1366. action="store_true",
  1367. help="Don't add new trailers, only parse existing ones",
  1368. )
  1369. parser.add_argument(
  1370. "--unfold", action="store_true", help="Join multiline values into one line"
  1371. )
  1372. parser.add_argument(
  1373. "--parse",
  1374. action="store_true",
  1375. help="Shorthand for --only-trailers --only-input --unfold",
  1376. )
  1377. parser.add_argument(
  1378. "--where",
  1379. choices=["end", "start", "after", "before"],
  1380. default="end",
  1381. help="Where to place new trailers",
  1382. )
  1383. parser.add_argument(
  1384. "--if-exists",
  1385. choices=[
  1386. "add",
  1387. "replace",
  1388. "addIfDifferent",
  1389. "addIfDifferentNeighbor",
  1390. "doNothing",
  1391. ],
  1392. default="addIfDifferentNeighbor",
  1393. help="Action if trailer already exists",
  1394. )
  1395. parser.add_argument(
  1396. "--if-missing",
  1397. choices=["add", "doNothing"],
  1398. default="add",
  1399. help="Action if trailer is missing",
  1400. )
  1401. parsed_args = parser.parse_args(args)
  1402. # Read message from file or stdin
  1403. if parsed_args.file:
  1404. with open(parsed_args.file, "rb") as f:
  1405. message = f.read()
  1406. else:
  1407. message = sys.stdin.buffer.read()
  1408. # Parse trailer arguments
  1409. trailer_list = []
  1410. if parsed_args.trailers:
  1411. for trailer_spec in parsed_args.trailers:
  1412. # Parse "key:value" or "key=value" or just "key"
  1413. if ":" in trailer_spec:
  1414. key, value = trailer_spec.split(":", 1)
  1415. elif "=" in trailer_spec:
  1416. key, value = trailer_spec.split("=", 1)
  1417. else:
  1418. key = trailer_spec
  1419. value = ""
  1420. trailer_list.append((key.strip(), value.strip()))
  1421. # Call interpret_trailers
  1422. result = porcelain.interpret_trailers(
  1423. message,
  1424. trailers=trailer_list if trailer_list else None,
  1425. trim_empty=parsed_args.trim_empty,
  1426. only_trailers=parsed_args.only_trailers,
  1427. only_input=parsed_args.only_input,
  1428. unfold=parsed_args.unfold,
  1429. parse=parsed_args.parse,
  1430. where=parsed_args.where,
  1431. if_exists=parsed_args.if_exists,
  1432. if_missing=parsed_args.if_missing,
  1433. )
  1434. # Output result
  1435. sys.stdout.buffer.write(result)
  1436. class cmd_stripspace(Command):
  1437. """Remove unnecessary whitespace from text."""
  1438. def run(self, args: Sequence[str]) -> None:
  1439. """Execute the stripspace command.
  1440. Args:
  1441. args: Command line arguments
  1442. """
  1443. parser = argparse.ArgumentParser()
  1444. parser.add_argument(
  1445. "file",
  1446. nargs="?",
  1447. help="File to read text from. If not specified, reads from stdin.",
  1448. )
  1449. parser.add_argument(
  1450. "-s",
  1451. "--strip-comments",
  1452. action="store_true",
  1453. help="Strip lines that begin with comment character",
  1454. )
  1455. parser.add_argument(
  1456. "-c",
  1457. "--comment-lines",
  1458. action="store_true",
  1459. help="Prepend comment character to each line",
  1460. )
  1461. parser.add_argument(
  1462. "--comment-char",
  1463. default="#",
  1464. help="Comment character to use (default: #)",
  1465. )
  1466. parsed_args = parser.parse_args(args)
  1467. # Read text from file or stdin
  1468. if parsed_args.file:
  1469. with open(parsed_args.file, "rb") as f:
  1470. text = f.read()
  1471. else:
  1472. text = sys.stdin.buffer.read()
  1473. # Call stripspace
  1474. result = porcelain.stripspace(
  1475. text,
  1476. strip_comments=parsed_args.strip_comments,
  1477. comment_char=parsed_args.comment_char,
  1478. comment_lines=parsed_args.comment_lines,
  1479. )
  1480. # Output result
  1481. sys.stdout.buffer.write(result)
  1482. class cmd_column(Command):
  1483. """Display data in columns."""
  1484. def run(self, args: Sequence[str]) -> None:
  1485. """Execute the column command.
  1486. Args:
  1487. args: Command line arguments
  1488. """
  1489. parser = argparse.ArgumentParser(
  1490. description="Format input data into columns for better readability"
  1491. )
  1492. parser.add_argument(
  1493. "--mode",
  1494. default="column",
  1495. help=(
  1496. "Layout mode: 'column' (fill columns first), 'row' (fill rows first), "
  1497. "'plain' (one column). Add ',dense' for unequal column widths, "
  1498. "',nodense' for equal widths (default: column)"
  1499. ),
  1500. )
  1501. parser.add_argument(
  1502. "--width",
  1503. type=int,
  1504. help="Terminal width (default: auto-detect)",
  1505. )
  1506. parser.add_argument(
  1507. "--indent",
  1508. default="",
  1509. help="String to prepend to each line (default: empty)",
  1510. )
  1511. parser.add_argument(
  1512. "--nl",
  1513. default="\n",
  1514. help="String to append to each line, including newline (default: \\n)",
  1515. )
  1516. parser.add_argument(
  1517. "--padding",
  1518. type=int,
  1519. default=1,
  1520. help="Number of spaces between columns (default: 1)",
  1521. )
  1522. parsed_args = parser.parse_args(args)
  1523. # Read lines from stdin
  1524. lines = []
  1525. for line in sys.stdin:
  1526. # Strip the newline but keep the content
  1527. lines.append(line.rstrip("\n\r"))
  1528. # Format and output
  1529. result = format_columns(
  1530. lines,
  1531. width=parsed_args.width,
  1532. mode=parsed_args.mode,
  1533. padding=parsed_args.padding,
  1534. indent=parsed_args.indent,
  1535. nl=parsed_args.nl,
  1536. )
  1537. sys.stdout.write(result)
  1538. class cmd_init(Command):
  1539. """Create an empty Git repository or reinitialize an existing one."""
  1540. def run(self, args: Sequence[str]) -> None:
  1541. """Execute the init command.
  1542. Args:
  1543. args: Command line arguments
  1544. """
  1545. parser = argparse.ArgumentParser()
  1546. parser.add_argument(
  1547. "--bare", action="store_true", help="Create a bare repository"
  1548. )
  1549. parser.add_argument(
  1550. "path", nargs="?", default=os.getcwd(), help="Repository path"
  1551. )
  1552. parsed_args = parser.parse_args(args)
  1553. porcelain.init(parsed_args.path, bare=parsed_args.bare)
  1554. class cmd_clone(Command):
  1555. """Clone a repository into a new directory."""
  1556. def run(self, args: Sequence[str]) -> None:
  1557. """Execute the clone command.
  1558. Args:
  1559. args: Command line arguments
  1560. """
  1561. parser = argparse.ArgumentParser()
  1562. parser.add_argument(
  1563. "--bare",
  1564. help="Whether to create a bare repository.",
  1565. action="store_true",
  1566. )
  1567. parser.add_argument("--depth", type=int, help="Depth at which to fetch")
  1568. parser.add_argument(
  1569. "-b",
  1570. "--branch",
  1571. type=str,
  1572. help="Check out branch instead of branch pointed to by remote HEAD",
  1573. )
  1574. parser.add_argument(
  1575. "--refspec",
  1576. type=str,
  1577. help="References to fetch",
  1578. action="append",
  1579. )
  1580. parser.add_argument(
  1581. "--filter",
  1582. dest="filter_spec",
  1583. type=str,
  1584. help="git-rev-list-style object filter",
  1585. )
  1586. parser.add_argument(
  1587. "--protocol",
  1588. type=int,
  1589. help="Git protocol version to use",
  1590. )
  1591. parser.add_argument(
  1592. "--recurse-submodules",
  1593. action="store_true",
  1594. help="Initialize and clone submodules",
  1595. )
  1596. parser.add_argument("source", help="Repository to clone from")
  1597. parser.add_argument("target", nargs="?", help="Directory to clone into")
  1598. parsed_args = parser.parse_args(args)
  1599. try:
  1600. porcelain.clone(
  1601. parsed_args.source,
  1602. parsed_args.target,
  1603. bare=parsed_args.bare,
  1604. depth=parsed_args.depth,
  1605. branch=parsed_args.branch,
  1606. refspec=parsed_args.refspec,
  1607. filter_spec=parsed_args.filter_spec,
  1608. protocol_version=parsed_args.protocol,
  1609. recurse_submodules=parsed_args.recurse_submodules,
  1610. )
  1611. except GitProtocolError as e:
  1612. logging.exception(e)
  1613. def _get_commit_message_with_template(
  1614. initial_message: bytes | None,
  1615. repo: Repo | None = None,
  1616. commit: Commit | None = None,
  1617. ) -> bytes:
  1618. """Get commit message with an initial message template."""
  1619. # Start with the initial message
  1620. template = initial_message or b""
  1621. if template and not template.endswith(b"\n"):
  1622. template += b"\n"
  1623. template += b"\n"
  1624. template += b"# Please enter the commit message for your changes. Lines starting\n"
  1625. template += b"# with '#' will be ignored, and an empty message aborts the commit.\n"
  1626. template += b"#\n"
  1627. # Add branch info if repo is provided
  1628. if repo:
  1629. try:
  1630. ref_names, _ref_sha = repo.refs.follow(HEADREF)
  1631. ref_path = ref_names[-1] # Get the final reference
  1632. if ref_path.startswith(b"refs/heads/"):
  1633. branch = ref_path[11:] # Remove 'refs/heads/' prefix
  1634. else:
  1635. branch = ref_path
  1636. template += b"# On branch %s\n" % branch
  1637. except (KeyError, IndexError):
  1638. template += b"# On branch (unknown)\n"
  1639. template += b"#\n"
  1640. template += b"# Changes to be committed:\n"
  1641. # Launch editor
  1642. content = launch_editor(template)
  1643. # Remove comment lines and strip
  1644. lines = content.split(b"\n")
  1645. message_lines = [line for line in lines if not line.strip().startswith(b"#")]
  1646. message = b"\n".join(message_lines).strip()
  1647. if not message:
  1648. raise CommitMessageError("Aborting commit due to empty commit message")
  1649. return message
  1650. class cmd_config(Command):
  1651. """Get and set repository or global options."""
  1652. def run(self, args: Sequence[str]) -> int | None:
  1653. """Execute the config command.
  1654. Args:
  1655. args: Command line arguments
  1656. """
  1657. parser = argparse.ArgumentParser()
  1658. parser.add_argument(
  1659. "--global",
  1660. dest="global_config",
  1661. action="store_true",
  1662. help="Use global config file",
  1663. )
  1664. parser.add_argument(
  1665. "--local",
  1666. action="store_true",
  1667. help="Use repository config file (default)",
  1668. )
  1669. parser.add_argument(
  1670. "-l",
  1671. "--list",
  1672. action="store_true",
  1673. help="List all variables",
  1674. )
  1675. parser.add_argument(
  1676. "--unset",
  1677. action="store_true",
  1678. help="Remove a variable",
  1679. )
  1680. parser.add_argument(
  1681. "--unset-all",
  1682. action="store_true",
  1683. help="Remove all matches for a variable",
  1684. )
  1685. parser.add_argument(
  1686. "--get-all",
  1687. action="store_true",
  1688. help="Get all values for a multivar",
  1689. )
  1690. parser.add_argument(
  1691. "key",
  1692. nargs="?",
  1693. help="Config key (e.g., user.name)",
  1694. )
  1695. parser.add_argument(
  1696. "value",
  1697. nargs="?",
  1698. help="Config value to set",
  1699. )
  1700. parsed_args = parser.parse_args(args)
  1701. # Determine which config file to use
  1702. if parsed_args.global_config:
  1703. # Use global config file
  1704. config_path = os.path.expanduser("~/.gitconfig")
  1705. try:
  1706. from .config import ConfigFile
  1707. config = ConfigFile.from_path(config_path)
  1708. except FileNotFoundError:
  1709. from .config import ConfigFile
  1710. config = ConfigFile()
  1711. config.path = config_path
  1712. else:
  1713. # Use local repository config (default)
  1714. try:
  1715. repo = Repo(".")
  1716. config = repo.get_config()
  1717. except NotGitRepository:
  1718. logger.error("error: not a git repository")
  1719. return 1
  1720. # Handle --list
  1721. if parsed_args.list:
  1722. for section in config.sections():
  1723. for key, value in config.items(section):
  1724. section_str = ".".join(
  1725. s.decode("utf-8") if isinstance(s, bytes) else s
  1726. for s in section
  1727. )
  1728. key_str = key.decode("utf-8") if isinstance(key, bytes) else key
  1729. value_str = (
  1730. value.decode("utf-8") if isinstance(value, bytes) else value
  1731. )
  1732. print(f"{section_str}.{key_str}={value_str}")
  1733. return 0
  1734. # Handle --unset or --unset-all
  1735. if parsed_args.unset or parsed_args.unset_all:
  1736. if not parsed_args.key:
  1737. logger.error("error: key is required for --unset")
  1738. return 1
  1739. # Parse the key (e.g., "user.name" or "remote.origin.url")
  1740. parts = parsed_args.key.split(".")
  1741. if len(parts) < 2:
  1742. logger.error("error: invalid key format")
  1743. return 1
  1744. if len(parts) == 2:
  1745. section = (parts[0],)
  1746. name = parts[1]
  1747. else:
  1748. # For keys like "remote.origin.url", section is ("remote", "origin")
  1749. section = tuple(parts[:-1])
  1750. name = parts[-1]
  1751. try:
  1752. # Check if the key exists first
  1753. try:
  1754. config.get(section, name)
  1755. except KeyError:
  1756. logger.error(f"error: key '{parsed_args.key}' not found")
  1757. return 1
  1758. # Delete the configuration key using ConfigDict's delete method
  1759. section_bytes = tuple(
  1760. s.encode("utf-8") if isinstance(s, str) else s for s in section
  1761. )
  1762. name_bytes = name.encode("utf-8") if isinstance(name, str) else name
  1763. section_dict = config._values.get(section_bytes)
  1764. if section_dict:
  1765. del section_dict[name_bytes]
  1766. config.write_to_path()
  1767. else:
  1768. logger.error(f"error: key '{parsed_args.key}' not found")
  1769. return 1
  1770. except Exception as e:
  1771. logger.error(f"error: {e}")
  1772. return 1
  1773. return 0
  1774. # Handle --get-all
  1775. if parsed_args.get_all:
  1776. if not parsed_args.key:
  1777. logger.error("error: key is required for --get-all")
  1778. return 1
  1779. parts = parsed_args.key.split(".")
  1780. if len(parts) < 2:
  1781. logger.error("error: invalid key format")
  1782. return 1
  1783. if len(parts) == 2:
  1784. section = (parts[0],)
  1785. name = parts[1]
  1786. else:
  1787. section = tuple(parts[:-1])
  1788. name = parts[-1]
  1789. try:
  1790. for value in config.get_multivar(section, name):
  1791. value_str = (
  1792. value.decode("utf-8") if isinstance(value, bytes) else value
  1793. )
  1794. print(value_str)
  1795. return 0
  1796. except KeyError:
  1797. return 1
  1798. # Handle get (no value provided)
  1799. if parsed_args.key and not parsed_args.value:
  1800. parts = parsed_args.key.split(".")
  1801. if len(parts) < 2:
  1802. logger.error("error: invalid key format")
  1803. return 1
  1804. if len(parts) == 2:
  1805. section = (parts[0],)
  1806. name = parts[1]
  1807. else:
  1808. # For keys like "remote.origin.url", section is ("remote", "origin")
  1809. section = tuple(parts[:-1])
  1810. name = parts[-1]
  1811. try:
  1812. value = config.get(section, name)
  1813. value_str = value.decode("utf-8") if isinstance(value, bytes) else value
  1814. print(value_str)
  1815. return 0
  1816. except KeyError:
  1817. return 1
  1818. # Handle set (key and value provided)
  1819. if parsed_args.key and parsed_args.value:
  1820. parts = parsed_args.key.split(".")
  1821. if len(parts) < 2:
  1822. logger.error("error: invalid key format")
  1823. return 1
  1824. if len(parts) == 2:
  1825. section = (parts[0],)
  1826. name = parts[1]
  1827. else:
  1828. # For keys like "remote.origin.url", section is ("remote", "origin")
  1829. section = tuple(parts[:-1])
  1830. name = parts[-1]
  1831. config.set(section, name, parsed_args.value)
  1832. if parsed_args.global_config:
  1833. config.write_to_path()
  1834. else:
  1835. config.write_to_path()
  1836. return 0
  1837. # No action specified
  1838. parser.print_help()
  1839. return 1
  1840. class cmd_commit(Command):
  1841. """Record changes to the repository."""
  1842. def run(self, args: Sequence[str]) -> int | None:
  1843. """Execute the commit command.
  1844. Args:
  1845. args: Command line arguments
  1846. """
  1847. parser = argparse.ArgumentParser()
  1848. parser.add_argument("--message", "-m", help="Commit message")
  1849. parser.add_argument(
  1850. "-a",
  1851. "--all",
  1852. action="store_true",
  1853. help="Automatically stage all tracked files that have been modified",
  1854. )
  1855. parser.add_argument(
  1856. "--amend",
  1857. action="store_true",
  1858. help="Replace the tip of the current branch by creating a new commit",
  1859. )
  1860. parsed_args = parser.parse_args(args)
  1861. message: bytes | str | Callable[[Repo | None, Commit | None], bytes]
  1862. if parsed_args.message:
  1863. message = parsed_args.message
  1864. elif parsed_args.amend:
  1865. # For amend, create a callable that opens editor with original message pre-populated
  1866. def get_amend_message(repo: Repo | None, commit: Commit | None) -> bytes:
  1867. # Get the original commit message from current HEAD
  1868. assert repo is not None
  1869. try:
  1870. head_commit = repo[repo.head()]
  1871. assert isinstance(head_commit, Commit)
  1872. original_message = head_commit.message
  1873. except KeyError:
  1874. original_message = b""
  1875. # Open editor with original message
  1876. return _get_commit_message_with_template(original_message, repo, commit)
  1877. message = get_amend_message
  1878. else:
  1879. # For regular commits, use empty template
  1880. def get_regular_message(repo: Repo | None, commit: Commit | None) -> bytes:
  1881. return _get_commit_message_with_template(b"", repo, commit)
  1882. message = get_regular_message
  1883. try:
  1884. porcelain.commit(
  1885. ".", message=message, all=parsed_args.all, amend=parsed_args.amend
  1886. )
  1887. except CommitMessageError as e:
  1888. logging.exception(e)
  1889. return 1
  1890. return None
  1891. class cmd_commit_tree(Command):
  1892. """Create a new commit object from a tree."""
  1893. def run(self, args: Sequence[str]) -> None:
  1894. """Execute the commit-tree command.
  1895. Args:
  1896. args: Command line arguments
  1897. """
  1898. parser = argparse.ArgumentParser()
  1899. parser.add_argument("--message", "-m", required=True, help="Commit message")
  1900. parser.add_argument("tree", help="Tree SHA to commit")
  1901. parsed_args = parser.parse_args(args)
  1902. porcelain.commit_tree(".", tree=parsed_args.tree, message=parsed_args.message)
  1903. class cmd_update_server_info(Command):
  1904. """Update auxiliary info file to help dumb servers."""
  1905. def run(self, args: Sequence[str]) -> None:
  1906. """Execute the update-server-info command.
  1907. Args:
  1908. args: Command line arguments
  1909. """
  1910. porcelain.update_server_info(".")
  1911. class cmd_symbolic_ref(Command):
  1912. """Read, modify and delete symbolic refs."""
  1913. def run(self, args: Sequence[str]) -> int | None:
  1914. """Execute the symbolic-ref command.
  1915. Args:
  1916. args: Command line arguments
  1917. """
  1918. parser = argparse.ArgumentParser()
  1919. parser.add_argument("name", help="Symbolic reference name")
  1920. parser.add_argument("ref", nargs="?", help="Target reference")
  1921. parser.add_argument("--force", action="store_true", help="Force update")
  1922. parsed_args = parser.parse_args(args)
  1923. # If ref is provided, we're setting; otherwise we're reading
  1924. if parsed_args.ref:
  1925. # Set symbolic reference
  1926. from .repo import Repo
  1927. with Repo(".") as repo:
  1928. repo.refs.set_symbolic_ref(
  1929. parsed_args.name.encode(), parsed_args.ref.encode()
  1930. )
  1931. return 0
  1932. else:
  1933. # Read symbolic reference
  1934. from .repo import Repo
  1935. with Repo(".") as repo:
  1936. try:
  1937. target = repo.refs.read_ref(parsed_args.name.encode())
  1938. if target is None:
  1939. logger.error(
  1940. "fatal: ref '%s' is not a symbolic ref", parsed_args.name
  1941. )
  1942. return 1
  1943. elif target.startswith(b"ref: "):
  1944. logger.info(target[5:].decode())
  1945. else:
  1946. logger.info(target.decode())
  1947. return 0
  1948. except KeyError:
  1949. logger.error(
  1950. "fatal: ref '%s' is not a symbolic ref", parsed_args.name
  1951. )
  1952. return 1
  1953. class cmd_pack_refs(Command):
  1954. """Pack heads and tags for efficient repository access."""
  1955. def run(self, argv: Sequence[str]) -> None:
  1956. """Execute the pack-refs command.
  1957. Args:
  1958. argv: Command line arguments
  1959. """
  1960. parser = argparse.ArgumentParser()
  1961. parser.add_argument("--all", action="store_true")
  1962. # ignored, we never prune
  1963. parser.add_argument("--no-prune", action="store_true")
  1964. args = parser.parse_args(argv)
  1965. porcelain.pack_refs(".", all=args.all)
  1966. class cmd_var(Command):
  1967. """Display Git logical variables."""
  1968. def run(self, argv: Sequence[str]) -> int | None:
  1969. """Execute the var command.
  1970. Args:
  1971. argv: Command line arguments
  1972. """
  1973. parser = argparse.ArgumentParser()
  1974. parser.add_argument(
  1975. "variable",
  1976. nargs="?",
  1977. help="Variable to query (e.g., GIT_AUTHOR_IDENT)",
  1978. )
  1979. parser.add_argument(
  1980. "-l",
  1981. "--list",
  1982. action="store_true",
  1983. help="List all variables",
  1984. )
  1985. args = parser.parse_args(argv)
  1986. if args.list:
  1987. # List all variables
  1988. variables = porcelain.var_list(".")
  1989. for key, value in sorted(variables.items()):
  1990. print(f"{key}={value}")
  1991. return 0
  1992. elif args.variable:
  1993. # Query specific variable
  1994. try:
  1995. value = porcelain.var(".", variable=args.variable)
  1996. print(value)
  1997. return 0
  1998. except KeyError:
  1999. logger.error("error: variable '%s' has no value", args.variable)
  2000. return 1
  2001. else:
  2002. # No arguments - print error
  2003. logger.error("error: variable or -l is required")
  2004. parser.print_help()
  2005. return 1
  2006. class cmd_show(Command):
  2007. """Show various types of objects."""
  2008. def run(self, argv: Sequence[str]) -> None:
  2009. """Execute the show command.
  2010. Args:
  2011. argv: Command line arguments
  2012. """
  2013. parser = argparse.ArgumentParser()
  2014. parser.add_argument("objectish", type=str, nargs="*")
  2015. parser.add_argument(
  2016. "--color",
  2017. choices=["always", "never", "auto"],
  2018. default="auto",
  2019. help="Use colored output (requires rich)",
  2020. )
  2021. args = parser.parse_args(argv)
  2022. # Determine if we should use color
  2023. def _should_use_color() -> bool:
  2024. if args.color == "always":
  2025. return True
  2026. elif args.color == "never":
  2027. return False
  2028. else: # auto
  2029. return sys.stdout.isatty()
  2030. def _create_output_stream(outstream: TextIO) -> TextIO:
  2031. """Create output stream, optionally with colorization."""
  2032. if not _should_use_color():
  2033. return outstream
  2034. from .diff import ColorizedDiffStream
  2035. if not ColorizedDiffStream.is_available():
  2036. if args.color == "always":
  2037. raise ImportError(
  2038. "Rich is required for colored output. Install with: pip install 'dulwich[colordiff]'"
  2039. )
  2040. else:
  2041. logging.warning(
  2042. "Rich not available, disabling colored output. Install with: pip install 'dulwich[colordiff]'"
  2043. )
  2044. return outstream
  2045. # Wrap the ColorizedDiffStream (BinaryIO) back to TextIO
  2046. import io
  2047. colorized = ColorizedDiffStream(outstream.buffer)
  2048. return io.TextIOWrapper(colorized, encoding="utf-8", line_buffering=True)
  2049. with Repo(".") as repo:
  2050. config = repo.get_config_stack()
  2051. with get_pager(config=config, cmd_name="show") as outstream:
  2052. output_stream = _create_output_stream(outstream)
  2053. porcelain.show(repo, args.objectish or None, outstream=output_stream)
  2054. class cmd_show_ref(Command):
  2055. """List references in a local repository."""
  2056. def run(self, args: Sequence[str]) -> int | None:
  2057. """Execute the show-ref command.
  2058. Args:
  2059. args: Command line arguments
  2060. Returns:
  2061. Exit code (0 for success, 1 for error/no matches, 2 for missing ref with --exists)
  2062. """
  2063. parser = argparse.ArgumentParser()
  2064. parser.add_argument(
  2065. "--head",
  2066. action="store_true",
  2067. help="Show the HEAD reference",
  2068. )
  2069. parser.add_argument(
  2070. "--branches",
  2071. action="store_true",
  2072. help="Limit to local branches",
  2073. )
  2074. parser.add_argument(
  2075. "--tags",
  2076. action="store_true",
  2077. help="Limit to local tags",
  2078. )
  2079. parser.add_argument(
  2080. "-d",
  2081. "--dereference",
  2082. action="store_true",
  2083. help="Dereference tags into object IDs",
  2084. )
  2085. parser.add_argument(
  2086. "-s",
  2087. "--hash",
  2088. nargs="?",
  2089. const=40,
  2090. type=int,
  2091. metavar="n",
  2092. help="Only show the OID, not the reference name",
  2093. )
  2094. parser.add_argument(
  2095. "--abbrev",
  2096. nargs="?",
  2097. const=7,
  2098. type=int,
  2099. metavar="n",
  2100. help="Abbreviate the object name",
  2101. )
  2102. parser.add_argument(
  2103. "--verify",
  2104. action="store_true",
  2105. help="Enable stricter reference checking (exact path match)",
  2106. )
  2107. parser.add_argument(
  2108. "--exists",
  2109. action="store_true",
  2110. help="Check whether the given reference exists",
  2111. )
  2112. parser.add_argument(
  2113. "-q",
  2114. "--quiet",
  2115. action="store_true",
  2116. help="Do not print any results to stdout",
  2117. )
  2118. parser.add_argument(
  2119. "patterns",
  2120. nargs="*",
  2121. help="Show references matching patterns",
  2122. )
  2123. parsed_args = parser.parse_args(args)
  2124. # Handle --exists mode
  2125. if parsed_args.exists:
  2126. if not parsed_args.patterns or len(parsed_args.patterns) != 1:
  2127. logger.error("--exists requires exactly one reference argument")
  2128. return 1
  2129. try:
  2130. with Repo(".") as repo:
  2131. repo_refs = repo.get_refs()
  2132. pattern_bytes = os.fsencode(parsed_args.patterns[0])
  2133. if pattern_bytes in repo_refs:
  2134. return 0 # Reference exists
  2135. else:
  2136. return 2 # Reference missing
  2137. except (NotGitRepository, OSError, FileFormatException) as e:
  2138. logger.error(f"Error looking up reference: {e}")
  2139. return 1 # Error looking up reference
  2140. # Regular show-ref mode
  2141. try:
  2142. matched_refs = porcelain.show_ref(
  2143. ".",
  2144. patterns=parsed_args.patterns if parsed_args.patterns else None,
  2145. head=parsed_args.head,
  2146. branches=parsed_args.branches,
  2147. tags=parsed_args.tags,
  2148. dereference=parsed_args.dereference,
  2149. verify=parsed_args.verify,
  2150. )
  2151. except (NotGitRepository, OSError, FileFormatException) as e:
  2152. logger.error(f"Error: {e}")
  2153. return 1
  2154. # Return error if no matches found (unless quiet)
  2155. if not matched_refs:
  2156. if parsed_args.verify and not parsed_args.quiet:
  2157. logger.error("error: no matching refs found")
  2158. return 1
  2159. # Output results
  2160. if not parsed_args.quiet:
  2161. abbrev_len = parsed_args.abbrev if parsed_args.abbrev else 40
  2162. hash_only = parsed_args.hash is not None
  2163. if hash_only and parsed_args.hash:
  2164. abbrev_len = parsed_args.hash
  2165. for sha, ref in matched_refs:
  2166. sha_str = sha.decode()
  2167. if abbrev_len < 40:
  2168. sha_str = sha_str[:abbrev_len]
  2169. if hash_only:
  2170. logger.info(sha_str)
  2171. else:
  2172. logger.info(f"{sha_str} {ref.decode()}")
  2173. return 0
  2174. class cmd_show_branch(Command):
  2175. """Show branches and their commits."""
  2176. def run(self, args: Sequence[str]) -> int | None:
  2177. """Execute the show-branch command.
  2178. Args:
  2179. args: Command line arguments
  2180. Returns:
  2181. Exit code (0 for success, 1 for error)
  2182. """
  2183. parser = argparse.ArgumentParser()
  2184. parser.add_argument(
  2185. "-r",
  2186. "--remotes",
  2187. action="store_true",
  2188. help="Show remote-tracking branches",
  2189. )
  2190. parser.add_argument(
  2191. "-a",
  2192. "--all",
  2193. dest="all_branches",
  2194. action="store_true",
  2195. help="Show both remote-tracking and local branches",
  2196. )
  2197. parser.add_argument(
  2198. "--current",
  2199. action="store_true",
  2200. help="Include current branch if not given on command line",
  2201. )
  2202. parser.add_argument(
  2203. "--topo-order",
  2204. dest="topo_order",
  2205. action="store_true",
  2206. help="Show commits in topological order",
  2207. )
  2208. parser.add_argument(
  2209. "--date-order",
  2210. action="store_true",
  2211. help="Show commits in date order (default)",
  2212. )
  2213. parser.add_argument(
  2214. "--more",
  2215. type=int,
  2216. metavar="n",
  2217. help="Show n more commits beyond common ancestor",
  2218. )
  2219. parser.add_argument(
  2220. "--list",
  2221. dest="list_branches",
  2222. action="store_true",
  2223. help="Show only branch names and their tip commits",
  2224. )
  2225. parser.add_argument(
  2226. "--independent",
  2227. dest="independent_branches",
  2228. action="store_true",
  2229. help="Show only branches not reachable from any other",
  2230. )
  2231. parser.add_argument(
  2232. "--merge-base",
  2233. dest="merge_base",
  2234. action="store_true",
  2235. help="Show merge base of specified branches",
  2236. )
  2237. parser.add_argument(
  2238. "branches",
  2239. nargs="*",
  2240. help="Branches to show (default: all local branches)",
  2241. )
  2242. parsed_args = parser.parse_args(args)
  2243. try:
  2244. output_lines = porcelain.show_branch(
  2245. ".",
  2246. branches=parsed_args.branches if parsed_args.branches else None,
  2247. all_branches=parsed_args.all_branches,
  2248. remotes=parsed_args.remotes,
  2249. current=parsed_args.current,
  2250. topo_order=parsed_args.topo_order,
  2251. more=parsed_args.more,
  2252. list_branches=parsed_args.list_branches,
  2253. independent_branches=parsed_args.independent_branches,
  2254. merge_base=parsed_args.merge_base,
  2255. )
  2256. except (NotGitRepository, OSError, FileFormatException) as e:
  2257. logger.error(f"Error: {e}")
  2258. return 1
  2259. # Output results
  2260. for line in output_lines:
  2261. logger.info(line)
  2262. return 0
  2263. class cmd_diff_tree(Command):
  2264. """Compare the content and mode of trees."""
  2265. def run(self, args: Sequence[str]) -> None:
  2266. """Execute the diff-tree command.
  2267. Args:
  2268. args: Command line arguments
  2269. """
  2270. parser = argparse.ArgumentParser()
  2271. parser.add_argument("old_tree", help="Old tree SHA")
  2272. parser.add_argument("new_tree", help="New tree SHA")
  2273. parsed_args = parser.parse_args(args)
  2274. porcelain.diff_tree(".", parsed_args.old_tree, parsed_args.new_tree)
  2275. class cmd_rev_list(Command):
  2276. """List commit objects in reverse chronological order."""
  2277. def run(self, args: Sequence[str]) -> None:
  2278. """Execute the rev-list command.
  2279. Args:
  2280. args: Command line arguments
  2281. """
  2282. parser = argparse.ArgumentParser()
  2283. parser.add_argument("commits", nargs="+", help="Commit IDs to list")
  2284. parsed_args = parser.parse_args(args)
  2285. porcelain.rev_list(".", parsed_args.commits)
  2286. class cmd_tag(Command):
  2287. """Create, list, delete or verify a tag object."""
  2288. def run(self, args: Sequence[str]) -> None:
  2289. """Execute the tag command.
  2290. Args:
  2291. args: Command line arguments
  2292. """
  2293. parser = argparse.ArgumentParser()
  2294. parser.add_argument(
  2295. "-a",
  2296. "--annotated",
  2297. help="Create an annotated tag.",
  2298. action="store_true",
  2299. )
  2300. parser.add_argument(
  2301. "-s", "--sign", help="Sign the annotated tag.", action="store_true"
  2302. )
  2303. parser.add_argument("tag_name", help="Name of the tag to create")
  2304. parsed_args = parser.parse_args(args)
  2305. porcelain.tag_create(
  2306. ".",
  2307. parsed_args.tag_name,
  2308. annotated=parsed_args.annotated,
  2309. sign=parsed_args.sign,
  2310. )
  2311. class cmd_verify_commit(Command):
  2312. """Check the GPG signature of commits."""
  2313. def run(self, args: Sequence[str]) -> int | None:
  2314. """Execute the verify-commit command.
  2315. Args:
  2316. args: Command line arguments
  2317. Returns:
  2318. Exit code (1 on error, None on success)
  2319. """
  2320. parser = argparse.ArgumentParser()
  2321. parser.add_argument(
  2322. "-v",
  2323. "--verbose",
  2324. help="Print the contents of the commit object before validating it.",
  2325. action="store_true",
  2326. )
  2327. parser.add_argument(
  2328. "--raw",
  2329. help="Print the raw gpg status output to standard error.",
  2330. action="store_true",
  2331. )
  2332. parser.add_argument(
  2333. "commits",
  2334. nargs="*",
  2335. default=["HEAD"],
  2336. help="Commits to verify (defaults to HEAD)",
  2337. )
  2338. parsed_args = parser.parse_args(args)
  2339. exit_code = None
  2340. for commit in parsed_args.commits:
  2341. try:
  2342. if parsed_args.verbose:
  2343. # Show commit contents before verification
  2344. porcelain.show(
  2345. ".",
  2346. objects=[commit],
  2347. outstream=sys.stdout,
  2348. )
  2349. porcelain.verify_commit(".", commit)
  2350. if not parsed_args.raw:
  2351. print(f"gpg: Good signature from commit '{commit}'")
  2352. except Exception as e:
  2353. if not parsed_args.raw:
  2354. print(f"error: {commit}: {e}", file=sys.stderr)
  2355. else:
  2356. # In raw mode, let the exception propagate
  2357. raise
  2358. exit_code = 1
  2359. return exit_code
  2360. class cmd_verify_tag(Command):
  2361. """Check the GPG signature of tags."""
  2362. def run(self, args: Sequence[str]) -> int | None:
  2363. """Execute the verify-tag command.
  2364. Args:
  2365. args: Command line arguments
  2366. Returns:
  2367. Exit code (1 on error, None on success)
  2368. """
  2369. parser = argparse.ArgumentParser()
  2370. parser.add_argument(
  2371. "-v",
  2372. "--verbose",
  2373. help="Print the contents of the tag object before validating it.",
  2374. action="store_true",
  2375. )
  2376. parser.add_argument(
  2377. "--raw",
  2378. help="Print the raw gpg status output to standard error.",
  2379. action="store_true",
  2380. )
  2381. parser.add_argument("tags", nargs="+", help="Tags to verify")
  2382. parsed_args = parser.parse_args(args)
  2383. exit_code = None
  2384. for tag in parsed_args.tags:
  2385. try:
  2386. if parsed_args.verbose:
  2387. # Show tag contents before verification
  2388. porcelain.show(
  2389. ".",
  2390. objects=[tag],
  2391. outstream=sys.stdout,
  2392. )
  2393. porcelain.verify_tag(".", tag)
  2394. if not parsed_args.raw:
  2395. print(f"gpg: Good signature from tag '{tag}'")
  2396. except Exception as e:
  2397. if not parsed_args.raw:
  2398. print(f"error: {tag}: {e}", file=sys.stderr)
  2399. else:
  2400. # In raw mode, let the exception propagate
  2401. raise
  2402. exit_code = 1
  2403. return exit_code
  2404. class cmd_repack(Command):
  2405. """Pack unpacked objects in a repository."""
  2406. def run(self, args: Sequence[str]) -> None:
  2407. """Execute the repack command.
  2408. Args:
  2409. args: Command line arguments
  2410. """
  2411. parser = argparse.ArgumentParser()
  2412. parser.add_argument(
  2413. "--write-bitmap-index",
  2414. action="store_true",
  2415. help="write a bitmap index for packs",
  2416. )
  2417. parsed_args = parser.parse_args(args)
  2418. porcelain.repack(".", write_bitmaps=parsed_args.write_bitmap_index)
  2419. class cmd_reflog(Command):
  2420. """Manage reflog information."""
  2421. def run(self, args: Sequence[str]) -> None:
  2422. """Execute the reflog command.
  2423. Args:
  2424. args: Command line arguments
  2425. """
  2426. parser = argparse.ArgumentParser(prog="dulwich reflog")
  2427. subparsers = parser.add_subparsers(dest="subcommand", help="Subcommand")
  2428. # Show subcommand (default when no subcommand is specified)
  2429. show_parser = subparsers.add_parser(
  2430. "show", help="Show reflog entries (default)", add_help=False
  2431. )
  2432. show_parser.add_argument(
  2433. "ref", nargs="?", default="HEAD", help="Reference to show reflog for"
  2434. )
  2435. show_parser.add_argument(
  2436. "--all", action="store_true", help="Show reflogs for all refs"
  2437. )
  2438. # Expire subcommand
  2439. expire_parser = subparsers.add_parser("expire", help="Expire reflog entries")
  2440. expire_parser.add_argument(
  2441. "ref", nargs="?", help="Reference to expire reflog for"
  2442. )
  2443. expire_parser.add_argument(
  2444. "--all", action="store_true", help="Expire reflogs for all refs"
  2445. )
  2446. expire_parser.add_argument(
  2447. "--expire",
  2448. type=str,
  2449. help="Expire entries older than time (e.g., '90 days ago', 'all', 'never')",
  2450. )
  2451. expire_parser.add_argument(
  2452. "--expire-unreachable",
  2453. type=str,
  2454. help="Expire unreachable entries older than time",
  2455. )
  2456. expire_parser.add_argument(
  2457. "--dry-run", "-n", action="store_true", help="Show what would be expired"
  2458. )
  2459. # Delete subcommand
  2460. delete_parser = subparsers.add_parser(
  2461. "delete", help="Delete specific reflog entry"
  2462. )
  2463. delete_parser.add_argument(
  2464. "refspec", help="Reference specification (e.g., HEAD@{1})"
  2465. )
  2466. delete_parser.add_argument(
  2467. "--rewrite",
  2468. action="store_true",
  2469. help="Rewrite subsequent entries to maintain consistency",
  2470. )
  2471. # If no arguments or first arg is not a subcommand, treat as show
  2472. if not args or (args[0] not in ["show", "expire", "delete"]):
  2473. # Parse as show command
  2474. parsed_args = parser.parse_args(["show", *list(args)])
  2475. else:
  2476. parsed_args = parser.parse_args(args)
  2477. if parsed_args.subcommand == "expire":
  2478. self._run_expire(parsed_args)
  2479. elif parsed_args.subcommand == "delete":
  2480. self._run_delete(parsed_args)
  2481. else: # show or default
  2482. self._run_show(parsed_args)
  2483. def _run_show(self, parsed_args: argparse.Namespace) -> None:
  2484. """Show reflog entries."""
  2485. with Repo(".") as repo:
  2486. config = repo.get_config_stack()
  2487. with get_pager(config=config, cmd_name="reflog") as outstream:
  2488. if parsed_args.all:
  2489. # Show reflogs for all refs
  2490. for ref_bytes, entry in porcelain.reflog(repo, all=True):
  2491. ref_str = ref_bytes.decode("utf-8", "replace")
  2492. short_new = entry.new_sha[:8].decode("ascii")
  2493. outstream.write(
  2494. f"{short_new} {ref_str}: {entry.message.decode('utf-8', 'replace')}\n"
  2495. )
  2496. else:
  2497. ref = (
  2498. parsed_args.ref.encode("utf-8")
  2499. if isinstance(parsed_args.ref, str)
  2500. else parsed_args.ref
  2501. )
  2502. for i, entry in enumerate(porcelain.reflog(repo, ref)):
  2503. # Format similar to git reflog
  2504. from dulwich.reflog import Entry
  2505. assert isinstance(entry, Entry)
  2506. short_new = entry.new_sha[:8].decode("ascii")
  2507. message = (
  2508. entry.message.decode("utf-8", "replace")
  2509. if entry.message
  2510. else ""
  2511. )
  2512. outstream.write(
  2513. f"{short_new} {ref.decode('utf-8', 'replace')}@{{{i}}}: {message}\n"
  2514. )
  2515. def _run_expire(self, parsed_args: argparse.Namespace) -> None:
  2516. """Expire reflog entries."""
  2517. # Parse time specifications
  2518. expire_time = None
  2519. expire_unreachable_time = None
  2520. if parsed_args.expire:
  2521. expire_time = parse_time_to_timestamp(parsed_args.expire)
  2522. if parsed_args.expire_unreachable:
  2523. expire_unreachable_time = parse_time_to_timestamp(
  2524. parsed_args.expire_unreachable
  2525. )
  2526. # Execute expire
  2527. result = porcelain.reflog_expire(
  2528. repo=".",
  2529. ref=parsed_args.ref,
  2530. all=parsed_args.all,
  2531. expire_time=expire_time,
  2532. expire_unreachable_time=expire_unreachable_time,
  2533. dry_run=parsed_args.dry_run,
  2534. )
  2535. # Print results
  2536. for ref_name, count in result.items():
  2537. ref_str = ref_name.decode("utf-8", "replace")
  2538. if parsed_args.dry_run:
  2539. print(f"Would expire {count} entries from {ref_str}")
  2540. else:
  2541. print(f"Expired {count} entries from {ref_str}")
  2542. def _run_delete(self, parsed_args: argparse.Namespace) -> None:
  2543. """Delete a specific reflog entry."""
  2544. from dulwich.reflog import parse_reflog_spec
  2545. # Parse refspec (e.g., "HEAD@{1}" or "refs/heads/master@{2}")
  2546. ref, index = parse_reflog_spec(parsed_args.refspec)
  2547. # Execute delete
  2548. porcelain.reflog_delete(
  2549. repo=".",
  2550. ref=ref,
  2551. index=index,
  2552. rewrite=parsed_args.rewrite,
  2553. )
  2554. print(f"Deleted entry {ref.decode('utf-8', 'replace')}@{{{index}}}")
  2555. class cmd_reset(Command):
  2556. """Reset current HEAD to the specified state."""
  2557. def run(self, args: Sequence[str]) -> None:
  2558. """Execute the reset command.
  2559. Args:
  2560. args: Command line arguments
  2561. """
  2562. parser = argparse.ArgumentParser()
  2563. mode_group = parser.add_mutually_exclusive_group()
  2564. mode_group.add_argument(
  2565. "--hard", action="store_true", help="Reset working tree and index"
  2566. )
  2567. mode_group.add_argument("--soft", action="store_true", help="Reset only HEAD")
  2568. mode_group.add_argument(
  2569. "--mixed", action="store_true", help="Reset HEAD and index"
  2570. )
  2571. parser.add_argument("treeish", nargs="?", help="Commit/tree to reset to")
  2572. parsed_args = parser.parse_args(args)
  2573. if parsed_args.hard:
  2574. mode = "hard"
  2575. elif parsed_args.soft:
  2576. mode = "soft"
  2577. elif parsed_args.mixed:
  2578. mode = "mixed"
  2579. else:
  2580. # Default to mixed behavior
  2581. mode = "mixed"
  2582. # Use the porcelain.reset function for all modes
  2583. porcelain.reset(".", mode=mode, treeish=parsed_args.treeish)
  2584. class cmd_revert(Command):
  2585. """Revert some existing commits."""
  2586. def run(self, args: Sequence[str]) -> None:
  2587. """Execute the revert command.
  2588. Args:
  2589. args: Command line arguments
  2590. """
  2591. parser = argparse.ArgumentParser()
  2592. parser.add_argument(
  2593. "--no-commit",
  2594. "-n",
  2595. action="store_true",
  2596. help="Apply changes but don't create a commit",
  2597. )
  2598. parser.add_argument("-m", "--message", help="Custom commit message")
  2599. parser.add_argument("commits", nargs="+", help="Commits to revert")
  2600. parsed_args = parser.parse_args(args)
  2601. result = porcelain.revert(
  2602. ".",
  2603. commits=parsed_args.commits,
  2604. no_commit=parsed_args.no_commit,
  2605. message=parsed_args.message,
  2606. )
  2607. if result and not parsed_args.no_commit:
  2608. logger.info("[%s] Revert completed", result.decode("ascii")[:7])
  2609. class cmd_daemon(Command):
  2610. """Run a simple Git protocol server."""
  2611. def run(self, args: Sequence[str]) -> None:
  2612. """Execute the daemon command.
  2613. Args:
  2614. args: Command line arguments
  2615. """
  2616. from dulwich import log_utils
  2617. from .protocol import TCP_GIT_PORT
  2618. parser = argparse.ArgumentParser()
  2619. parser.add_argument(
  2620. "-l",
  2621. "--listen_address",
  2622. default="localhost",
  2623. help="Binding IP address.",
  2624. )
  2625. parser.add_argument(
  2626. "-p",
  2627. "--port",
  2628. type=int,
  2629. default=TCP_GIT_PORT,
  2630. help="Binding TCP port.",
  2631. )
  2632. parser.add_argument(
  2633. "gitdir", nargs="?", default=".", help="Git directory to serve"
  2634. )
  2635. parsed_args = parser.parse_args(args)
  2636. log_utils.default_logging_config()
  2637. porcelain.daemon(
  2638. parsed_args.gitdir,
  2639. address=parsed_args.listen_address,
  2640. port=parsed_args.port,
  2641. )
  2642. class cmd_web_daemon(Command):
  2643. """Run a simple HTTP server for Git repositories."""
  2644. def run(self, args: Sequence[str]) -> None:
  2645. """Execute the web-daemon command.
  2646. Args:
  2647. args: Command line arguments
  2648. """
  2649. from dulwich import log_utils
  2650. parser = argparse.ArgumentParser()
  2651. parser.add_argument(
  2652. "-l",
  2653. "--listen_address",
  2654. default="",
  2655. help="Binding IP address.",
  2656. )
  2657. parser.add_argument(
  2658. "-p",
  2659. "--port",
  2660. type=int,
  2661. default=8000,
  2662. help="Binding TCP port.",
  2663. )
  2664. parser.add_argument(
  2665. "gitdir", nargs="?", default=".", help="Git directory to serve"
  2666. )
  2667. parsed_args = parser.parse_args(args)
  2668. log_utils.default_logging_config()
  2669. porcelain.web_daemon(
  2670. parsed_args.gitdir,
  2671. address=parsed_args.listen_address,
  2672. port=parsed_args.port,
  2673. )
  2674. class cmd_write_tree(Command):
  2675. """Create a tree object from the current index."""
  2676. def run(self, args: Sequence[str]) -> None:
  2677. """Execute the write-tree command.
  2678. Args:
  2679. args: Command line arguments
  2680. """
  2681. parser = argparse.ArgumentParser()
  2682. parser.parse_args(args)
  2683. sys.stdout.write("{}\n".format(porcelain.write_tree(".").decode()))
  2684. class cmd_receive_pack(Command):
  2685. """Receive what is pushed into the repository."""
  2686. def run(self, args: Sequence[str]) -> None:
  2687. """Execute the receive-pack command.
  2688. Args:
  2689. args: Command line arguments
  2690. """
  2691. parser = argparse.ArgumentParser()
  2692. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  2693. parsed_args = parser.parse_args(args)
  2694. porcelain.receive_pack(parsed_args.gitdir)
  2695. class cmd_upload_pack(Command):
  2696. """Send objects packed back to git-fetch-pack."""
  2697. def run(self, args: Sequence[str]) -> None:
  2698. """Execute the upload-pack command.
  2699. Args:
  2700. args: Command line arguments
  2701. """
  2702. parser = argparse.ArgumentParser()
  2703. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  2704. parsed_args = parser.parse_args(args)
  2705. porcelain.upload_pack(parsed_args.gitdir)
  2706. class cmd_shortlog(Command):
  2707. """Show a shortlog of commits by author."""
  2708. def run(self, args: Sequence[str]) -> None:
  2709. """Execute the shortlog command with the given CLI arguments.
  2710. Args:
  2711. args: List of command line arguments.
  2712. """
  2713. parser = argparse.ArgumentParser()
  2714. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  2715. parser.add_argument("--summary", action="store_true", help="Show summary only")
  2716. parser.add_argument(
  2717. "--sort", action="store_true", help="Sort authors by commit count"
  2718. )
  2719. parsed_args = parser.parse_args(args)
  2720. shortlog_items: list[dict[str, str]] = porcelain.shortlog(
  2721. repo=parsed_args.gitdir,
  2722. summary_only=parsed_args.summary,
  2723. sort_by_commits=parsed_args.sort,
  2724. )
  2725. for item in shortlog_items:
  2726. author: str = item["author"]
  2727. messages: str = item["messages"]
  2728. if parsed_args.summary:
  2729. count = len(messages.splitlines())
  2730. sys.stdout.write(f"{count}\t{author}\n")
  2731. else:
  2732. sys.stdout.write(f"{author} ({len(messages.splitlines())}):\n")
  2733. for msg in messages.splitlines():
  2734. sys.stdout.write(f" {msg}\n")
  2735. sys.stdout.write("\n")
  2736. class cmd_status(Command):
  2737. """Show the working tree status."""
  2738. def run(self, args: Sequence[str]) -> None:
  2739. """Execute the status command.
  2740. Args:
  2741. args: Command line arguments
  2742. """
  2743. parser = argparse.ArgumentParser()
  2744. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  2745. parser.add_argument(
  2746. "--column",
  2747. action="store_true",
  2748. help="Display untracked files in columns",
  2749. )
  2750. parsed_args = parser.parse_args(args)
  2751. status = porcelain.status(parsed_args.gitdir)
  2752. if any(names for (kind, names) in status.staged.items()):
  2753. sys.stdout.write("Changes to be committed:\n\n")
  2754. for kind, names in status.staged.items():
  2755. for name in names:
  2756. sys.stdout.write(
  2757. f"\t{kind}: {name.decode(sys.getfilesystemencoding())}\n"
  2758. )
  2759. sys.stdout.write("\n")
  2760. if status.unstaged:
  2761. sys.stdout.write("Changes not staged for commit:\n\n")
  2762. for name in status.unstaged:
  2763. sys.stdout.write(f"\t{name.decode(sys.getfilesystemencoding())}\n")
  2764. sys.stdout.write("\n")
  2765. if status.untracked:
  2766. sys.stdout.write("Untracked files:\n\n")
  2767. if parsed_args.column:
  2768. # Format untracked files in columns
  2769. untracked_names = [name for name in status.untracked]
  2770. output = format_columns(untracked_names, mode="column", indent="\t")
  2771. sys.stdout.write(output)
  2772. else:
  2773. for name in status.untracked:
  2774. sys.stdout.write(f"\t{name}\n")
  2775. sys.stdout.write("\n")
  2776. class cmd_ls_remote(Command):
  2777. """List references in a remote repository."""
  2778. def run(self, args: Sequence[str]) -> None:
  2779. """Execute the ls-remote command.
  2780. Args:
  2781. args: Command line arguments
  2782. """
  2783. parser = argparse.ArgumentParser()
  2784. parser.add_argument(
  2785. "--symref", action="store_true", help="Show symbolic references"
  2786. )
  2787. parser.add_argument("url", help="Remote URL to list references from")
  2788. parsed_args = parser.parse_args(args)
  2789. result = porcelain.ls_remote(parsed_args.url)
  2790. if parsed_args.symref:
  2791. # Show symrefs first, like git does
  2792. for ref, target in sorted(result.symrefs.items()):
  2793. if target:
  2794. sys.stdout.write(f"ref: {target.decode()}\t{ref.decode()}\n")
  2795. # Show regular refs
  2796. for ref in sorted(result.refs):
  2797. sha = result.refs[ref]
  2798. if sha is not None:
  2799. sys.stdout.write(f"{sha.decode()}\t{ref.decode()}\n")
  2800. class cmd_ls_tree(Command):
  2801. """List the contents of a tree object."""
  2802. def run(self, args: Sequence[str]) -> None:
  2803. """Execute the ls-tree command.
  2804. Args:
  2805. args: Command line arguments
  2806. """
  2807. parser = argparse.ArgumentParser()
  2808. parser.add_argument(
  2809. "-r",
  2810. "--recursive",
  2811. action="store_true",
  2812. help="Recursively list tree contents.",
  2813. )
  2814. parser.add_argument(
  2815. "--name-only", action="store_true", help="Only display name."
  2816. )
  2817. parser.add_argument("treeish", nargs="?", help="Tree-ish to list")
  2818. parsed_args = parser.parse_args(args)
  2819. with Repo(".") as repo:
  2820. config = repo.get_config_stack()
  2821. with get_pager(config=config, cmd_name="ls-tree") as outstream:
  2822. porcelain.ls_tree(
  2823. repo,
  2824. parsed_args.treeish,
  2825. outstream=outstream,
  2826. recursive=parsed_args.recursive,
  2827. name_only=parsed_args.name_only,
  2828. )
  2829. class cmd_pack_objects(Command):
  2830. """Create a packed archive of objects."""
  2831. def run(self, args: Sequence[str]) -> None:
  2832. """Execute the pack-objects command.
  2833. Args:
  2834. args: Command line arguments
  2835. """
  2836. parser = argparse.ArgumentParser()
  2837. parser.add_argument(
  2838. "--stdout", action="store_true", help="Write pack to stdout"
  2839. )
  2840. parser.add_argument("--deltify", action="store_true", help="Create deltas")
  2841. parser.add_argument(
  2842. "--no-reuse-deltas", action="store_true", help="Don't reuse existing deltas"
  2843. )
  2844. parser.add_argument("basename", nargs="?", help="Base name for pack files")
  2845. parsed_args = parser.parse_args(args)
  2846. if not parsed_args.stdout and not parsed_args.basename:
  2847. parser.error("basename required when not using --stdout")
  2848. object_ids = [ObjectID(line.strip().encode()) for line in sys.stdin.readlines()]
  2849. deltify = parsed_args.deltify
  2850. reuse_deltas = not parsed_args.no_reuse_deltas
  2851. if parsed_args.stdout:
  2852. packf = getattr(sys.stdout, "buffer", sys.stdout)
  2853. assert isinstance(packf, BinaryIO)
  2854. idxf = None
  2855. close = []
  2856. else:
  2857. packf = open(parsed_args.basename + ".pack", "wb")
  2858. idxf = open(parsed_args.basename + ".idx", "wb")
  2859. close = [packf, idxf]
  2860. porcelain.pack_objects(
  2861. ".", object_ids, packf, idxf, deltify=deltify, reuse_deltas=reuse_deltas
  2862. )
  2863. for f in close:
  2864. f.close()
  2865. class cmd_unpack_objects(Command):
  2866. """Unpack objects from a packed archive."""
  2867. def run(self, args: Sequence[str]) -> None:
  2868. """Execute the unpack-objects command.
  2869. Args:
  2870. args: Command line arguments
  2871. """
  2872. parser = argparse.ArgumentParser()
  2873. parser.add_argument("pack_file", help="Pack file to unpack")
  2874. parsed_args = parser.parse_args(args)
  2875. count = porcelain.unpack_objects(parsed_args.pack_file)
  2876. logger.info("Unpacked %d objects", count)
  2877. class cmd_prune(Command):
  2878. """Prune all unreachable objects from the object database."""
  2879. def run(self, args: Sequence[str]) -> int | None:
  2880. """Execute the prune command.
  2881. Args:
  2882. args: Command line arguments
  2883. """
  2884. import datetime
  2885. import time
  2886. from dulwich.object_store import DEFAULT_TEMPFILE_GRACE_PERIOD
  2887. parser = argparse.ArgumentParser(
  2888. description="Remove temporary pack files left behind by interrupted operations"
  2889. )
  2890. parser.add_argument(
  2891. "--expire",
  2892. nargs="?",
  2893. const="2.weeks.ago",
  2894. help="Only prune files older than the specified date (default: 2.weeks.ago)",
  2895. )
  2896. parser.add_argument(
  2897. "--dry-run",
  2898. "-n",
  2899. action="store_true",
  2900. help="Only report what would be removed",
  2901. )
  2902. parser.add_argument(
  2903. "--verbose",
  2904. "-v",
  2905. action="store_true",
  2906. help="Report all actions",
  2907. )
  2908. parsed_args = parser.parse_args(args)
  2909. # Parse expire grace period
  2910. grace_period = DEFAULT_TEMPFILE_GRACE_PERIOD
  2911. if parsed_args.expire:
  2912. from .approxidate import parse_relative_time
  2913. try:
  2914. grace_period = parse_relative_time(parsed_args.expire)
  2915. except ValueError:
  2916. # Try to parse as absolute date
  2917. try:
  2918. date = datetime.datetime.strptime(parsed_args.expire, "%Y-%m-%d")
  2919. grace_period = int(time.time() - date.timestamp())
  2920. except ValueError:
  2921. logger.error("Invalid expire date: %s", parsed_args.expire)
  2922. return 1
  2923. # Progress callback
  2924. def progress(msg: str) -> None:
  2925. if parsed_args.verbose:
  2926. logger.info("%s", msg)
  2927. try:
  2928. porcelain.prune(
  2929. ".",
  2930. grace_period=grace_period,
  2931. dry_run=parsed_args.dry_run,
  2932. progress=progress if parsed_args.verbose else None,
  2933. )
  2934. return None
  2935. except porcelain.Error as e:
  2936. logger.error("%s", e)
  2937. return 1
  2938. class cmd_pull(Command):
  2939. """Fetch from and integrate with another repository or a local branch."""
  2940. def run(self, args: Sequence[str]) -> None:
  2941. """Execute the pull command.
  2942. Args:
  2943. args: Command line arguments
  2944. """
  2945. parser = argparse.ArgumentParser()
  2946. parser.add_argument("from_location", type=str)
  2947. parser.add_argument("refspec", type=str, nargs="*")
  2948. parser.add_argument("--filter", type=str, nargs=1)
  2949. parser.add_argument("--protocol", type=int)
  2950. parsed_args = parser.parse_args(args)
  2951. porcelain.pull(
  2952. ".",
  2953. remote_location=parsed_args.from_location or None,
  2954. refspecs=parsed_args.refspec or None,
  2955. filter_spec=parsed_args.filter,
  2956. protocol_version=parsed_args.protocol or None,
  2957. )
  2958. class cmd_push(Command):
  2959. """Update remote refs along with associated objects."""
  2960. def run(self, argv: Sequence[str]) -> int | None:
  2961. """Execute the push command.
  2962. Args:
  2963. argv: Command line arguments
  2964. """
  2965. parser = argparse.ArgumentParser()
  2966. parser.add_argument("-f", "--force", action="store_true", help="Force")
  2967. parser.add_argument("to_location", type=str)
  2968. parser.add_argument("refspec", type=str, nargs="*")
  2969. args = parser.parse_args(argv)
  2970. try:
  2971. porcelain.push(
  2972. ".", args.to_location, args.refspec or None, force=args.force
  2973. )
  2974. except porcelain.DivergedBranches:
  2975. sys.stderr.write("Diverged branches; specify --force to override")
  2976. return 1
  2977. return None
  2978. class cmd_remote_add(Command):
  2979. """Add a remote repository."""
  2980. def run(self, args: Sequence[str]) -> None:
  2981. """Execute the remote-add command.
  2982. Args:
  2983. args: Command line arguments
  2984. """
  2985. parser = argparse.ArgumentParser()
  2986. parser.add_argument("name", help="Name of the remote")
  2987. parser.add_argument("url", help="URL of the remote")
  2988. parsed_args = parser.parse_args(args)
  2989. porcelain.remote_add(".", parsed_args.name, parsed_args.url)
  2990. class SuperCommand(Command):
  2991. """Base class for commands that have subcommands."""
  2992. subcommands: ClassVar[dict[str, type[Command]]] = {}
  2993. default_command: ClassVar[type[Command] | None] = None
  2994. def run(self, args: Sequence[str]) -> int | None:
  2995. """Execute the subcommand command.
  2996. Args:
  2997. args: Command line arguments
  2998. """
  2999. if not args:
  3000. if self.default_command:
  3001. return self.default_command().run(args)
  3002. else:
  3003. logger.info(
  3004. "Supported subcommands: %s", ", ".join(self.subcommands.keys())
  3005. )
  3006. return False
  3007. cmd = args[0]
  3008. try:
  3009. cmd_kls = self.subcommands[cmd]
  3010. except KeyError:
  3011. logger.error("No such subcommand: %s", args[0])
  3012. sys.exit(1)
  3013. return cmd_kls().run(args[1:])
  3014. class cmd_remote(SuperCommand):
  3015. """Manage set of tracked repositories."""
  3016. subcommands: ClassVar[dict[str, type[Command]]] = {
  3017. "add": cmd_remote_add,
  3018. }
  3019. class cmd_submodule_list(Command):
  3020. """List submodules."""
  3021. def run(self, argv: Sequence[str]) -> None:
  3022. """Execute the submodule-list command.
  3023. Args:
  3024. argv: Command line arguments
  3025. """
  3026. parser = argparse.ArgumentParser()
  3027. parser.parse_args(argv)
  3028. for path, sha in porcelain.submodule_list("."):
  3029. sys.stdout.write(f" {sha} {path}\n")
  3030. class cmd_submodule_init(Command):
  3031. """Initialize submodules."""
  3032. def run(self, argv: Sequence[str]) -> None:
  3033. """Execute the submodule-init command.
  3034. Args:
  3035. argv: Command line arguments
  3036. """
  3037. parser = argparse.ArgumentParser()
  3038. parser.parse_args(argv)
  3039. porcelain.submodule_init(".")
  3040. class cmd_submodule_add(Command):
  3041. """Add a submodule."""
  3042. def run(self, argv: Sequence[str]) -> None:
  3043. """Execute the submodule-add command.
  3044. Args:
  3045. argv: Command line arguments
  3046. """
  3047. parser = argparse.ArgumentParser()
  3048. parser.add_argument("url", help="URL of repository to add as submodule")
  3049. parser.add_argument("path", nargs="?", help="Path where submodule should live")
  3050. parser.add_argument("--name", help="Name for the submodule")
  3051. args = parser.parse_args(argv)
  3052. porcelain.submodule_add(".", args.url, args.path, args.name)
  3053. class cmd_submodule_update(Command):
  3054. """Update submodules."""
  3055. def run(self, argv: Sequence[str]) -> None:
  3056. """Execute the submodule-update command.
  3057. Args:
  3058. argv: Command line arguments
  3059. """
  3060. parser = argparse.ArgumentParser()
  3061. parser.add_argument(
  3062. "--init", action="store_true", help="Initialize submodules first"
  3063. )
  3064. parser.add_argument(
  3065. "--force",
  3066. action="store_true",
  3067. help="Force update even if local changes exist",
  3068. )
  3069. parser.add_argument(
  3070. "--recursive",
  3071. action="store_true",
  3072. help="Recursively update nested submodules",
  3073. )
  3074. parser.add_argument(
  3075. "paths", nargs="*", help="Specific submodule paths to update"
  3076. )
  3077. args = parser.parse_args(argv)
  3078. paths = args.paths if args.paths else None
  3079. porcelain.submodule_update(
  3080. ".", paths=paths, init=args.init, force=args.force, recursive=args.recursive
  3081. )
  3082. class cmd_submodule(SuperCommand):
  3083. """Initialize, update or inspect submodules."""
  3084. subcommands: ClassVar[dict[str, type[Command]]] = {
  3085. "add": cmd_submodule_add,
  3086. "init": cmd_submodule_init,
  3087. "list": cmd_submodule_list,
  3088. "update": cmd_submodule_update,
  3089. }
  3090. default_command = cmd_submodule_list
  3091. class cmd_check_ignore(Command):
  3092. """Check whether files are excluded by gitignore."""
  3093. def run(self, args: Sequence[str]) -> int:
  3094. """Execute the check-ignore command.
  3095. Args:
  3096. args: Command line arguments
  3097. """
  3098. parser = argparse.ArgumentParser()
  3099. parser.add_argument("paths", nargs="+", help="Paths to check")
  3100. parsed_args = parser.parse_args(args)
  3101. ret = 1
  3102. for path in porcelain.check_ignore(".", parsed_args.paths):
  3103. logger.info(path)
  3104. ret = 0
  3105. return ret
  3106. class cmd_check_mailmap(Command):
  3107. """Show canonical names and email addresses of contacts."""
  3108. def run(self, args: Sequence[str]) -> None:
  3109. """Execute the check-mailmap command.
  3110. Args:
  3111. args: Command line arguments
  3112. """
  3113. parser = argparse.ArgumentParser()
  3114. parser.add_argument("identities", nargs="+", help="Identities to check")
  3115. parsed_args = parser.parse_args(args)
  3116. for identity in parsed_args.identities:
  3117. canonical_identity = porcelain.check_mailmap(".", identity)
  3118. logger.info(canonical_identity)
  3119. class cmd_branch(Command):
  3120. """List, create, or delete branches."""
  3121. def run(self, args: Sequence[str]) -> int | None:
  3122. """Execute the branch command.
  3123. Args:
  3124. args: Command line arguments
  3125. """
  3126. parser = argparse.ArgumentParser()
  3127. parser.add_argument(
  3128. "branch",
  3129. type=str,
  3130. nargs="?",
  3131. help="Name of the branch",
  3132. )
  3133. parser.add_argument(
  3134. "-d",
  3135. "--delete",
  3136. action="store_true",
  3137. help="Delete branch",
  3138. )
  3139. parser.add_argument("--all", action="store_true", help="List all branches")
  3140. parser.add_argument(
  3141. "--merged", action="store_true", help="List merged into current branch"
  3142. )
  3143. parser.add_argument(
  3144. "--no-merged",
  3145. action="store_true",
  3146. help="List branches not merged into current branch",
  3147. )
  3148. parser.add_argument(
  3149. "--remotes", action="store_true", help="List remotes branches"
  3150. )
  3151. parser.add_argument(
  3152. "--contains",
  3153. nargs="?",
  3154. const="HEAD",
  3155. help="List branches that contain a specific commit",
  3156. )
  3157. parser.add_argument(
  3158. "--column", action="store_true", help="Display branch list in columns"
  3159. )
  3160. parser.add_argument(
  3161. "--list",
  3162. nargs="?",
  3163. const=None,
  3164. help="List branches matching a pattern",
  3165. )
  3166. parsed_args = parser.parse_args(args)
  3167. def print_branches(
  3168. branches: Iterator[bytes] | Sequence[bytes], use_columns: bool = False
  3169. ) -> None:
  3170. if use_columns:
  3171. branch_names = [branch.decode() for branch in branches]
  3172. output = format_columns(branch_names, mode="column")
  3173. sys.stdout.write(output)
  3174. else:
  3175. for branch in branches:
  3176. sys.stdout.write(f"{branch.decode()}\n")
  3177. branches: Iterator[bytes] | list[bytes] | None = None
  3178. try:
  3179. if parsed_args.all:
  3180. branches = porcelain.branch_list(".") + porcelain.branch_remotes_list(
  3181. "."
  3182. )
  3183. elif parsed_args.remotes:
  3184. branches = porcelain.branch_remotes_list(".")
  3185. elif parsed_args.merged:
  3186. branches = porcelain.merged_branches(".")
  3187. elif parsed_args.no_merged:
  3188. branches = porcelain.no_merged_branches(".")
  3189. elif parsed_args.contains:
  3190. try:
  3191. branches = list(
  3192. porcelain.branches_containing(".", commit=parsed_args.contains)
  3193. )
  3194. except KeyError as e:
  3195. sys.stderr.write(
  3196. f"error: object name {e.args[0].decode()} not found\n"
  3197. )
  3198. return 1
  3199. except porcelain.Error as e:
  3200. sys.stderr.write(f"{e}")
  3201. return 1
  3202. pattern = parsed_args.list
  3203. if pattern is not None and branches:
  3204. branches = porcelain.filter_branches_by_pattern(branches, pattern)
  3205. if branches is not None:
  3206. print_branches(branches, parsed_args.column)
  3207. return 0
  3208. if not parsed_args.branch:
  3209. logger.error("Usage: dulwich branch [-d] BRANCH_NAME")
  3210. return 1
  3211. if parsed_args.delete:
  3212. porcelain.branch_delete(".", name=parsed_args.branch)
  3213. else:
  3214. try:
  3215. porcelain.branch_create(".", name=parsed_args.branch)
  3216. except porcelain.Error as e:
  3217. sys.stderr.write(f"{e}")
  3218. return 1
  3219. return 0
  3220. class cmd_checkout(Command):
  3221. """Switch branches or restore working tree files."""
  3222. def run(self, args: Sequence[str]) -> int | None:
  3223. """Execute the checkout command.
  3224. Args:
  3225. args: Command line arguments
  3226. """
  3227. parser = argparse.ArgumentParser()
  3228. parser.add_argument(
  3229. "target",
  3230. type=str,
  3231. help="Name of the branch, tag, or commit to checkout",
  3232. )
  3233. parser.add_argument(
  3234. "-f",
  3235. "--force",
  3236. action="store_true",
  3237. help="Force checkout",
  3238. )
  3239. parser.add_argument(
  3240. "-b",
  3241. "--new-branch",
  3242. type=str,
  3243. help="Create a new branch at the target and switch to it",
  3244. )
  3245. parsed_args = parser.parse_args(args)
  3246. if not parsed_args.target:
  3247. logger.error("Usage: dulwich checkout TARGET [--force] [-b NEW_BRANCH]")
  3248. return 1
  3249. try:
  3250. porcelain.checkout(
  3251. ".",
  3252. target=parsed_args.target,
  3253. force=parsed_args.force,
  3254. new_branch=parsed_args.new_branch,
  3255. )
  3256. except porcelain.CheckoutError as e:
  3257. sys.stderr.write(f"{e}\n")
  3258. return 1
  3259. return 0
  3260. class cmd_restore(Command):
  3261. """Restore working tree files."""
  3262. def run(self, args: Sequence[str]) -> int | None:
  3263. """Execute the restore command.
  3264. Args:
  3265. args: Command line arguments
  3266. """
  3267. parser = argparse.ArgumentParser()
  3268. parser.add_argument(
  3269. "paths",
  3270. nargs="+",
  3271. type=str,
  3272. help="Paths to restore",
  3273. )
  3274. parser.add_argument(
  3275. "-s",
  3276. "--source",
  3277. type=str,
  3278. help="Restore from a specific commit (default: HEAD for --staged, index for worktree)",
  3279. )
  3280. parser.add_argument(
  3281. "--staged",
  3282. action="store_true",
  3283. help="Restore files in the index",
  3284. )
  3285. parser.add_argument(
  3286. "--worktree",
  3287. action="store_true",
  3288. help="Restore files in the working tree",
  3289. )
  3290. parsed_args = parser.parse_args(args)
  3291. # If neither --staged nor --worktree is specified, default to --worktree
  3292. if not parsed_args.staged and not parsed_args.worktree:
  3293. worktree = True
  3294. staged = False
  3295. else:
  3296. worktree = parsed_args.worktree
  3297. staged = parsed_args.staged
  3298. try:
  3299. porcelain.restore(
  3300. ".",
  3301. paths=parsed_args.paths,
  3302. source=parsed_args.source,
  3303. staged=staged,
  3304. worktree=worktree,
  3305. )
  3306. except porcelain.CheckoutError as e:
  3307. sys.stderr.write(f"{e}\n")
  3308. return 1
  3309. return 0
  3310. class cmd_switch(Command):
  3311. """Switch branches."""
  3312. def run(self, args: Sequence[str]) -> int | None:
  3313. """Execute the switch command.
  3314. Args:
  3315. args: Command line arguments
  3316. """
  3317. parser = argparse.ArgumentParser()
  3318. parser.add_argument(
  3319. "target",
  3320. type=str,
  3321. help="Branch or commit to switch to",
  3322. )
  3323. parser.add_argument(
  3324. "-c",
  3325. "--create",
  3326. type=str,
  3327. help="Create a new branch at the target and switch to it",
  3328. )
  3329. parser.add_argument(
  3330. "-f",
  3331. "--force",
  3332. action="store_true",
  3333. help="Force switch even if there are local changes",
  3334. )
  3335. parser.add_argument(
  3336. "-d",
  3337. "--detach",
  3338. action="store_true",
  3339. help="Switch to a commit in detached HEAD state",
  3340. )
  3341. parsed_args = parser.parse_args(args)
  3342. if not parsed_args.target:
  3343. logger.error(
  3344. "Usage: dulwich switch TARGET [-c NEW_BRANCH] [--force] [--detach]"
  3345. )
  3346. return 1
  3347. try:
  3348. porcelain.switch(
  3349. ".",
  3350. target=parsed_args.target,
  3351. create=parsed_args.create,
  3352. force=parsed_args.force,
  3353. detach=parsed_args.detach,
  3354. )
  3355. except porcelain.CheckoutError as e:
  3356. sys.stderr.write(f"{e}\n")
  3357. return 1
  3358. return 0
  3359. class cmd_stash_list(Command):
  3360. """List stash entries."""
  3361. def run(self, args: Sequence[str]) -> None:
  3362. """Execute the stash-list command.
  3363. Args:
  3364. args: Command line arguments
  3365. """
  3366. parser = argparse.ArgumentParser()
  3367. parser.parse_args(args)
  3368. from .repo import Repo
  3369. from .stash import Stash
  3370. with Repo(".") as r:
  3371. stash = Stash.from_repo(r)
  3372. for i, entry in enumerate(stash.stashes()):
  3373. logger.info(
  3374. "stash@{%d}: %s",
  3375. i,
  3376. entry.message.decode("utf-8", "replace").rstrip("\n"),
  3377. )
  3378. class cmd_stash_push(Command):
  3379. """Save your local modifications to a new stash."""
  3380. def run(self, args: Sequence[str]) -> None:
  3381. """Execute the stash-push command.
  3382. Args:
  3383. args: Command line arguments
  3384. """
  3385. parser = argparse.ArgumentParser()
  3386. parser.parse_args(args)
  3387. porcelain.stash_push(".")
  3388. logger.info("Saved working directory and index state")
  3389. class cmd_stash_pop(Command):
  3390. """Apply a stash and remove it from the stash list."""
  3391. def run(self, args: Sequence[str]) -> None:
  3392. """Execute the stash-pop command.
  3393. Args:
  3394. args: Command line arguments
  3395. """
  3396. parser = argparse.ArgumentParser()
  3397. parser.parse_args(args)
  3398. porcelain.stash_pop(".")
  3399. logger.info("Restored working directory and index state")
  3400. class cmd_bisect(SuperCommand):
  3401. """Use binary search to find the commit that introduced a bug."""
  3402. subcommands: ClassVar[dict[str, type[Command]]] = {}
  3403. def run(self, args: Sequence[str]) -> int | None:
  3404. """Execute the bisect command.
  3405. Args:
  3406. args: Command line arguments
  3407. """
  3408. parser = argparse.ArgumentParser(prog="dulwich bisect")
  3409. subparsers = parser.add_subparsers(dest="subcommand", help="bisect subcommands")
  3410. # bisect start
  3411. start_parser = subparsers.add_parser("start", help="Start a new bisect session")
  3412. start_parser.add_argument("bad", nargs="?", help="Bad commit")
  3413. start_parser.add_argument("good", nargs="*", help="Good commit(s)")
  3414. start_parser.add_argument(
  3415. "--no-checkout",
  3416. action="store_true",
  3417. help="Don't checkout commits during bisect",
  3418. )
  3419. start_parser.add_argument(
  3420. "--term-bad", default="bad", help="Term to use for bad commits"
  3421. )
  3422. start_parser.add_argument(
  3423. "--term-good", default="good", help="Term to use for good commits"
  3424. )
  3425. start_parser.add_argument(
  3426. "--", dest="paths", nargs="*", help="Paths to limit bisect to"
  3427. )
  3428. # bisect bad
  3429. bad_parser = subparsers.add_parser("bad", help="Mark a commit as bad")
  3430. bad_parser.add_argument("rev", nargs="?", help="Commit to mark as bad")
  3431. # bisect good
  3432. good_parser = subparsers.add_parser("good", help="Mark a commit as good")
  3433. good_parser.add_argument("rev", nargs="?", help="Commit to mark as good")
  3434. # bisect skip
  3435. skip_parser = subparsers.add_parser("skip", help="Skip commits")
  3436. skip_parser.add_argument("revs", nargs="*", help="Commits to skip")
  3437. # bisect reset
  3438. reset_parser = subparsers.add_parser("reset", help="Reset bisect state")
  3439. reset_parser.add_argument("commit", nargs="?", help="Commit to reset to")
  3440. # bisect log
  3441. subparsers.add_parser("log", help="Show bisect log")
  3442. # bisect replay
  3443. replay_parser = subparsers.add_parser("replay", help="Replay bisect log")
  3444. replay_parser.add_argument("logfile", help="Log file to replay")
  3445. # bisect help
  3446. subparsers.add_parser("help", help="Show help")
  3447. parsed_args = parser.parse_args(args)
  3448. if not parsed_args.subcommand:
  3449. parser.print_help()
  3450. return 1
  3451. try:
  3452. if parsed_args.subcommand == "start":
  3453. next_sha = porcelain.bisect_start(
  3454. bad=parsed_args.bad,
  3455. good=parsed_args.good if parsed_args.good else None,
  3456. paths=parsed_args.paths,
  3457. no_checkout=parsed_args.no_checkout,
  3458. term_bad=parsed_args.term_bad,
  3459. term_good=parsed_args.term_good,
  3460. )
  3461. if next_sha:
  3462. logger.info(
  3463. "Bisecting: checking out '%s'", next_sha.decode("ascii")
  3464. )
  3465. elif parsed_args.subcommand == "bad":
  3466. next_sha = porcelain.bisect_bad(rev=parsed_args.rev)
  3467. if next_sha:
  3468. logger.info(
  3469. "Bisecting: checking out '%s'", next_sha.decode("ascii")
  3470. )
  3471. else:
  3472. # Bisect complete - find the first bad commit
  3473. with porcelain.open_repo_closing(".") as r:
  3474. bad_ref = os.path.join(r.controldir(), "refs", "bisect", "bad")
  3475. with open(bad_ref, "rb") as f:
  3476. bad_sha = ObjectID(f.read().strip())
  3477. commit = r.object_store[bad_sha]
  3478. assert isinstance(commit, Commit)
  3479. message = commit.message.decode(
  3480. "utf-8", errors="replace"
  3481. ).split("\n")[0]
  3482. logger.info(
  3483. "%s is the first bad commit", bad_sha.decode("ascii")
  3484. )
  3485. logger.info("commit %s", bad_sha.decode("ascii"))
  3486. logger.info(" %s", message)
  3487. elif parsed_args.subcommand == "good":
  3488. next_sha = porcelain.bisect_good(rev=parsed_args.rev)
  3489. if next_sha:
  3490. logger.info(
  3491. "Bisecting: checking out '%s'", next_sha.decode("ascii")
  3492. )
  3493. elif parsed_args.subcommand == "skip":
  3494. next_sha = porcelain.bisect_skip(
  3495. revs=parsed_args.revs if parsed_args.revs else None
  3496. )
  3497. if next_sha:
  3498. logger.info(
  3499. "Bisecting: checking out '%s'", next_sha.decode("ascii")
  3500. )
  3501. elif parsed_args.subcommand == "reset":
  3502. porcelain.bisect_reset(commit=parsed_args.commit)
  3503. logger.info("Bisect reset")
  3504. elif parsed_args.subcommand == "log":
  3505. log = porcelain.bisect_log()
  3506. logger.info(log.rstrip())
  3507. elif parsed_args.subcommand == "replay":
  3508. porcelain.bisect_replay(".", log_file=parsed_args.logfile)
  3509. logger.info("Replayed bisect log from %s", parsed_args.logfile)
  3510. elif parsed_args.subcommand == "help":
  3511. parser.print_help()
  3512. except porcelain.Error as e:
  3513. logger.error("%s", e)
  3514. return 1
  3515. except ValueError as e:
  3516. logger.error("%s", e)
  3517. return 1
  3518. return 0
  3519. class cmd_stash(SuperCommand):
  3520. """Stash the changes in a dirty working directory away."""
  3521. subcommands: ClassVar[dict[str, type[Command]]] = {
  3522. "list": cmd_stash_list,
  3523. "pop": cmd_stash_pop,
  3524. "push": cmd_stash_push,
  3525. }
  3526. class cmd_ls_files(Command):
  3527. """Show information about files in the index and working tree."""
  3528. def run(self, args: Sequence[str]) -> None:
  3529. """Execute the ls-files command.
  3530. Args:
  3531. args: Command line arguments
  3532. """
  3533. parser = argparse.ArgumentParser()
  3534. parser.parse_args(args)
  3535. for name in porcelain.ls_files("."):
  3536. logger.info(name)
  3537. class cmd_describe(Command):
  3538. """Give an object a human readable name based on an available ref."""
  3539. def run(self, args: Sequence[str]) -> None:
  3540. """Execute the describe command.
  3541. Args:
  3542. args: Command line arguments
  3543. """
  3544. parser = argparse.ArgumentParser()
  3545. parser.parse_args(args)
  3546. logger.info(porcelain.describe("."))
  3547. class cmd_diagnose(Command):
  3548. """Display diagnostic information about the Python environment."""
  3549. def run(self, args: Sequence[str]) -> None:
  3550. """Execute the diagnose command.
  3551. Args:
  3552. args: Command line arguments
  3553. """
  3554. # TODO: Support creating zip files with diagnostic information
  3555. parser = argparse.ArgumentParser()
  3556. parser.parse_args(args)
  3557. # Python version and executable
  3558. logger.info("Python version: %s", sys.version)
  3559. logger.info("Python executable: %s", sys.executable)
  3560. # PYTHONPATH
  3561. pythonpath = os.environ.get("PYTHONPATH", "")
  3562. if pythonpath:
  3563. logger.info("PYTHONPATH: %s", pythonpath)
  3564. else:
  3565. logger.info("PYTHONPATH: (not set)")
  3566. # sys.path
  3567. logger.info("sys.path:")
  3568. for path_entry in sys.path:
  3569. logger.info(" %s", path_entry)
  3570. # Dulwich version
  3571. try:
  3572. import dulwich
  3573. logger.info("Dulwich version: %s", dulwich.__version__)
  3574. except AttributeError:
  3575. logger.info("Dulwich version: (unknown)")
  3576. # List installed dependencies and their versions
  3577. logger.info("Installed dependencies:")
  3578. # Core dependencies
  3579. dependencies = [
  3580. ("urllib3", "core"),
  3581. ("typing_extensions", "core (Python < 3.12)"),
  3582. ]
  3583. # Optional dependencies
  3584. optional_dependencies = [
  3585. ("fastimport", "fastimport"),
  3586. ("gpg", "pgp"),
  3587. ("paramiko", "paramiko"),
  3588. ("rich", "colordiff"),
  3589. ("merge3", "merge"),
  3590. ("patiencediff", "patiencediff"),
  3591. ("atheris", "fuzzing"),
  3592. ]
  3593. for dep, dep_type in dependencies + optional_dependencies:
  3594. try:
  3595. module = __import__(dep)
  3596. version = getattr(module, "__version__", "(unknown)")
  3597. logger.info(" %s: %s [%s]", dep, version, dep_type)
  3598. except ImportError:
  3599. logger.info(" %s: (not installed) [%s]", dep, dep_type)
  3600. class cmd_merge(Command):
  3601. """Join two or more development histories together."""
  3602. def run(self, args: Sequence[str]) -> int | None:
  3603. """Execute the merge command.
  3604. Args:
  3605. args: Command line arguments
  3606. """
  3607. parser = argparse.ArgumentParser()
  3608. parser.add_argument("commit", type=str, nargs="+", help="Commit(s) to merge")
  3609. parser.add_argument(
  3610. "--no-commit", action="store_true", help="Do not create a merge commit"
  3611. )
  3612. parser.add_argument(
  3613. "--no-ff", action="store_true", help="Force create a merge commit"
  3614. )
  3615. parser.add_argument("-m", "--message", type=str, help="Merge commit message")
  3616. parsed_args = parser.parse_args(args)
  3617. try:
  3618. # If multiple commits are provided, pass them as a list
  3619. # If only one commit is provided, pass it as a string
  3620. if len(parsed_args.commit) == 1:
  3621. committish = parsed_args.commit[0]
  3622. else:
  3623. committish = parsed_args.commit
  3624. merge_commit_id, conflicts = porcelain.merge(
  3625. ".",
  3626. committish,
  3627. no_commit=parsed_args.no_commit,
  3628. no_ff=parsed_args.no_ff,
  3629. message=parsed_args.message,
  3630. )
  3631. if conflicts:
  3632. logger.warning("Merge conflicts in %d file(s):", len(conflicts))
  3633. for conflict_path in conflicts:
  3634. logger.warning(" %s", conflict_path.decode())
  3635. if len(parsed_args.commit) > 1:
  3636. logger.error(
  3637. "Octopus merge failed; refusing to merge with conflicts."
  3638. )
  3639. else:
  3640. logger.error(
  3641. "Automatic merge failed; fix conflicts and then commit the result."
  3642. )
  3643. return 1
  3644. elif merge_commit_id is None and not parsed_args.no_commit:
  3645. logger.info("Already up to date.")
  3646. elif parsed_args.no_commit:
  3647. logger.info("Automatic merge successful; not committing as requested.")
  3648. else:
  3649. assert merge_commit_id is not None
  3650. if len(parsed_args.commit) > 1:
  3651. logger.info(
  3652. "Octopus merge successful. Created merge commit %s",
  3653. merge_commit_id.decode(),
  3654. )
  3655. else:
  3656. logger.info(
  3657. "Merge successful. Created merge commit %s",
  3658. merge_commit_id.decode(),
  3659. )
  3660. return 0
  3661. except porcelain.Error as e:
  3662. logger.error("%s", e)
  3663. return 1
  3664. class cmd_merge_base(Command):
  3665. """Find the best common ancestor between commits."""
  3666. def run(self, args: Sequence[str]) -> int | None:
  3667. """Execute the merge-base command.
  3668. Args:
  3669. args: Command line arguments
  3670. """
  3671. parser = argparse.ArgumentParser(
  3672. description="Find the best common ancestor between commits",
  3673. prog="dulwich merge-base",
  3674. )
  3675. parser.add_argument("commits", nargs="+", help="Commits to find merge base for")
  3676. parser.add_argument("--all", action="store_true", help="Output all merge bases")
  3677. parser.add_argument(
  3678. "--octopus",
  3679. action="store_true",
  3680. help="Compute common ancestor of all commits",
  3681. )
  3682. parser.add_argument(
  3683. "--is-ancestor",
  3684. action="store_true",
  3685. help="Check if first commit is ancestor of second",
  3686. )
  3687. parser.add_argument(
  3688. "--independent",
  3689. action="store_true",
  3690. help="List commits not reachable from others",
  3691. )
  3692. parsed_args = parser.parse_args(args)
  3693. try:
  3694. if parsed_args.is_ancestor:
  3695. if len(parsed_args.commits) != 2:
  3696. logger.error("--is-ancestor requires exactly two commits")
  3697. return 1
  3698. is_anc = porcelain.is_ancestor(
  3699. ".",
  3700. ancestor=parsed_args.commits[0],
  3701. descendant=parsed_args.commits[1],
  3702. )
  3703. return 0 if is_anc else 1
  3704. elif parsed_args.independent:
  3705. commits = porcelain.independent_commits(".", parsed_args.commits)
  3706. for commit_id in commits:
  3707. print(commit_id.decode())
  3708. return 0
  3709. else:
  3710. if len(parsed_args.commits) < 2:
  3711. logger.error("At least two commits are required")
  3712. return 1
  3713. merge_bases = porcelain.merge_base(
  3714. ".",
  3715. parsed_args.commits,
  3716. all=parsed_args.all,
  3717. octopus=parsed_args.octopus,
  3718. )
  3719. for commit_id in merge_bases:
  3720. print(commit_id.decode())
  3721. return 0
  3722. except (ValueError, KeyError) as e:
  3723. logger.error("%s", e)
  3724. return 1
  3725. class cmd_notes_add(Command):
  3726. """Add notes to a commit."""
  3727. def run(self, args: Sequence[str]) -> None:
  3728. """Execute the notes-add command.
  3729. Args:
  3730. args: Command line arguments
  3731. """
  3732. parser = argparse.ArgumentParser()
  3733. parser.add_argument("object", help="Object to annotate")
  3734. parser.add_argument("-m", "--message", help="Note message", required=True)
  3735. parser.add_argument(
  3736. "--ref", default="commits", help="Notes ref (default: commits)"
  3737. )
  3738. parsed_args = parser.parse_args(args)
  3739. porcelain.notes_add(
  3740. ".", parsed_args.object, parsed_args.message, ref=parsed_args.ref
  3741. )
  3742. class cmd_notes_show(Command):
  3743. """Show notes for a commit."""
  3744. def run(self, args: Sequence[str]) -> None:
  3745. """Execute the notes-show command.
  3746. Args:
  3747. args: Command line arguments
  3748. """
  3749. parser = argparse.ArgumentParser()
  3750. parser.add_argument("object", help="Object to show notes for")
  3751. parser.add_argument(
  3752. "--ref", default="commits", help="Notes ref (default: commits)"
  3753. )
  3754. parsed_args = parser.parse_args(args)
  3755. note = porcelain.notes_show(".", parsed_args.object, ref=parsed_args.ref)
  3756. if note:
  3757. sys.stdout.buffer.write(note)
  3758. else:
  3759. logger.info("No notes found for object %s", parsed_args.object)
  3760. class cmd_notes_remove(Command):
  3761. """Remove notes for a commit."""
  3762. def run(self, args: Sequence[str]) -> None:
  3763. """Execute the notes-remove command.
  3764. Args:
  3765. args: Command line arguments
  3766. """
  3767. parser = argparse.ArgumentParser()
  3768. parser.add_argument("object", help="Object to remove notes from")
  3769. parser.add_argument(
  3770. "--ref", default="commits", help="Notes ref (default: commits)"
  3771. )
  3772. parsed_args = parser.parse_args(args)
  3773. result = porcelain.notes_remove(".", parsed_args.object, ref=parsed_args.ref)
  3774. if result:
  3775. logger.info("Removed notes for object %s", parsed_args.object)
  3776. else:
  3777. logger.info("No notes found for object %s", parsed_args.object)
  3778. class cmd_notes_list(Command):
  3779. """List all note objects."""
  3780. def run(self, args: Sequence[str]) -> None:
  3781. """Execute the notes-list command.
  3782. Args:
  3783. args: Command line arguments
  3784. """
  3785. parser = argparse.ArgumentParser()
  3786. parser.add_argument(
  3787. "--ref", default="commits", help="Notes ref (default: commits)"
  3788. )
  3789. parsed_args = parser.parse_args(args)
  3790. notes = porcelain.notes_list(".", ref=parsed_args.ref)
  3791. for object_sha, note_content in notes:
  3792. logger.info(object_sha.hex())
  3793. class cmd_notes(SuperCommand):
  3794. """Add or inspect object notes."""
  3795. subcommands: ClassVar[dict[str, type[Command]]] = {
  3796. "add": cmd_notes_add,
  3797. "show": cmd_notes_show,
  3798. "remove": cmd_notes_remove,
  3799. "list": cmd_notes_list,
  3800. }
  3801. default_command = cmd_notes_list
  3802. class cmd_replace_list(Command):
  3803. """List all replacement refs."""
  3804. def run(self, args: Sequence[str]) -> None:
  3805. """Execute the replace-list command.
  3806. Args:
  3807. args: Command line arguments
  3808. """
  3809. parser = argparse.ArgumentParser()
  3810. parser.parse_args(args)
  3811. replacements = porcelain.replace_list(".")
  3812. for object_sha, replacement_sha in replacements:
  3813. sys.stdout.write(
  3814. f"{object_sha.decode('ascii')} -> {replacement_sha.decode('ascii')}\n"
  3815. )
  3816. class cmd_replace_delete(Command):
  3817. """Delete a replacement ref."""
  3818. def run(self, args: Sequence[str]) -> int | None:
  3819. """Execute the replace-delete command.
  3820. Args:
  3821. args: Command line arguments
  3822. Returns:
  3823. Exit code (0 for success, 1 for error)
  3824. """
  3825. parser = argparse.ArgumentParser()
  3826. parser.add_argument("object", help="Object whose replacement should be removed")
  3827. parsed_args = parser.parse_args(args)
  3828. try:
  3829. porcelain.replace_delete(".", parsed_args.object)
  3830. logger.info("Deleted replacement for %s", parsed_args.object)
  3831. return None
  3832. except KeyError as e:
  3833. logger.error(str(e))
  3834. return 1
  3835. class cmd_replace(SuperCommand):
  3836. """Create, list, and delete replacement refs."""
  3837. subcommands: ClassVar[dict[str, type[Command]]] = {
  3838. "list": cmd_replace_list,
  3839. "delete": cmd_replace_delete,
  3840. }
  3841. default_command = cmd_replace_list
  3842. def run(self, args: Sequence[str]) -> int | None:
  3843. """Execute the replace command.
  3844. Args:
  3845. args: Command line arguments
  3846. Returns:
  3847. Exit code (0 for success, 1 for error)
  3848. """
  3849. # Special case: if we have exactly 2 args and no subcommand, treat as create
  3850. if len(args) == 2 and args[0] not in self.subcommands:
  3851. # This is the create form: git replace <object> <replacement>
  3852. parser = argparse.ArgumentParser()
  3853. parser.add_argument("object", help="Object to replace")
  3854. parser.add_argument("replacement", help="Replacement object")
  3855. parsed_args = parser.parse_args(args)
  3856. porcelain.replace_create(".", parsed_args.object, parsed_args.replacement)
  3857. logger.info(
  3858. "Created replacement: %s -> %s",
  3859. parsed_args.object,
  3860. parsed_args.replacement,
  3861. )
  3862. return None
  3863. # Otherwise, delegate to supercommand handling
  3864. return super().run(args)
  3865. class cmd_cherry(Command):
  3866. """Find commits not merged upstream."""
  3867. def run(self, args: Sequence[str]) -> int | None:
  3868. """Execute the cherry command.
  3869. Args:
  3870. args: Command line arguments
  3871. Returns:
  3872. Exit code (0 for success, 1 for error)
  3873. """
  3874. parser = argparse.ArgumentParser(description="Find commits not merged upstream")
  3875. parser.add_argument(
  3876. "-v",
  3877. "--verbose",
  3878. action="store_true",
  3879. help="Show commit messages",
  3880. )
  3881. parser.add_argument(
  3882. "upstream",
  3883. nargs="?",
  3884. help="Upstream branch (default: tracking branch or HEAD^)",
  3885. )
  3886. parser.add_argument(
  3887. "head",
  3888. nargs="?",
  3889. help="Head branch (default: HEAD)",
  3890. )
  3891. parser.add_argument(
  3892. "limit",
  3893. nargs="?",
  3894. help="Limit commits to those after this ref",
  3895. )
  3896. parsed_args = parser.parse_args(args)
  3897. try:
  3898. results = porcelain.cherry(
  3899. ".",
  3900. upstream=parsed_args.upstream,
  3901. head=parsed_args.head,
  3902. limit=parsed_args.limit,
  3903. verbose=parsed_args.verbose,
  3904. )
  3905. except (NotGitRepository, OSError, FileFormatException, ValueError) as e:
  3906. logger.error(f"Error: {e}")
  3907. return 1
  3908. # Output results
  3909. for status, commit_sha, message in results:
  3910. # Convert commit_sha to hex string
  3911. if isinstance(commit_sha, bytes):
  3912. commit_hex = commit_sha.hex()
  3913. else:
  3914. commit_hex = commit_sha
  3915. if parsed_args.verbose and message:
  3916. message_str = message.decode("utf-8", errors="replace")
  3917. logger.info(f"{status} {commit_hex} {message_str}")
  3918. else:
  3919. logger.info(f"{status} {commit_hex}")
  3920. return 0
  3921. class cmd_cherry_pick(Command):
  3922. """Apply the changes introduced by some existing commits."""
  3923. def run(self, args: Sequence[str]) -> int | None:
  3924. """Execute the cherry-pick command.
  3925. Args:
  3926. args: Command line arguments
  3927. """
  3928. parser = argparse.ArgumentParser(
  3929. description="Apply the changes introduced by some existing commits"
  3930. )
  3931. parser.add_argument("commit", nargs="?", help="Commit to cherry-pick")
  3932. parser.add_argument(
  3933. "-n",
  3934. "--no-commit",
  3935. action="store_true",
  3936. help="Apply changes without making a commit",
  3937. )
  3938. parser.add_argument(
  3939. "--continue",
  3940. dest="continue_",
  3941. action="store_true",
  3942. help="Continue after resolving conflicts",
  3943. )
  3944. parser.add_argument(
  3945. "--abort",
  3946. action="store_true",
  3947. help="Abort the current cherry-pick operation",
  3948. )
  3949. parsed_args = parser.parse_args(args)
  3950. # Check argument validity
  3951. if parsed_args.continue_ or parsed_args.abort:
  3952. if parsed_args.commit is not None:
  3953. parser.error("Cannot specify commit with --continue or --abort")
  3954. return 1
  3955. else:
  3956. if parsed_args.commit is None:
  3957. parser.error("Commit argument is required")
  3958. return 1
  3959. try:
  3960. commit_arg = parsed_args.commit
  3961. result = porcelain.cherry_pick(
  3962. ".",
  3963. commit_arg,
  3964. no_commit=parsed_args.no_commit,
  3965. continue_=parsed_args.continue_,
  3966. abort=parsed_args.abort,
  3967. )
  3968. if parsed_args.abort:
  3969. logger.info("Cherry-pick aborted.")
  3970. elif parsed_args.continue_:
  3971. if result:
  3972. logger.info("Cherry-pick completed: %s", result.decode())
  3973. else:
  3974. logger.info("Cherry-pick completed.")
  3975. elif result is None:
  3976. if parsed_args.no_commit:
  3977. logger.info("Cherry-pick applied successfully (no commit created).")
  3978. else:
  3979. # This shouldn't happen unless there were conflicts
  3980. logger.warning("Cherry-pick resulted in conflicts.")
  3981. else:
  3982. logger.info("Cherry-pick successful: %s", result.decode())
  3983. return None
  3984. except porcelain.Error as e:
  3985. logger.error("%s", e)
  3986. return 1
  3987. class cmd_merge_tree(Command):
  3988. """Show three-way merge without touching index."""
  3989. def run(self, args: Sequence[str]) -> int | None:
  3990. """Execute the merge-tree command.
  3991. Args:
  3992. args: Command line arguments
  3993. """
  3994. parser = argparse.ArgumentParser(
  3995. description="Perform a tree-level merge without touching the working directory"
  3996. )
  3997. parser.add_argument(
  3998. "base_tree",
  3999. nargs="?",
  4000. help="The common ancestor tree (optional, defaults to empty tree)",
  4001. )
  4002. parser.add_argument("our_tree", help="Our side of the merge")
  4003. parser.add_argument("their_tree", help="Their side of the merge")
  4004. parser.add_argument(
  4005. "-z",
  4006. "--name-only",
  4007. action="store_true",
  4008. help="Output only conflict paths, null-terminated",
  4009. )
  4010. parsed_args = parser.parse_args(args)
  4011. try:
  4012. # Determine base tree - if only two parsed_args provided, base is None
  4013. if parsed_args.base_tree is None:
  4014. # Only two arguments provided
  4015. base_tree = None
  4016. our_tree = parsed_args.our_tree
  4017. their_tree = parsed_args.their_tree
  4018. else:
  4019. # Three arguments provided
  4020. base_tree = parsed_args.base_tree
  4021. our_tree = parsed_args.our_tree
  4022. their_tree = parsed_args.their_tree
  4023. merged_tree_id, conflicts = porcelain.merge_tree(
  4024. ".", base_tree, our_tree, their_tree
  4025. )
  4026. if parsed_args.name_only:
  4027. # Output only conflict paths, null-terminated
  4028. for conflict_path in conflicts:
  4029. sys.stdout.buffer.write(conflict_path)
  4030. sys.stdout.buffer.write(b"\0")
  4031. else:
  4032. # Output the merged tree SHA
  4033. logger.info(merged_tree_id.decode("ascii"))
  4034. # Output conflict information
  4035. if conflicts:
  4036. logger.warning("\nConflicts in %d file(s):", len(conflicts))
  4037. for conflict_path in conflicts:
  4038. logger.warning(" %s", conflict_path.decode())
  4039. return None
  4040. except porcelain.Error as e:
  4041. logger.error("%s", e)
  4042. return 1
  4043. except KeyError as e:
  4044. logger.error("Object not found: %s", e)
  4045. return 1
  4046. class cmd_gc(Command):
  4047. """Cleanup unnecessary files and optimize the local repository."""
  4048. def run(self, args: Sequence[str]) -> int | None:
  4049. """Execute the gc command.
  4050. Args:
  4051. args: Command line arguments
  4052. """
  4053. import datetime
  4054. import time
  4055. parser = argparse.ArgumentParser()
  4056. parser.add_argument(
  4057. "--auto",
  4058. action="store_true",
  4059. help="Only run gc if needed",
  4060. )
  4061. parser.add_argument(
  4062. "--aggressive",
  4063. action="store_true",
  4064. help="Use more aggressive settings",
  4065. )
  4066. parser.add_argument(
  4067. "--no-prune",
  4068. action="store_true",
  4069. help="Do not prune unreachable objects",
  4070. )
  4071. parser.add_argument(
  4072. "--prune",
  4073. nargs="?",
  4074. const="now",
  4075. help="Prune unreachable objects older than date (default: 2 weeks ago)",
  4076. )
  4077. parser.add_argument(
  4078. "--dry-run",
  4079. "-n",
  4080. action="store_true",
  4081. help="Only report what would be done",
  4082. )
  4083. parser.add_argument(
  4084. "--quiet",
  4085. "-q",
  4086. action="store_true",
  4087. help="Only report errors",
  4088. )
  4089. parsed_args = parser.parse_args(args)
  4090. # Parse prune grace period
  4091. grace_period = None
  4092. if parsed_args.prune:
  4093. from .approxidate import parse_relative_time
  4094. try:
  4095. grace_period = parse_relative_time(parsed_args.prune)
  4096. except ValueError:
  4097. # Try to parse as absolute date
  4098. try:
  4099. date = datetime.datetime.strptime(parsed_args.prune, "%Y-%m-%d")
  4100. grace_period = int(time.time() - date.timestamp())
  4101. except ValueError:
  4102. logger.error("Invalid prune date: %s", parsed_args.prune)
  4103. return 1
  4104. elif not parsed_args.no_prune:
  4105. # Default to 2 weeks
  4106. grace_period = 1209600
  4107. # Progress callback
  4108. def progress(msg: str) -> None:
  4109. if not parsed_args.quiet:
  4110. logger.info(msg)
  4111. try:
  4112. stats = porcelain.gc(
  4113. ".",
  4114. auto=parsed_args.auto,
  4115. aggressive=parsed_args.aggressive,
  4116. prune=not parsed_args.no_prune,
  4117. grace_period=grace_period,
  4118. dry_run=parsed_args.dry_run,
  4119. progress=progress if not parsed_args.quiet else None,
  4120. )
  4121. # Report results
  4122. if not parsed_args.quiet:
  4123. if parsed_args.dry_run:
  4124. logger.info("\nDry run results:")
  4125. if not parsed_args.quiet:
  4126. if parsed_args.dry_run:
  4127. print("\nDry run results:")
  4128. else:
  4129. logger.info("\nGarbage collection complete:")
  4130. if stats.pruned_objects:
  4131. logger.info(
  4132. " Pruned %d unreachable objects", len(stats.pruned_objects)
  4133. )
  4134. logger.info(" Freed %s", format_bytes(stats.bytes_freed))
  4135. if stats.packs_before != stats.packs_after:
  4136. logger.info(
  4137. " Reduced pack files from %d to %d",
  4138. stats.packs_before,
  4139. stats.packs_after,
  4140. )
  4141. except porcelain.Error as e:
  4142. logger.error("%s", e)
  4143. return 1
  4144. return None
  4145. class cmd_maintenance(Command):
  4146. """Run tasks to optimize Git repository data."""
  4147. def run(self, args: Sequence[str]) -> int | None:
  4148. """Execute the maintenance command.
  4149. Args:
  4150. args: Command line arguments
  4151. """
  4152. parser = argparse.ArgumentParser(
  4153. description="Run tasks to optimize Git repository data"
  4154. )
  4155. subparsers = parser.add_subparsers(
  4156. dest="subcommand", help="Maintenance subcommand"
  4157. )
  4158. # maintenance run subcommand
  4159. run_parser = subparsers.add_parser("run", help="Run maintenance tasks")
  4160. run_parser.add_argument(
  4161. "--task",
  4162. action="append",
  4163. dest="tasks",
  4164. help="Run a specific task (can be specified multiple times)",
  4165. )
  4166. run_parser.add_argument(
  4167. "--auto",
  4168. action="store_true",
  4169. help="Only run tasks if needed",
  4170. )
  4171. run_parser.add_argument(
  4172. "--quiet",
  4173. "-q",
  4174. action="store_true",
  4175. help="Only report errors",
  4176. )
  4177. # maintenance start subcommand (placeholder)
  4178. subparsers.add_parser("start", help="Start background maintenance")
  4179. # maintenance stop subcommand (placeholder)
  4180. subparsers.add_parser("stop", help="Stop background maintenance")
  4181. # maintenance register subcommand
  4182. subparsers.add_parser("register", help="Register repository for maintenance")
  4183. # maintenance unregister subcommand
  4184. unregister_parser = subparsers.add_parser(
  4185. "unregister", help="Unregister repository from maintenance"
  4186. )
  4187. unregister_parser.add_argument(
  4188. "--force",
  4189. action="store_true",
  4190. help="Don't error if repository is not registered",
  4191. )
  4192. parsed_args = parser.parse_args(args)
  4193. if not parsed_args.subcommand:
  4194. parser.print_help()
  4195. return 1
  4196. if parsed_args.subcommand == "run":
  4197. # Progress callback
  4198. def progress(msg: str) -> None:
  4199. if not parsed_args.quiet:
  4200. logger.info(msg)
  4201. try:
  4202. result = porcelain.maintenance_run(
  4203. ".",
  4204. tasks=parsed_args.tasks,
  4205. auto=parsed_args.auto,
  4206. progress=progress if not parsed_args.quiet else None,
  4207. )
  4208. # Report results
  4209. if not parsed_args.quiet:
  4210. if result.tasks_succeeded:
  4211. logger.info("\nSuccessfully completed tasks:")
  4212. for task in result.tasks_succeeded:
  4213. logger.info(f" - {task}")
  4214. if result.tasks_failed:
  4215. logger.error("\nFailed tasks:")
  4216. for task in result.tasks_failed:
  4217. error_msg = result.errors.get(task, "Unknown error")
  4218. logger.error(f" - {task}: {error_msg}")
  4219. return 1
  4220. except porcelain.Error as e:
  4221. logger.error("%s", e)
  4222. return 1
  4223. elif parsed_args.subcommand == "register":
  4224. porcelain.maintenance_register(".")
  4225. logger.info("Repository registered for background maintenance")
  4226. elif parsed_args.subcommand == "unregister":
  4227. try:
  4228. force = getattr(parsed_args, "force", False)
  4229. porcelain.maintenance_unregister(".", force=force)
  4230. except ValueError as e:
  4231. logger.error(str(e))
  4232. return 1
  4233. logger.info("Repository unregistered from background maintenance")
  4234. elif parsed_args.subcommand in ("start", "stop"):
  4235. # TODO: Implement background maintenance scheduling
  4236. logger.error(
  4237. f"The '{parsed_args.subcommand}' subcommand is not yet implemented"
  4238. )
  4239. return 1
  4240. else:
  4241. parser.print_help()
  4242. return 1
  4243. return None
  4244. class cmd_grep(Command):
  4245. """Search for patterns in tracked files."""
  4246. def run(self, args: Sequence[str]) -> None:
  4247. """Execute the grep command.
  4248. Args:
  4249. args: Command line arguments
  4250. """
  4251. parser = argparse.ArgumentParser()
  4252. parser.add_argument("pattern", help="Regular expression pattern to search for")
  4253. parser.add_argument(
  4254. "revision",
  4255. nargs="?",
  4256. default=None,
  4257. help="Revision to search (defaults to HEAD)",
  4258. )
  4259. parser.add_argument(
  4260. "pathspecs",
  4261. nargs="*",
  4262. help="Path patterns to limit search",
  4263. )
  4264. parser.add_argument(
  4265. "-i",
  4266. "--ignore-case",
  4267. action="store_true",
  4268. help="Perform case-insensitive matching",
  4269. )
  4270. parser.add_argument(
  4271. "-n",
  4272. "--line-number",
  4273. action="store_true",
  4274. help="Show line numbers for matches",
  4275. )
  4276. parser.add_argument(
  4277. "--max-depth",
  4278. type=int,
  4279. default=None,
  4280. help="Maximum directory depth to search",
  4281. )
  4282. parser.add_argument(
  4283. "--no-ignore",
  4284. action="store_true",
  4285. help="Do not respect .gitignore patterns",
  4286. )
  4287. parsed_args = parser.parse_args(args)
  4288. # Handle the case where revision might be a pathspec
  4289. revision = parsed_args.revision
  4290. pathspecs = parsed_args.pathspecs
  4291. # If revision looks like a pathspec (contains wildcards or slashes),
  4292. # treat it as a pathspec instead
  4293. if revision and ("*" in revision or "/" in revision or "." in revision):
  4294. pathspecs = [revision, *pathspecs]
  4295. revision = None
  4296. with Repo(".") as repo:
  4297. config = repo.get_config_stack()
  4298. with get_pager(config=config, cmd_name="grep") as outstream:
  4299. porcelain.grep(
  4300. repo,
  4301. parsed_args.pattern,
  4302. outstream=outstream,
  4303. rev=revision,
  4304. pathspecs=pathspecs if pathspecs else None,
  4305. ignore_case=parsed_args.ignore_case,
  4306. line_number=parsed_args.line_number,
  4307. max_depth=parsed_args.max_depth,
  4308. respect_ignores=not parsed_args.no_ignore,
  4309. )
  4310. class cmd_count_objects(Command):
  4311. """Count unpacked number of objects and their disk consumption."""
  4312. def run(self, args: Sequence[str]) -> None:
  4313. """Execute the count-objects command.
  4314. Args:
  4315. args: Command line arguments
  4316. """
  4317. parser = argparse.ArgumentParser()
  4318. parser.add_argument(
  4319. "-v",
  4320. "--verbose",
  4321. action="store_true",
  4322. help="Display verbose information.",
  4323. )
  4324. parsed_args = parser.parse_args(args)
  4325. if parsed_args.verbose:
  4326. stats = porcelain.count_objects(".", verbose=True)
  4327. # Display verbose output
  4328. logger.info("count: %d", stats.count)
  4329. logger.info("size: %d", stats.size // 1024) # Size in KiB
  4330. assert stats.in_pack is not None
  4331. logger.info("in-pack: %d", stats.in_pack)
  4332. assert stats.packs is not None
  4333. logger.info("packs: %d", stats.packs)
  4334. assert stats.size_pack is not None
  4335. logger.info("size-pack: %d", stats.size_pack // 1024) # Size in KiB
  4336. else:
  4337. # Simple output
  4338. stats = porcelain.count_objects(".", verbose=False)
  4339. logger.info("%d objects, %d kilobytes", stats.count, stats.size // 1024)
  4340. class cmd_rebase(Command):
  4341. """Reapply commits on top of another base tip."""
  4342. def run(self, args: Sequence[str]) -> int:
  4343. """Execute the rebase command.
  4344. Args:
  4345. args: Command line arguments
  4346. """
  4347. parser = argparse.ArgumentParser()
  4348. parser.add_argument(
  4349. "upstream", nargs="?", help="Upstream branch to rebase onto"
  4350. )
  4351. parser.add_argument("--onto", type=str, help="Rebase onto specific commit")
  4352. parser.add_argument(
  4353. "--branch", type=str, help="Branch to rebase (default: current)"
  4354. )
  4355. parser.add_argument(
  4356. "-i", "--interactive", action="store_true", help="Interactive rebase"
  4357. )
  4358. parser.add_argument(
  4359. "--edit-todo",
  4360. action="store_true",
  4361. help="Edit the todo list during an interactive rebase",
  4362. )
  4363. parser.add_argument(
  4364. "--abort", action="store_true", help="Abort an in-progress rebase"
  4365. )
  4366. parser.add_argument(
  4367. "--continue",
  4368. dest="continue_rebase",
  4369. action="store_true",
  4370. help="Continue an in-progress rebase",
  4371. )
  4372. parser.add_argument(
  4373. "--skip", action="store_true", help="Skip current commit and continue"
  4374. )
  4375. parsed_args = parser.parse_args(args)
  4376. # Handle abort/continue/skip first
  4377. if parsed_args.abort:
  4378. try:
  4379. porcelain.rebase(".", parsed_args.upstream or "HEAD", abort=True)
  4380. logger.info("Rebase aborted.")
  4381. except porcelain.Error as e:
  4382. logger.error("%s", e)
  4383. return 1
  4384. return 0
  4385. if parsed_args.continue_rebase:
  4386. try:
  4387. # Check if interactive rebase is in progress
  4388. if porcelain.is_interactive_rebase("."):
  4389. result = porcelain.rebase(
  4390. ".",
  4391. parsed_args.upstream or "HEAD",
  4392. continue_rebase=True,
  4393. interactive=True,
  4394. )
  4395. if result:
  4396. logger.info("Rebase complete.")
  4397. else:
  4398. logger.info("Rebase paused. Use --continue to resume.")
  4399. else:
  4400. new_shas = porcelain.rebase(
  4401. ".", parsed_args.upstream or "HEAD", continue_rebase=True
  4402. )
  4403. logger.info("Rebase complete.")
  4404. except porcelain.Error as e:
  4405. logger.error("%s", e)
  4406. return 1
  4407. return 0
  4408. if parsed_args.edit_todo:
  4409. # Edit todo list for interactive rebase
  4410. try:
  4411. porcelain.rebase(".", parsed_args.upstream or "HEAD", edit_todo=True)
  4412. logger.info("Todo list updated.")
  4413. except porcelain.Error as e:
  4414. logger.error("%s", e)
  4415. return 1
  4416. return 0
  4417. # Normal rebase requires upstream
  4418. if not parsed_args.upstream:
  4419. logger.error("Missing required argument 'upstream'")
  4420. return 1
  4421. try:
  4422. if parsed_args.interactive:
  4423. # Interactive rebase
  4424. result = porcelain.rebase(
  4425. ".",
  4426. parsed_args.upstream,
  4427. onto=parsed_args.onto,
  4428. branch=parsed_args.branch,
  4429. interactive=True,
  4430. )
  4431. if result:
  4432. logger.info(
  4433. "Interactive rebase started. Edit the todo list and save."
  4434. )
  4435. else:
  4436. logger.info("No commits to rebase.")
  4437. else:
  4438. # Regular rebase
  4439. new_shas = porcelain.rebase(
  4440. ".",
  4441. parsed_args.upstream,
  4442. onto=parsed_args.onto,
  4443. branch=parsed_args.branch,
  4444. )
  4445. if new_shas:
  4446. logger.info("Successfully rebased %d commits.", len(new_shas))
  4447. else:
  4448. logger.info("Already up to date.")
  4449. return 0
  4450. except porcelain.Error as e:
  4451. logger.error("%s", e)
  4452. return 1
  4453. class cmd_filter_branch(Command):
  4454. """Rewrite branches."""
  4455. def run(self, args: Sequence[str]) -> int | None:
  4456. """Execute the filter-branch command.
  4457. Args:
  4458. args: Command line arguments
  4459. """
  4460. import subprocess
  4461. parser = argparse.ArgumentParser(description="Rewrite branches")
  4462. # Supported Git-compatible options
  4463. parser.add_argument(
  4464. "--subdirectory-filter",
  4465. type=str,
  4466. help="Only include history for subdirectory",
  4467. )
  4468. parser.add_argument("--env-filter", type=str, help="Environment filter command")
  4469. parser.add_argument("--tree-filter", type=str, help="Tree filter command")
  4470. parser.add_argument("--index-filter", type=str, help="Index filter command")
  4471. parser.add_argument("--parent-filter", type=str, help="Parent filter command")
  4472. parser.add_argument("--msg-filter", type=str, help="Message filter command")
  4473. parser.add_argument("--commit-filter", type=str, help="Commit filter command")
  4474. parser.add_argument(
  4475. "--tag-name-filter", type=str, help="Tag name filter command"
  4476. )
  4477. parser.add_argument(
  4478. "--prune-empty", action="store_true", help="Remove empty commits"
  4479. )
  4480. parser.add_argument(
  4481. "--original",
  4482. type=str,
  4483. default="refs/original",
  4484. help="Namespace for original refs",
  4485. )
  4486. parser.add_argument(
  4487. "-f",
  4488. "--force",
  4489. action="store_true",
  4490. help="Force operation even if refs/original/* exists",
  4491. )
  4492. # Branch/ref to rewrite (defaults to HEAD)
  4493. parser.add_argument(
  4494. "branch", nargs="?", default="HEAD", help="Branch or ref to rewrite"
  4495. )
  4496. parsed_args = parser.parse_args(args)
  4497. # Track if any filter fails
  4498. filter_error = False
  4499. # Setup environment for filters
  4500. env = os.environ.copy()
  4501. # Helper function to run shell commands
  4502. def run_filter(
  4503. cmd: str,
  4504. input_data: bytes | None = None,
  4505. cwd: str | None = None,
  4506. extra_env: dict[str, str] | None = None,
  4507. ) -> bytes | None:
  4508. nonlocal filter_error
  4509. filter_env = env.copy()
  4510. if extra_env:
  4511. filter_env.update(extra_env)
  4512. result = subprocess.run(
  4513. cmd,
  4514. shell=True,
  4515. input=input_data,
  4516. cwd=cwd,
  4517. env=filter_env,
  4518. capture_output=True,
  4519. )
  4520. if result.returncode != 0:
  4521. filter_error = True
  4522. return None
  4523. return result.stdout
  4524. # Create filter functions based on arguments
  4525. filter_message = None
  4526. if parsed_args.msg_filter:
  4527. def filter_message(message: bytes) -> bytes:
  4528. result = run_filter(parsed_args.msg_filter, input_data=message)
  4529. return result if result is not None else message
  4530. tree_filter = None
  4531. if parsed_args.tree_filter:
  4532. def tree_filter(tree_sha: ObjectID, tmpdir: str) -> ObjectID:
  4533. from dulwich.objects import Blob, Tree
  4534. # Export tree to tmpdir
  4535. with Repo(".") as r:
  4536. tree = r.object_store[tree_sha]
  4537. assert isinstance(tree, Tree)
  4538. for entry in tree.iteritems():
  4539. assert entry.path is not None
  4540. assert entry.sha is not None
  4541. path = Path(tmpdir) / entry.path.decode()
  4542. obj = r.object_store[entry.sha]
  4543. if isinstance(obj, Tree):
  4544. path.mkdir(exist_ok=True)
  4545. else:
  4546. assert isinstance(obj, Blob)
  4547. path.write_bytes(obj.data)
  4548. # Run the filter command in the temp directory
  4549. run_filter(parsed_args.tree_filter, cwd=tmpdir)
  4550. # Rebuild tree from modified temp directory
  4551. def build_tree_from_dir(dir_path: str) -> ObjectID:
  4552. tree = Tree()
  4553. for name in sorted(os.listdir(dir_path)):
  4554. if name.startswith("."):
  4555. continue
  4556. path = os.path.join(dir_path, name)
  4557. if os.path.isdir(path):
  4558. subtree_sha = build_tree_from_dir(path)
  4559. tree.add(name.encode(), 0o040000, subtree_sha)
  4560. else:
  4561. with open(path, "rb") as f:
  4562. data = f.read()
  4563. blob = Blob.from_string(data)
  4564. r.object_store.add_object(blob)
  4565. # Use appropriate file mode
  4566. mode = os.stat(path).st_mode
  4567. if mode & 0o100:
  4568. file_mode = 0o100755
  4569. else:
  4570. file_mode = 0o100644
  4571. tree.add(name.encode(), file_mode, blob.id)
  4572. r.object_store.add_object(tree)
  4573. return tree.id
  4574. return build_tree_from_dir(tmpdir)
  4575. index_filter = None
  4576. if parsed_args.index_filter:
  4577. def index_filter(tree_sha: ObjectID, index_path: str) -> ObjectID | None:
  4578. run_filter(
  4579. parsed_args.index_filter, extra_env={"GIT_INDEX_FILE": index_path}
  4580. )
  4581. return None # Read back from index
  4582. parent_filter = None
  4583. if parsed_args.parent_filter:
  4584. def parent_filter(parents: Sequence[ObjectID]) -> list[ObjectID]:
  4585. parent_str = " ".join(p.hex() for p in parents)
  4586. result = run_filter(
  4587. parsed_args.parent_filter, input_data=parent_str.encode()
  4588. )
  4589. if result is None:
  4590. return list(parents)
  4591. output = result.decode().strip()
  4592. if not output:
  4593. return []
  4594. new_parents = []
  4595. for sha in output.split():
  4596. sha_bytes = sha.encode()
  4597. if valid_hexsha(sha_bytes):
  4598. new_parents.append(ObjectID(sha_bytes))
  4599. return new_parents
  4600. commit_filter = None
  4601. if parsed_args.commit_filter:
  4602. def commit_filter(
  4603. commit_obj: Commit, tree_sha: ObjectID
  4604. ) -> ObjectID | None:
  4605. # The filter receives: tree parent1 parent2...
  4606. cmd_input = tree_sha.hex()
  4607. for parent in commit_obj.parents:
  4608. cmd_input += " " + parent.hex()
  4609. result = run_filter(
  4610. parsed_args.commit_filter,
  4611. input_data=cmd_input.encode(),
  4612. extra_env={"GIT_COMMIT": commit_obj.id.hex()},
  4613. )
  4614. if result is None:
  4615. return None
  4616. output = result.decode().strip()
  4617. if not output:
  4618. return None # Skip commit
  4619. if valid_hexsha(output):
  4620. return ObjectID(output.encode())
  4621. return None
  4622. tag_name_filter = None
  4623. if parsed_args.tag_name_filter:
  4624. def tag_name_filter(tag_name: bytes) -> bytes:
  4625. result = run_filter(parsed_args.tag_name_filter, input_data=tag_name)
  4626. return result if result is not None else tag_name
  4627. # Open repo once
  4628. with Repo(".") as r:
  4629. # Check for refs/original if not forcing
  4630. if not parsed_args.force:
  4631. original_prefix = parsed_args.original.encode() + b"/"
  4632. for ref in r.refs.allkeys():
  4633. if ref.startswith(original_prefix):
  4634. logger.error("Cannot create a new backup.")
  4635. logger.error(
  4636. "A previous backup already exists in %s/",
  4637. parsed_args.original,
  4638. )
  4639. logger.error("Force overwriting the backup with -f")
  4640. print("Cannot create a new backup.")
  4641. print(
  4642. f"A previous backup already exists in {parsed_args.original}/"
  4643. )
  4644. print("Force overwriting the backup with -f")
  4645. return 1
  4646. try:
  4647. # Call porcelain.filter_branch with the repo object
  4648. result = porcelain.filter_branch(
  4649. r,
  4650. parsed_args.branch,
  4651. filter_message=filter_message,
  4652. tree_filter=tree_filter if parsed_args.tree_filter else None,
  4653. index_filter=index_filter if parsed_args.index_filter else None,
  4654. parent_filter=parent_filter if parsed_args.parent_filter else None,
  4655. commit_filter=commit_filter if parsed_args.commit_filter else None,
  4656. subdirectory_filter=parsed_args.subdirectory_filter,
  4657. prune_empty=parsed_args.prune_empty,
  4658. tag_name_filter=tag_name_filter
  4659. if parsed_args.tag_name_filter
  4660. else None,
  4661. force=parsed_args.force,
  4662. keep_original=True, # Always keep original with git
  4663. )
  4664. # Check if any filter failed
  4665. if filter_error:
  4666. logger.error("Filter command failed")
  4667. return 1
  4668. # Git filter-branch shows progress
  4669. if result:
  4670. logger.info(
  4671. "Rewrite %s (%d commits)", parsed_args.branch, len(result)
  4672. )
  4673. # Git shows: Ref 'refs/heads/branch' was rewritten
  4674. if parsed_args.branch != "HEAD":
  4675. ref_name = (
  4676. parsed_args.branch
  4677. if parsed_args.branch.startswith("refs/")
  4678. else f"refs/heads/{parsed_args.branch}"
  4679. )
  4680. logger.info("Ref '%s' was rewritten", ref_name)
  4681. return 0
  4682. except porcelain.Error as e:
  4683. logger.error("%s", e)
  4684. return 1
  4685. class cmd_lfs(Command):
  4686. """Git Large File Storage management."""
  4687. """Git LFS management commands."""
  4688. def run(self, argv: Sequence[str]) -> None:
  4689. """Execute the lfs command.
  4690. Args:
  4691. argv: Command line arguments
  4692. """
  4693. parser = argparse.ArgumentParser(prog="dulwich lfs")
  4694. subparsers = parser.add_subparsers(dest="subcommand", help="LFS subcommands")
  4695. # lfs init
  4696. subparsers.add_parser("init", help="Initialize Git LFS")
  4697. # lfs track
  4698. parser_track = subparsers.add_parser(
  4699. "track", help="Track file patterns with LFS"
  4700. )
  4701. parser_track.add_argument("patterns", nargs="*", help="File patterns to track")
  4702. # lfs untrack
  4703. parser_untrack = subparsers.add_parser(
  4704. "untrack", help="Untrack file patterns from LFS"
  4705. )
  4706. parser_untrack.add_argument(
  4707. "patterns", nargs="+", help="File patterns to untrack"
  4708. )
  4709. # lfs ls-files
  4710. parser_ls = subparsers.add_parser("ls-files", help="List LFS files")
  4711. parser_ls.add_argument("--ref", help="Git ref to check (defaults to HEAD)")
  4712. # lfs migrate
  4713. parser_migrate = subparsers.add_parser("migrate", help="Migrate files to LFS")
  4714. parser_migrate.add_argument("--include", nargs="+", help="Patterns to include")
  4715. parser_migrate.add_argument("--exclude", nargs="+", help="Patterns to exclude")
  4716. parser_migrate.add_argument(
  4717. "--everything", action="store_true", help="Migrate all files above 100MB"
  4718. )
  4719. # lfs pointer
  4720. parser_pointer = subparsers.add_parser("pointer", help="Check LFS pointers")
  4721. parser_pointer.add_argument(
  4722. "--check", nargs="*", dest="paths", help="Check if files are LFS pointers"
  4723. )
  4724. # lfs clean
  4725. parser_clean = subparsers.add_parser("clean", help="Clean file to LFS pointer")
  4726. parser_clean.add_argument("path", help="File path to clean")
  4727. # lfs smudge
  4728. parser_smudge = subparsers.add_parser(
  4729. "smudge", help="Smudge LFS pointer to content"
  4730. )
  4731. parser_smudge.add_argument(
  4732. "--stdin", action="store_true", help="Read pointer from stdin"
  4733. )
  4734. # lfs fetch
  4735. parser_fetch = subparsers.add_parser(
  4736. "fetch", help="Fetch LFS objects from remote"
  4737. )
  4738. parser_fetch.add_argument(
  4739. "--remote", default="origin", help="Remote to fetch from"
  4740. )
  4741. parser_fetch.add_argument("refs", nargs="*", help="Specific refs to fetch")
  4742. # lfs pull
  4743. parser_pull = subparsers.add_parser(
  4744. "pull", help="Pull LFS objects for current checkout"
  4745. )
  4746. parser_pull.add_argument(
  4747. "--remote", default="origin", help="Remote to pull from"
  4748. )
  4749. # lfs push
  4750. parser_push = subparsers.add_parser("push", help="Push LFS objects to remote")
  4751. parser_push.add_argument("--remote", default="origin", help="Remote to push to")
  4752. parser_push.add_argument("refs", nargs="*", help="Specific refs to push")
  4753. # lfs status
  4754. subparsers.add_parser("status", help="Show status of LFS files")
  4755. args = parser.parse_args(argv)
  4756. if args.subcommand == "init":
  4757. porcelain.lfs_init()
  4758. logger.info("Git LFS initialized.")
  4759. elif args.subcommand == "track":
  4760. if args.patterns:
  4761. tracked = porcelain.lfs_track(patterns=args.patterns)
  4762. logger.info("Tracking patterns:")
  4763. else:
  4764. tracked = porcelain.lfs_track()
  4765. logger.info("Currently tracked patterns:")
  4766. for pattern in tracked:
  4767. logger.info(" %s", pattern)
  4768. elif args.subcommand == "untrack":
  4769. tracked = porcelain.lfs_untrack(patterns=args.patterns)
  4770. logger.info("Remaining tracked patterns:")
  4771. for pattern in tracked:
  4772. logger.info(" %s", to_display_str(pattern))
  4773. elif args.subcommand == "ls-files":
  4774. files = porcelain.lfs_ls_files(ref=args.ref)
  4775. for path, oid, size in files:
  4776. logger.info(
  4777. "%s * %s (%s)",
  4778. to_display_str(oid[:12]),
  4779. to_display_str(path),
  4780. format_bytes(size),
  4781. )
  4782. elif args.subcommand == "migrate":
  4783. count = porcelain.lfs_migrate(
  4784. include=args.include, exclude=args.exclude, everything=args.everything
  4785. )
  4786. logger.info("Migrated %d file(s) to Git LFS.", count)
  4787. elif args.subcommand == "pointer":
  4788. if args.paths is not None:
  4789. results = porcelain.lfs_pointer_check(paths=args.paths or None)
  4790. for file_path, pointer in results.items():
  4791. if pointer:
  4792. logger.info(
  4793. "%s: LFS pointer (oid: %s, size: %s)",
  4794. to_display_str(file_path),
  4795. to_display_str(pointer.oid[:12]),
  4796. format_bytes(pointer.size),
  4797. )
  4798. else:
  4799. logger.warning(
  4800. "%s: Not an LFS pointer", to_display_str(file_path)
  4801. )
  4802. elif args.subcommand == "clean":
  4803. pointer = porcelain.lfs_clean(path=args.path)
  4804. sys.stdout.buffer.write(pointer)
  4805. elif args.subcommand == "smudge":
  4806. if args.stdin:
  4807. pointer_content = sys.stdin.buffer.read()
  4808. content = porcelain.lfs_smudge(pointer_content=pointer_content)
  4809. sys.stdout.buffer.write(content)
  4810. else:
  4811. logger.error("--stdin required for smudge command")
  4812. sys.exit(1)
  4813. elif args.subcommand == "fetch":
  4814. refs = args.refs or None
  4815. count = porcelain.lfs_fetch(remote=args.remote, refs=refs)
  4816. logger.info("Fetched %d LFS object(s).", count)
  4817. elif args.subcommand == "pull":
  4818. count = porcelain.lfs_pull(remote=args.remote)
  4819. logger.info("Pulled %d LFS object(s).", count)
  4820. elif args.subcommand == "push":
  4821. refs = args.refs or None
  4822. count = porcelain.lfs_push(remote=args.remote, refs=refs)
  4823. logger.info("Pushed %d LFS object(s).", count)
  4824. elif args.subcommand == "status":
  4825. status = porcelain.lfs_status()
  4826. if status["tracked"]:
  4827. logger.info("LFS tracked files: %d", len(status["tracked"]))
  4828. if status["missing"]:
  4829. logger.warning("\nMissing LFS objects:")
  4830. for file_path in status["missing"]:
  4831. logger.warning(" %s", to_display_str(file_path))
  4832. if status["not_staged"]:
  4833. logger.info("\nModified LFS files not staged:")
  4834. for file_path in status["not_staged"]:
  4835. logger.warning(" %s", to_display_str(file_path))
  4836. if not any(status.values()):
  4837. logger.info("No LFS files found.")
  4838. else:
  4839. parser.print_help()
  4840. sys.exit(1)
  4841. class cmd_help(Command):
  4842. """Display help information about git."""
  4843. def run(self, args: Sequence[str]) -> None:
  4844. """Execute the help command.
  4845. Args:
  4846. args: Command line arguments
  4847. """
  4848. parser = argparse.ArgumentParser()
  4849. parser.add_argument(
  4850. "-a",
  4851. "--all",
  4852. action="store_true",
  4853. help="List all commands.",
  4854. )
  4855. parsed_args = parser.parse_args(args)
  4856. if parsed_args.all:
  4857. logger.info("Available commands:")
  4858. for cmd in sorted(commands):
  4859. logger.info(" %s", cmd)
  4860. else:
  4861. logger.info(
  4862. "The dulwich command line tool is currently a very basic frontend for the\n"
  4863. "Dulwich python module. For full functionality, please see the API reference.\n"
  4864. "\n"
  4865. "For a list of supported commands, see 'dulwich help -a'."
  4866. )
  4867. class cmd_format_patch(Command):
  4868. """Prepare patches for e-mail submission."""
  4869. def run(self, args: Sequence[str]) -> None:
  4870. """Execute the format-patch command.
  4871. Args:
  4872. args: Command line arguments
  4873. """
  4874. parser = argparse.ArgumentParser()
  4875. parser.add_argument(
  4876. "committish",
  4877. nargs="?",
  4878. help="Commit or commit range (e.g., HEAD~3..HEAD or origin/master..HEAD)",
  4879. )
  4880. parser.add_argument(
  4881. "-n",
  4882. "--numbered",
  4883. type=int,
  4884. default=1,
  4885. help="Number of commits to format (default: 1)",
  4886. )
  4887. parser.add_argument(
  4888. "-o",
  4889. "--output-directory",
  4890. dest="outdir",
  4891. help="Output directory for patches",
  4892. )
  4893. parser.add_argument(
  4894. "--stdout",
  4895. action="store_true",
  4896. help="Output patches to stdout",
  4897. )
  4898. parsed_args = parser.parse_args(args)
  4899. # Parse committish using the new function
  4900. committish: ObjectID | tuple[ObjectID, ObjectID] | None = None
  4901. if parsed_args.committish:
  4902. with Repo(".") as r:
  4903. range_result = parse_commit_range(r, parsed_args.committish)
  4904. if range_result:
  4905. # Convert Commit objects to their SHAs
  4906. committish = (range_result[0].id, range_result[1].id)
  4907. else:
  4908. committish = ObjectID(
  4909. parsed_args.committish.encode()
  4910. if isinstance(parsed_args.committish, str)
  4911. else parsed_args.committish
  4912. )
  4913. filenames = porcelain.format_patch(
  4914. ".",
  4915. committish=committish,
  4916. outstream=sys.stdout,
  4917. outdir=parsed_args.outdir,
  4918. n=parsed_args.numbered,
  4919. stdout=parsed_args.stdout,
  4920. )
  4921. if not parsed_args.stdout:
  4922. for filename in filenames:
  4923. logger.info(filename)
  4924. class cmd_mailsplit(Command):
  4925. """Split mbox or Maildir into individual message files."""
  4926. def run(self, args: Sequence[str]) -> None:
  4927. """Execute the mailsplit command.
  4928. Args:
  4929. args: Command line arguments
  4930. """
  4931. parser = argparse.ArgumentParser()
  4932. parser.add_argument(
  4933. "mbox",
  4934. nargs="?",
  4935. help="Path to mbox file or Maildir. If not specified, reads from stdin.",
  4936. )
  4937. parser.add_argument(
  4938. "-o",
  4939. "--output-directory",
  4940. dest="output_dir",
  4941. required=True,
  4942. help="Directory in which to place the individual messages",
  4943. )
  4944. parser.add_argument(
  4945. "-b",
  4946. action="store_true",
  4947. dest="single_mail",
  4948. help="If any file doesn't begin with a From line, assume it is a single mail message",
  4949. )
  4950. parser.add_argument(
  4951. "-d",
  4952. dest="precision",
  4953. type=int,
  4954. default=4,
  4955. help="Number of digits for generated filenames (default: 4)",
  4956. )
  4957. parser.add_argument(
  4958. "-f",
  4959. dest="start_number",
  4960. type=int,
  4961. default=1,
  4962. help="Skip the first <nn> numbers (default: 1)",
  4963. )
  4964. parser.add_argument(
  4965. "--keep-cr",
  4966. action="store_true",
  4967. help="Do not remove \\r from lines ending with \\r\\n",
  4968. )
  4969. parser.add_argument(
  4970. "--mboxrd",
  4971. action="store_true",
  4972. help='Input is of the "mboxrd" format and "^>+From " line escaping is reversed',
  4973. )
  4974. parsed_args = parser.parse_args(args)
  4975. # Determine if input is a Maildir
  4976. is_maildir = False
  4977. if parsed_args.mbox:
  4978. input_path = Path(parsed_args.mbox)
  4979. if input_path.is_dir():
  4980. # Check if it's a Maildir (has cur, tmp, new subdirectories)
  4981. if (
  4982. (input_path / "cur").exists()
  4983. and (input_path / "tmp").exists()
  4984. and (input_path / "new").exists()
  4985. ):
  4986. is_maildir = True
  4987. else:
  4988. input_path = None
  4989. # Call porcelain function
  4990. output_files = porcelain.mailsplit(
  4991. input_path=input_path,
  4992. output_dir=parsed_args.output_dir,
  4993. start_number=parsed_args.start_number,
  4994. precision=parsed_args.precision,
  4995. keep_cr=parsed_args.keep_cr,
  4996. mboxrd=parsed_args.mboxrd,
  4997. is_maildir=is_maildir,
  4998. )
  4999. # Print information about the split
  5000. logger.info(
  5001. "Split %d messages into %s", len(output_files), parsed_args.output_dir
  5002. )
  5003. class cmd_mailinfo(Command):
  5004. """Extract patch information from an email message."""
  5005. def run(self, args: Sequence[str]) -> None:
  5006. """Execute the mailinfo command.
  5007. Args:
  5008. args: Command line arguments
  5009. """
  5010. parser = argparse.ArgumentParser()
  5011. parser.add_argument(
  5012. "msg",
  5013. help="File to write commit message",
  5014. )
  5015. parser.add_argument(
  5016. "patch",
  5017. help="File to write patch content",
  5018. )
  5019. parser.add_argument(
  5020. "mail",
  5021. nargs="?",
  5022. help="Path to email file. If not specified, reads from stdin.",
  5023. )
  5024. parser.add_argument(
  5025. "-k",
  5026. action="store_true",
  5027. dest="keep_subject",
  5028. help="Pass -k flag to git mailinfo (keeps [PATCH] and other subject tags)",
  5029. )
  5030. parser.add_argument(
  5031. "-b",
  5032. action="store_true",
  5033. dest="keep_non_patch",
  5034. help="Pass -b flag to git mailinfo (only strip [PATCH] tags)",
  5035. )
  5036. parser.add_argument(
  5037. "--encoding",
  5038. dest="encoding",
  5039. help="Character encoding to use (default: detect from message)",
  5040. )
  5041. parser.add_argument(
  5042. "--scissors",
  5043. action="store_true",
  5044. help="Remove everything before scissors line",
  5045. )
  5046. parser.add_argument(
  5047. "-m",
  5048. "--message-id",
  5049. action="store_true",
  5050. dest="message_id",
  5051. help="Copy Message-ID to the end of the commit message",
  5052. )
  5053. parsed_args = parser.parse_args(args)
  5054. # Call porcelain function
  5055. result = porcelain.mailinfo(
  5056. input_path=parsed_args.mail,
  5057. msg_file=parsed_args.msg,
  5058. patch_file=parsed_args.patch,
  5059. keep_subject=parsed_args.keep_subject,
  5060. keep_non_patch=parsed_args.keep_non_patch,
  5061. encoding=parsed_args.encoding,
  5062. scissors=parsed_args.scissors,
  5063. message_id=parsed_args.message_id,
  5064. )
  5065. # Print author info to stdout (as git mailinfo does)
  5066. print(f"Author: {result.author_name}")
  5067. print(f"Email: {result.author_email}")
  5068. print(f"Subject: {result.subject}")
  5069. if result.author_date:
  5070. print(f"Date: {result.author_date}")
  5071. class cmd_bundle(Command):
  5072. """Create, unpack, and manipulate bundle files."""
  5073. def run(self, args: Sequence[str]) -> int:
  5074. """Execute the bundle command.
  5075. Args:
  5076. args: Command line arguments
  5077. """
  5078. if not args:
  5079. logger.error("Usage: bundle <create|verify|list-heads|unbundle> <options>")
  5080. return 1
  5081. subcommand = args[0]
  5082. subargs = args[1:]
  5083. if subcommand == "create":
  5084. return self._create(subargs)
  5085. elif subcommand == "verify":
  5086. return self._verify(subargs)
  5087. elif subcommand == "list-heads":
  5088. return self._list_heads(subargs)
  5089. elif subcommand == "unbundle":
  5090. return self._unbundle(subargs)
  5091. else:
  5092. logger.error("Unknown bundle subcommand: %s", subcommand)
  5093. return 1
  5094. def _create(self, args: Sequence[str]) -> int:
  5095. parser = argparse.ArgumentParser(prog="bundle create")
  5096. parser.add_argument(
  5097. "-q", "--quiet", action="store_true", help="Suppress progress"
  5098. )
  5099. parser.add_argument("--progress", action="store_true", help="Show progress")
  5100. parser.add_argument(
  5101. "--version", type=int, choices=[2, 3], help="Bundle version"
  5102. )
  5103. parser.add_argument("--all", action="store_true", help="Include all refs")
  5104. parser.add_argument("--stdin", action="store_true", help="Read refs from stdin")
  5105. parser.add_argument("file", help="Output bundle file (use - for stdout)")
  5106. parser.add_argument("refs", nargs="*", help="References or rev-list args")
  5107. parsed_args = parser.parse_args(args)
  5108. repo = Repo(".")
  5109. progress = None
  5110. if parsed_args.progress and not parsed_args.quiet:
  5111. def progress(*args: str | int) -> None:
  5112. # Handle both progress(msg) and progress(count, msg) signatures
  5113. if len(args) == 1:
  5114. msg = args[0]
  5115. elif len(args) == 2:
  5116. _count, msg = args
  5117. else:
  5118. msg = str(args)
  5119. # Convert bytes to string if needed
  5120. if isinstance(msg, bytes):
  5121. msg = msg.decode("utf-8", "replace")
  5122. logger.error("%s", msg)
  5123. refs_to_include: list[Ref] = []
  5124. prerequisites = []
  5125. if parsed_args.all:
  5126. refs_to_include = list(repo.refs.keys())
  5127. elif parsed_args.stdin:
  5128. for line in sys.stdin:
  5129. ref = line.strip().encode("utf-8")
  5130. if ref:
  5131. refs_to_include.append(Ref(ref))
  5132. elif parsed_args.refs:
  5133. for ref_arg in parsed_args.refs:
  5134. if ".." in ref_arg:
  5135. range_result = parse_commit_range(repo, ref_arg)
  5136. if range_result:
  5137. start_commit, _end_commit = range_result
  5138. prerequisites.append(start_commit.id)
  5139. # For ranges like A..B, we need to include B if it's a ref
  5140. # Split the range to get the end part
  5141. end_part = ref_arg.split("..")[1]
  5142. if end_part: # Not empty (not "A..")
  5143. end_ref = Ref(end_part.encode("utf-8"))
  5144. if end_ref in repo.refs:
  5145. refs_to_include.append(end_ref)
  5146. else:
  5147. sha = repo.refs[Ref(ref_arg.encode("utf-8"))]
  5148. refs_to_include.append(Ref(ref_arg.encode("utf-8")))
  5149. else:
  5150. if ref_arg.startswith("^"):
  5151. sha = repo.refs[Ref(ref_arg[1:].encode("utf-8"))]
  5152. prerequisites.append(sha)
  5153. else:
  5154. sha = repo.refs[Ref(ref_arg.encode("utf-8"))]
  5155. refs_to_include.append(Ref(ref_arg.encode("utf-8")))
  5156. else:
  5157. logger.error("No refs specified. Use --all, --stdin, or specify refs")
  5158. return 1
  5159. if not refs_to_include:
  5160. logger.error("fatal: Refusing to create empty bundle.")
  5161. return 1
  5162. bundle = create_bundle_from_repo(
  5163. repo,
  5164. refs=refs_to_include,
  5165. prerequisites=prerequisites,
  5166. version=parsed_args.version,
  5167. progress=progress,
  5168. )
  5169. if parsed_args.file == "-":
  5170. write_bundle(sys.stdout.buffer, bundle)
  5171. else:
  5172. with open(parsed_args.file, "wb") as f:
  5173. write_bundle(f, bundle)
  5174. return 0
  5175. def _verify(self, args: Sequence[str]) -> int:
  5176. parser = argparse.ArgumentParser(prog="bundle verify")
  5177. parser.add_argument(
  5178. "-q", "--quiet", action="store_true", help="Suppress output"
  5179. )
  5180. parser.add_argument("file", help="Bundle file to verify (use - for stdin)")
  5181. parsed_args = parser.parse_args(args)
  5182. repo = Repo(".")
  5183. def verify_bundle(bundle: Bundle) -> int:
  5184. missing_prereqs = []
  5185. for prereq_sha, comment in bundle.prerequisites:
  5186. try:
  5187. repo.object_store[prereq_sha]
  5188. except KeyError:
  5189. missing_prereqs.append(prereq_sha)
  5190. if missing_prereqs:
  5191. if not parsed_args.quiet:
  5192. logger.info("The bundle requires these prerequisite commits:")
  5193. for sha in missing_prereqs:
  5194. logger.info(" %s", sha.decode())
  5195. return 1
  5196. else:
  5197. if not parsed_args.quiet:
  5198. logger.info(
  5199. "The bundle is valid and can be applied to the current repository"
  5200. )
  5201. return 0
  5202. if parsed_args.file == "-":
  5203. bundle = read_bundle(sys.stdin.buffer)
  5204. return verify_bundle(bundle)
  5205. else:
  5206. with open(parsed_args.file, "rb") as f:
  5207. bundle = read_bundle(f)
  5208. return verify_bundle(bundle)
  5209. def _list_heads(self, args: Sequence[str]) -> int:
  5210. parser = argparse.ArgumentParser(prog="bundle list-heads")
  5211. parser.add_argument("file", help="Bundle file (use - for stdin)")
  5212. parser.add_argument("refnames", nargs="*", help="Only show these refs")
  5213. parsed_args = parser.parse_args(args)
  5214. def list_heads(bundle: Bundle) -> None:
  5215. for ref, sha in bundle.references.items():
  5216. if not parsed_args.refnames or ref.decode() in parsed_args.refnames:
  5217. logger.info("%s %s", sha.decode(), ref.decode())
  5218. if parsed_args.file == "-":
  5219. bundle = read_bundle(sys.stdin.buffer)
  5220. list_heads(bundle)
  5221. else:
  5222. with open(parsed_args.file, "rb") as f:
  5223. bundle = read_bundle(f)
  5224. list_heads(bundle)
  5225. return 0
  5226. def _unbundle(self, args: Sequence[str]) -> int:
  5227. parser = argparse.ArgumentParser(prog="bundle unbundle")
  5228. parser.add_argument("--progress", action="store_true", help="Show progress")
  5229. parser.add_argument("file", help="Bundle file (use - for stdin)")
  5230. parser.add_argument("refnames", nargs="*", help="Only unbundle these refs")
  5231. parsed_args = parser.parse_args(args)
  5232. repo = Repo(".")
  5233. progress = None
  5234. if parsed_args.progress:
  5235. def progress(*args: str | int | bytes) -> None:
  5236. # Handle both progress(msg) and progress(count, msg) signatures
  5237. if len(args) == 1:
  5238. msg = args[0]
  5239. elif len(args) == 2:
  5240. _count, msg = args
  5241. else:
  5242. msg = str(args)
  5243. # Convert bytes to string if needed
  5244. if isinstance(msg, bytes):
  5245. msg = msg.decode("utf-8", "replace")
  5246. elif not isinstance(msg, str):
  5247. msg = str(msg)
  5248. logger.error("%s", msg)
  5249. if parsed_args.file == "-":
  5250. bundle = read_bundle(sys.stdin.buffer)
  5251. # Process the bundle while file is still available via stdin
  5252. bundle.store_objects(repo.object_store, progress=progress)
  5253. else:
  5254. # Keep the file open during bundle processing
  5255. with open(parsed_args.file, "rb") as f:
  5256. bundle = read_bundle(f)
  5257. # Process pack data while file is still open
  5258. bundle.store_objects(repo.object_store, progress=progress)
  5259. for ref, sha in bundle.references.items():
  5260. if not parsed_args.refnames or ref.decode() in parsed_args.refnames:
  5261. logger.info(ref.decode())
  5262. return 0
  5263. class cmd_worktree_add(Command):
  5264. """Create a new worktree."""
  5265. """Add a new worktree to the repository."""
  5266. def run(self, args: Sequence[str]) -> int | None:
  5267. """Execute the worktree-add command.
  5268. Args:
  5269. args: Command line arguments
  5270. """
  5271. parser = argparse.ArgumentParser(
  5272. description="Add a new worktree", prog="dulwich worktree add"
  5273. )
  5274. parser.add_argument("path", help="Path for the new worktree")
  5275. parser.add_argument("committish", nargs="?", help="Commit-ish to checkout")
  5276. parser.add_argument("-b", "--create-branch", help="Create a new branch")
  5277. parser.add_argument(
  5278. "-B", "--force-create-branch", help="Create or reset a branch"
  5279. )
  5280. parser.add_argument(
  5281. "--detach", action="store_true", help="Detach HEAD in new worktree"
  5282. )
  5283. parser.add_argument("--force", action="store_true", help="Force creation")
  5284. parsed_args = parser.parse_args(args)
  5285. from dulwich import porcelain
  5286. branch = None
  5287. commit = None
  5288. if parsed_args.create_branch or parsed_args.force_create_branch:
  5289. branch = (
  5290. parsed_args.create_branch or parsed_args.force_create_branch
  5291. ).encode()
  5292. elif parsed_args.committish and not parsed_args.detach:
  5293. # If committish is provided and not detaching, treat as branch
  5294. branch = parsed_args.committish.encode()
  5295. elif parsed_args.committish:
  5296. # If committish is provided and detaching, treat as commit
  5297. commit = parsed_args.committish.encode()
  5298. worktree_path = porcelain.worktree_add(
  5299. repo=".",
  5300. path=parsed_args.path,
  5301. branch=branch,
  5302. commit=commit,
  5303. detach=parsed_args.detach,
  5304. force=parsed_args.force or bool(parsed_args.force_create_branch),
  5305. )
  5306. logger.info("Worktree added: %s", worktree_path)
  5307. return 0
  5308. class cmd_worktree_list(Command):
  5309. """List worktrees."""
  5310. """List details of each worktree."""
  5311. def run(self, args: Sequence[str]) -> int | None:
  5312. """Execute the worktree-list command.
  5313. Args:
  5314. args: Command line arguments
  5315. """
  5316. parser = argparse.ArgumentParser(
  5317. description="List worktrees", prog="dulwich worktree list"
  5318. )
  5319. parser.add_argument(
  5320. "-v", "--verbose", action="store_true", help="Show additional information"
  5321. )
  5322. parser.add_argument(
  5323. "--porcelain", action="store_true", help="Machine-readable output"
  5324. )
  5325. parsed_args = parser.parse_args(args)
  5326. from dulwich import porcelain
  5327. worktrees = porcelain.worktree_list(repo=".")
  5328. for wt in worktrees:
  5329. path = wt.path
  5330. if wt.bare:
  5331. status = "(bare)"
  5332. elif wt.detached:
  5333. status = (
  5334. f"(detached HEAD {wt.head[:7].decode() if wt.head else 'unknown'})"
  5335. )
  5336. elif wt.branch:
  5337. branch_name = wt.branch.decode().replace("refs/heads/", "")
  5338. status = f"[{branch_name}]"
  5339. else:
  5340. status = "(unknown)"
  5341. if parsed_args.porcelain:
  5342. locked = "locked" if wt.locked else "unlocked"
  5343. prunable = "prunable" if wt.prunable else "unprunable"
  5344. logger.info(
  5345. "%s %s %s %s %s",
  5346. path,
  5347. wt.head.decode() if wt.head else "unknown",
  5348. status,
  5349. locked,
  5350. prunable,
  5351. )
  5352. else:
  5353. line = f"{path} {status}"
  5354. if wt.locked:
  5355. line += " locked"
  5356. if wt.prunable:
  5357. line += " prunable"
  5358. logger.info(line)
  5359. return 0
  5360. class cmd_worktree_remove(Command):
  5361. """Remove a worktree."""
  5362. """Remove a worktree."""
  5363. def run(self, args: Sequence[str]) -> int | None:
  5364. """Execute the worktree-remove command.
  5365. Args:
  5366. args: Command line arguments
  5367. """
  5368. parser = argparse.ArgumentParser(
  5369. description="Remove a worktree", prog="dulwich worktree remove"
  5370. )
  5371. parser.add_argument("worktree", help="Path to worktree to remove")
  5372. parser.add_argument("--force", action="store_true", help="Force removal")
  5373. parsed_args = parser.parse_args(args)
  5374. from dulwich import porcelain
  5375. porcelain.worktree_remove(
  5376. repo=".", path=parsed_args.worktree, force=parsed_args.force
  5377. )
  5378. logger.info("Worktree removed: %s", parsed_args.worktree)
  5379. return 0
  5380. class cmd_worktree_prune(Command):
  5381. """Prune worktree information."""
  5382. """Prune worktree information."""
  5383. def run(self, args: Sequence[str]) -> int | None:
  5384. """Execute the worktree-prune command.
  5385. Args:
  5386. args: Command line arguments
  5387. """
  5388. parser = argparse.ArgumentParser(
  5389. description="Prune worktree information", prog="dulwich worktree prune"
  5390. )
  5391. parser.add_argument(
  5392. "--dry-run", action="store_true", help="Do not remove anything"
  5393. )
  5394. parser.add_argument(
  5395. "-v", "--verbose", action="store_true", help="Report all removals"
  5396. )
  5397. parser.add_argument(
  5398. "--expire", type=int, help="Expire worktrees older than time (seconds)"
  5399. )
  5400. parsed_args = parser.parse_args(args)
  5401. from dulwich import porcelain
  5402. pruned = porcelain.worktree_prune(
  5403. repo=".", dry_run=parsed_args.dry_run, expire=parsed_args.expire
  5404. )
  5405. if pruned:
  5406. if parsed_args.dry_run:
  5407. logger.info("Would prune worktrees:")
  5408. elif parsed_args.verbose:
  5409. logger.info("Pruned worktrees:")
  5410. for wt_id in pruned:
  5411. logger.info(" %s", wt_id)
  5412. elif parsed_args.verbose:
  5413. logger.info("No worktrees to prune")
  5414. return 0
  5415. class cmd_worktree_lock(Command):
  5416. """Lock a worktree to prevent it from being pruned."""
  5417. """Lock a worktree."""
  5418. def run(self, args: Sequence[str]) -> int | None:
  5419. """Execute the worktree-lock command.
  5420. Args:
  5421. args: Command line arguments
  5422. """
  5423. parser = argparse.ArgumentParser(
  5424. description="Lock a worktree", prog="dulwich worktree lock"
  5425. )
  5426. parser.add_argument("worktree", help="Path to worktree to lock")
  5427. parser.add_argument("--reason", help="Reason for locking")
  5428. parsed_args = parser.parse_args(args)
  5429. from dulwich import porcelain
  5430. porcelain.worktree_lock(
  5431. repo=".", path=parsed_args.worktree, reason=parsed_args.reason
  5432. )
  5433. logger.info("Worktree locked: %s", parsed_args.worktree)
  5434. return 0
  5435. class cmd_worktree_unlock(Command):
  5436. """Unlock a locked worktree."""
  5437. """Unlock a worktree."""
  5438. def run(self, args: Sequence[str]) -> int | None:
  5439. """Execute the worktree-unlock command.
  5440. Args:
  5441. args: Command line arguments
  5442. """
  5443. parser = argparse.ArgumentParser(
  5444. description="Unlock a worktree", prog="dulwich worktree unlock"
  5445. )
  5446. parser.add_argument("worktree", help="Path to worktree to unlock")
  5447. parsed_args = parser.parse_args(args)
  5448. from dulwich import porcelain
  5449. porcelain.worktree_unlock(repo=".", path=parsed_args.worktree)
  5450. logger.info("Worktree unlocked: %s", parsed_args.worktree)
  5451. return 0
  5452. class cmd_worktree_move(Command):
  5453. """Move a worktree to a new location."""
  5454. """Move a worktree."""
  5455. def run(self, args: Sequence[str]) -> int | None:
  5456. """Execute the worktree-move command.
  5457. Args:
  5458. args: Command line arguments
  5459. """
  5460. parser = argparse.ArgumentParser(
  5461. description="Move a worktree", prog="dulwich worktree move"
  5462. )
  5463. parser.add_argument("worktree", help="Path to worktree to move")
  5464. parser.add_argument("new_path", help="New path for the worktree")
  5465. parsed_args = parser.parse_args(args)
  5466. from dulwich import porcelain
  5467. porcelain.worktree_move(
  5468. repo=".", old_path=parsed_args.worktree, new_path=parsed_args.new_path
  5469. )
  5470. logger.info(
  5471. "Worktree moved: %s -> %s", parsed_args.worktree, parsed_args.new_path
  5472. )
  5473. return 0
  5474. class cmd_worktree_repair(Command):
  5475. """Repair worktree administrative files."""
  5476. """Repair worktree administrative files."""
  5477. def run(self, args: Sequence[str]) -> int | None:
  5478. """Execute the worktree-repair command.
  5479. Args:
  5480. args: Command line arguments
  5481. """
  5482. parser = argparse.ArgumentParser(
  5483. description="Repair worktree administrative files",
  5484. prog="dulwich worktree repair",
  5485. )
  5486. parser.add_argument(
  5487. "path",
  5488. nargs="*",
  5489. help="Paths to worktrees to repair (if not specified, repairs all)",
  5490. )
  5491. parsed_args = parser.parse_args(args)
  5492. from dulwich import porcelain
  5493. paths = parsed_args.path if parsed_args.path else None
  5494. repaired = porcelain.worktree_repair(repo=".", paths=paths)
  5495. if repaired:
  5496. for path in repaired:
  5497. logger.info("Repaired worktree: %s", path)
  5498. else:
  5499. logger.info("No worktrees needed repair")
  5500. return 0
  5501. class cmd_worktree(SuperCommand):
  5502. """Manage multiple working trees."""
  5503. """Manage multiple working trees."""
  5504. subcommands: ClassVar[dict[str, type[Command]]] = {
  5505. "add": cmd_worktree_add,
  5506. "list": cmd_worktree_list,
  5507. "remove": cmd_worktree_remove,
  5508. "prune": cmd_worktree_prune,
  5509. "lock": cmd_worktree_lock,
  5510. "unlock": cmd_worktree_unlock,
  5511. "move": cmd_worktree_move,
  5512. "repair": cmd_worktree_repair,
  5513. }
  5514. default_command = cmd_worktree_list
  5515. class cmd_rerere(Command):
  5516. """Record and reuse recorded conflict resolutions."""
  5517. def run(self, args: Sequence[str]) -> None:
  5518. """Execute the rerere command.
  5519. Args:
  5520. args: Command line arguments
  5521. """
  5522. parser = argparse.ArgumentParser()
  5523. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  5524. parser.add_argument(
  5525. "subcommand",
  5526. nargs="?",
  5527. default=None,
  5528. choices=["status", "diff", "forget", "clear", "gc"],
  5529. help="Subcommand to execute (default: record conflicts)",
  5530. )
  5531. parser.add_argument(
  5532. "pathspec", nargs="?", help="Path specification (for forget subcommand)"
  5533. )
  5534. parser.add_argument(
  5535. "--max-age-days",
  5536. type=int,
  5537. default=60,
  5538. help="Maximum age in days for gc (default: 60)",
  5539. )
  5540. parsed_args = parser.parse_args(args)
  5541. if parsed_args.subcommand is None:
  5542. # Record current conflicts
  5543. recorded, resolved = porcelain.rerere(parsed_args.gitdir)
  5544. if not recorded:
  5545. sys.stdout.write("No conflicts to record.\n")
  5546. else:
  5547. for path, conflict_id in recorded:
  5548. sys.stdout.write(
  5549. f"Recorded resolution for {path.decode('utf-8')}: {conflict_id}\n"
  5550. )
  5551. if resolved:
  5552. sys.stdout.write("\nAutomatically resolved:\n")
  5553. for path in resolved:
  5554. sys.stdout.write(f" {path.decode('utf-8')}\n")
  5555. elif parsed_args.subcommand == "status":
  5556. status_list = porcelain.rerere_status(parsed_args.gitdir)
  5557. if not status_list:
  5558. sys.stdout.write("No recorded resolutions.\n")
  5559. else:
  5560. for conflict_id, has_resolution in status_list:
  5561. status = "resolved" if has_resolution else "unresolved"
  5562. sys.stdout.write(f"{conflict_id}\t{status}\n")
  5563. elif parsed_args.subcommand == "diff":
  5564. diff_list = porcelain.rerere_diff(parsed_args.gitdir)
  5565. if not diff_list:
  5566. sys.stdout.write("No recorded conflicts.\n")
  5567. else:
  5568. for conflict_id, preimage, postimage in diff_list:
  5569. sys.stdout.write(f"--- {conflict_id} (preimage)\n")
  5570. sys.stdout.buffer.write(preimage)
  5571. sys.stdout.write("\n")
  5572. if postimage:
  5573. sys.stdout.write(f"+++ {conflict_id} (postimage)\n")
  5574. sys.stdout.buffer.write(postimage)
  5575. sys.stdout.write("\n")
  5576. elif parsed_args.subcommand == "forget":
  5577. porcelain.rerere_forget(parsed_args.gitdir, parsed_args.pathspec)
  5578. if parsed_args.pathspec:
  5579. sys.stdout.write(f"Forgot resolution for {parsed_args.pathspec}\n")
  5580. else:
  5581. sys.stdout.write("Forgot all resolutions\n")
  5582. elif parsed_args.subcommand == "clear":
  5583. porcelain.rerere_clear(parsed_args.gitdir)
  5584. sys.stdout.write("Cleared all rerere resolutions\n")
  5585. elif parsed_args.subcommand == "gc":
  5586. porcelain.rerere_gc(parsed_args.gitdir, parsed_args.max_age_days)
  5587. sys.stdout.write(
  5588. f"Cleaned up resolutions older than {parsed_args.max_age_days} days\n"
  5589. )
  5590. commands = {
  5591. "add": cmd_add,
  5592. "annotate": cmd_annotate,
  5593. "archive": cmd_archive,
  5594. "bisect": cmd_bisect,
  5595. "blame": cmd_blame,
  5596. "branch": cmd_branch,
  5597. "bundle": cmd_bundle,
  5598. "check-ignore": cmd_check_ignore,
  5599. "check-mailmap": cmd_check_mailmap,
  5600. "checkout": cmd_checkout,
  5601. "cherry": cmd_cherry,
  5602. "cherry-pick": cmd_cherry_pick,
  5603. "clone": cmd_clone,
  5604. "column": cmd_column,
  5605. "commit": cmd_commit,
  5606. "commit-tree": cmd_commit_tree,
  5607. "config": cmd_config,
  5608. "count-objects": cmd_count_objects,
  5609. "describe": cmd_describe,
  5610. "diagnose": cmd_diagnose,
  5611. "daemon": cmd_daemon,
  5612. "diff": cmd_diff,
  5613. "diff-tree": cmd_diff_tree,
  5614. "dump-pack": cmd_dump_pack,
  5615. "dump-index": cmd_dump_index,
  5616. "fetch-pack": cmd_fetch_pack,
  5617. "fetch": cmd_fetch,
  5618. "filter-branch": cmd_filter_branch,
  5619. "for-each-ref": cmd_for_each_ref,
  5620. "format-patch": cmd_format_patch,
  5621. "fsck": cmd_fsck,
  5622. "gc": cmd_gc,
  5623. "grep": cmd_grep,
  5624. "help": cmd_help,
  5625. "init": cmd_init,
  5626. "interpret-trailers": cmd_interpret_trailers,
  5627. "lfs": cmd_lfs,
  5628. "log": cmd_log,
  5629. "ls-files": cmd_ls_files,
  5630. "ls-remote": cmd_ls_remote,
  5631. "ls-tree": cmd_ls_tree,
  5632. "maintenance": cmd_maintenance,
  5633. "mailinfo": cmd_mailinfo,
  5634. "mailsplit": cmd_mailsplit,
  5635. "merge": cmd_merge,
  5636. "merge-base": cmd_merge_base,
  5637. "merge-tree": cmd_merge_tree,
  5638. "notes": cmd_notes,
  5639. "pack-objects": cmd_pack_objects,
  5640. "pack-refs": cmd_pack_refs,
  5641. "prune": cmd_prune,
  5642. "pull": cmd_pull,
  5643. "push": cmd_push,
  5644. "rebase": cmd_rebase,
  5645. "receive-pack": cmd_receive_pack,
  5646. "reflog": cmd_reflog,
  5647. "rerere": cmd_rerere,
  5648. "remote": cmd_remote,
  5649. "repack": cmd_repack,
  5650. "replace": cmd_replace,
  5651. "reset": cmd_reset,
  5652. "restore": cmd_restore,
  5653. "revert": cmd_revert,
  5654. "rev-list": cmd_rev_list,
  5655. "rm": cmd_rm,
  5656. "mv": cmd_mv,
  5657. "show": cmd_show,
  5658. "show-branch": cmd_show_branch,
  5659. "show-ref": cmd_show_ref,
  5660. "stash": cmd_stash,
  5661. "status": cmd_status,
  5662. "stripspace": cmd_stripspace,
  5663. "shortlog": cmd_shortlog,
  5664. "switch": cmd_switch,
  5665. "symbolic-ref": cmd_symbolic_ref,
  5666. "submodule": cmd_submodule,
  5667. "tag": cmd_tag,
  5668. "unpack-objects": cmd_unpack_objects,
  5669. "update-server-info": cmd_update_server_info,
  5670. "upload-pack": cmd_upload_pack,
  5671. "var": cmd_var,
  5672. "verify-commit": cmd_verify_commit,
  5673. "verify-tag": cmd_verify_tag,
  5674. "web-daemon": cmd_web_daemon,
  5675. "worktree": cmd_worktree,
  5676. "write-tree": cmd_write_tree,
  5677. }
  5678. def main(argv: Sequence[str] | None = None) -> int | None:
  5679. """Main entry point for the Dulwich CLI.
  5680. Args:
  5681. argv: Command line arguments (defaults to sys.argv[1:])
  5682. Returns:
  5683. Exit code or None
  5684. """
  5685. # Wrap stdout and stderr to respect GIT_FLUSH environment variable
  5686. sys.stdout = AutoFlushTextIOWrapper.env(sys.stdout)
  5687. sys.stderr = AutoFlushTextIOWrapper.env(sys.stderr)
  5688. if argv is None:
  5689. argv = sys.argv[1:]
  5690. # Parse only the global options and command, stop at first positional
  5691. parser = argparse.ArgumentParser(
  5692. prog="dulwich",
  5693. description="Simple command-line interface to Dulwich",
  5694. add_help=False, # We'll handle help ourselves
  5695. )
  5696. parser.add_argument("--no-pager", action="store_true", help="Disable pager")
  5697. parser.add_argument("--pager", action="store_true", help="Force enable pager")
  5698. parser.add_argument("--help", "-h", action="store_true", help="Show help")
  5699. # Parse known args to separate global options from command args
  5700. global_args, remaining = parser.parse_known_args(argv)
  5701. # Apply global pager settings
  5702. if global_args.no_pager:
  5703. disable_pager()
  5704. elif global_args.pager:
  5705. enable_pager()
  5706. # Handle help
  5707. if global_args.help or not remaining:
  5708. parser = argparse.ArgumentParser(
  5709. prog="dulwich", description="Simple command-line interface to Dulwich"
  5710. )
  5711. parser.add_argument("--no-pager", action="store_true", help="Disable pager")
  5712. parser.add_argument("--pager", action="store_true", help="Force enable pager")
  5713. parser.add_argument(
  5714. "command",
  5715. nargs="?",
  5716. help=f"Command to run. Available: {', '.join(sorted(commands.keys()))}",
  5717. )
  5718. parser.print_help()
  5719. return 1
  5720. # Try to configure from GIT_TRACE, fall back to default if it fails
  5721. if not _configure_logging_from_trace():
  5722. logging.basicConfig(
  5723. level=logging.INFO,
  5724. format="%(message)s",
  5725. )
  5726. # First remaining arg is the command
  5727. cmd = remaining[0]
  5728. cmd_args = remaining[1:]
  5729. try:
  5730. cmd_kls = commands[cmd]
  5731. except KeyError:
  5732. logging.fatal("No such subcommand: %s", cmd)
  5733. return 1
  5734. # TODO(jelmer): Return non-0 on errors
  5735. return cmd_kls().run(cmd_args)
  5736. def _main() -> None:
  5737. if "DULWICH_PDB" in os.environ and getattr(signal, "SIGQUIT", None):
  5738. signal.signal(signal.SIGQUIT, signal_quit) # type: ignore[attr-defined,unused-ignore]
  5739. signal.signal(signal.SIGINT, signal_int)
  5740. sys.exit(main())
  5741. if __name__ == "__main__":
  5742. _main()