test_porcelain.py 402 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010
  1. # test_porcelain.py -- porcelain tests
  2. # Copyright (C) 2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Tests for dulwich.porcelain."""
  22. import contextlib
  23. import os
  24. import platform
  25. import re
  26. import shutil
  27. import stat
  28. import subprocess
  29. import sys
  30. import tarfile
  31. import tempfile
  32. import threading
  33. import time
  34. from io import BytesIO, StringIO
  35. from unittest import skipIf
  36. from dulwich import porcelain
  37. from dulwich.client import SendPackResult
  38. from dulwich.diff_tree import tree_changes
  39. from dulwich.errors import CommitError
  40. from dulwich.object_store import DEFAULT_TEMPFILE_GRACE_PERIOD
  41. from dulwich.objects import ZERO_SHA, Blob, Commit, Tag, Tree
  42. from dulwich.porcelain import (
  43. CheckoutError, # Hypothetical or real error class
  44. CountObjectsResult,
  45. add,
  46. commit,
  47. )
  48. from dulwich.repo import NoIndexPresent, Repo
  49. from dulwich.server import DictBackend
  50. from dulwich.tests.utils import build_commit_graph, make_commit, make_object
  51. from dulwich.web import make_server, make_wsgi_chain
  52. from . import TestCase
  53. try:
  54. import gpg
  55. except ImportError:
  56. gpg = None
  57. def flat_walk_dir(dir_to_walk):
  58. for dirpath, _, filenames in os.walk(dir_to_walk):
  59. rel_dirpath = os.path.relpath(dirpath, dir_to_walk)
  60. if not dirpath == dir_to_walk:
  61. yield rel_dirpath
  62. for filename in filenames:
  63. if dirpath == dir_to_walk:
  64. yield filename
  65. else:
  66. yield os.path.join(rel_dirpath, filename)
  67. class PorcelainTestCase(TestCase):
  68. def setUp(self) -> None:
  69. super().setUp()
  70. # Disable pagers for tests
  71. self.overrideEnv("PAGER", "false")
  72. self.overrideEnv("GIT_PAGER", "false")
  73. self.overrideEnv("DULWICH_PAGER", "false")
  74. self.test_dir = tempfile.mkdtemp()
  75. self.addCleanup(shutil.rmtree, self.test_dir)
  76. self.repo_path = os.path.join(self.test_dir, "repo")
  77. self.repo = Repo.init(self.repo_path, mkdir=True)
  78. self.addCleanup(self.repo.close)
  79. def assertRecentTimestamp(self, ts) -> None:
  80. # On some slow CIs it does actually take more than 5 seconds to go from
  81. # creating the tag to here.
  82. self.assertLess(time.time() - ts, 50)
  83. @skipIf(gpg is None, "gpg is not available")
  84. class PorcelainGpgTestCase(PorcelainTestCase):
  85. DEFAULT_KEY = """
  86. -----BEGIN PGP PRIVATE KEY BLOCK-----
  87. lQVYBGBjIyIBDADAwydvMPQqeEiK54FG1DHwT5sQejAaJOb+PsOhVa4fLcKsrO3F
  88. g5CxO+/9BHCXAr8xQAtp/gOhDN05fyK3MFyGlL9s+Cd8xf34S3R4rN/qbF0oZmaa
  89. FW0MuGnniq54HINs8KshadVn1Dhi/GYSJ588qNFRl/qxFTYAk+zaGsgX/QgFfy0f
  90. djWXJLypZXu9D6DlyJ0cPSzUlfBkI2Ytx6grzIquRjY0FbkjK3l+iGsQ+ebRMdcP
  91. Sqd5iTN9XuzIUVoBFAZBRjibKV3N2wxlnCbfLlzCyDp7rktzSThzjJ2pVDuLrMAx
  92. 6/L9hIhwmFwdtY4FBFGvMR0b0Ugh3kCsRWr8sgj9I7dUoLHid6ObYhJFhnD3GzRc
  93. U+xX1uy3iTCqJDsG334aQIhC5Giuxln4SUZna2MNbq65ksh38N1aM/t3+Dc/TKVB
  94. rb5KWicRPCQ4DIQkHMDCSPyj+dvRLCPzIaPvHD7IrCfHYHOWuvvPGCpwjo0As3iP
  95. IecoMeguPLVaqgcAEQEAAQAL/i5/pQaUd4G7LDydpbixPS6r9UrfPrU/y5zvBP/p
  96. DCynPDutJ1oq539pZvXQ2VwEJJy7x0UVKkjyMndJLNWly9wHC7o8jkHx/NalVP47
  97. LXR+GWbCdOOcYYbdAWcCNB3zOtzPnWhdAEagkc2G9xRQDIB0dLHLCIUpCbLP/CWM
  98. qlHnDsVMrVTWjgzcpsnyGgw8NeLYJtYGB8dsN+XgCCjo7a9LEvUBKNgdmWBbf14/
  99. iBw7PCugazFcH9QYfZwzhsi3nqRRagTXHbxFRG0LD9Ro9qCEutHYGP2PJ59Nj8+M
  100. zaVkJj/OxWxVOGvn2q16mQBCjKpbWfqXZVVl+G5DGOmiSTZqXy+3j6JCKdOMy6Qd
  101. JBHOHhFZXYmWYaaPzoc33T/C3QhMfY5sOtUDLJmV05Wi4dyBeNBEslYgUuTk/jXb
  102. 5ZAie25eDdrsoqkcnSs2ZguMF7AXhe6il2zVhUUMs/6UZgd6I7I4Is0HXT/pnxEp
  103. uiTRFu4v8E+u+5a8O3pffe5boQYA3TsIxceen20qY+kRaTOkURHMZLn/y6KLW8bZ
  104. rNJyXWS9hBAcbbSGhfOwYfzbDCM17yPQO3E2zo8lcGdRklUdIIaCxQwtu36N5dfx
  105. OLCCQc5LmYdl/EAm91iAhrr7dNntZ18MU09gdzUu+ONZwu4CP3cJT83+qYZULso8
  106. 4Fvd/X8IEfGZ7kM+ylrdqBwtlrn8yYXtom+ows2M2UuNR53B+BUOd73kVLTkTCjE
  107. JH63+nE8BqG7tDLCMws+23SAA3xxBgDfDrr0x7zCozQKVQEqBzQr9Uoo/c/ZjAfi
  108. syzNSrDz+g5gqJYtuL9XpPJVWf6V1GXVyJlSbxR9CjTkBxmlPxpvV25IsbVSsh0o
  109. aqkf2eWpbCL6Qb2E0jd1rvf8sGeTTohzYfiSVVsC2t9ngRO/CmetizwQBvRzLGMZ
  110. 4mtAPiy7ZEDc2dFrPp7zlKISYmJZUx/DJVuZWuOrVMpBP+bSgJXoMTlICxZUqUnE
  111. 2VKVStb/L+Tl8XCwIWdrZb9BaDnHqfcGAM2B4HNPxP88Yj1tEDly/vqeb3vVMhj+
  112. S1lunnLdgxp46YyuTMYAzj88eCGurRtzBsdxxlGAsioEnZGebEqAHQbieKq/DO6I
  113. MOMZHMSVBDqyyIx3assGlxSX8BSFW0lhKyT7i0XqnAgCJ9f/5oq0SbFGq+01VQb7
  114. jIx9PbcYJORxsE0JG/CXXPv27bRtQXsudkWGSYvC0NLOgk4z8+kQpQtyFh16lujq
  115. WRwMeriu0qNDjCa1/eHIKDovhAZ3GyO5/9m1tBlUZXN0IFVzZXIgPHRlc3RAdGVz
  116. dC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAFiEEjrR8
  117. MQ4fJK44PYMvfN2AClLmXiYFAmDcEZEACgkQfN2AClLmXibZzgv/ZfeTpTuqQE1W
  118. C1jT5KpQExnt0BizTX0U7BvSn8Fr6VXTyol6kYc3u71GLUuJyawCLtIzOXqOXJvz
  119. bjcZqymcMADuftKcfMy513FhbF6MhdVd6QoeBP6+7/xXOFJCi+QVYF7SQ2h7K1Qm
  120. +yXOiAMgSxhCZQGPBNJLlDUOd47nSIMANvlumFtmLY/1FD7RpG7WQWjeX1mnxNTw
  121. hUU+Yv7GuFc/JprXCIYqHbhWfvXyVtae2ZK4xuVi5eqwA2RfggOVM7drb+CgPhG0
  122. +9aEDDLOZqVi65wK7J73Puo3rFTbPQMljxw5s27rWqF+vB6hhVdJOPNomWy3naPi
  123. k5MW0mhsacASz1WYndpZz+XaQTq/wJF5HUyyeUWJ0vlOEdwx021PHcqSTyfNnkjD
  124. KncrE21t2sxWRsgGDETxIwkd2b2HNGAvveUD0ffFK/oJHGSXjAERFGc3wuiDj3mQ
  125. BvKm4wt4QF9ZMrCdhMAA6ax5kfEUqQR4ntmrJk/khp/mV7TILaI4nQVYBGBjIyIB
  126. DADghIo9wXnRxzfdDTvwnP8dHpLAIaPokgdpyLswqUCixJWiW2xcV6weUjEWwH6n
  127. eN/t1uZYVehbrotxVPla+MPvzhxp6/cmG+2lhzEBOp6zRwnL1wIB6HoKJfpREhyM
  128. c8rLR0zMso1L1bJTyydvnu07a7BWo3VWKjilb0rEZZUSD/2hidx5HxMOJSoidLWe
  129. d/PPuv6yht3NtA4UThlcfldm9G6PbqCdm1kMEKAkq0wVJvhPJ6gEFRNJimgygfUw
  130. MDFXEIhQtxjgdV5Uoz3O5452VLoRsDlgpi3E0WDGj7WXDaO5uSU0T5aJgVgHCP/f
  131. xZhHuQFk2YYIl5nCBpOZyWWI0IKmscTuEwzpkhICQDQFvcMZ5ibsl7wA2P7YTrQf
  132. FDMjjzuaK80GYPfxDFlyKUyLqFt8w/QzsZLDLX7+jxIEpbRAaMw/JsWqm5BMxxbS
  133. 3CIQiS5S3oSKDsNINelqWFfwvLhvlQra8gIxyNTlek25OdgG66BiiX+seH8A/ql+
  134. F+MAEQEAAQAL/1jrNSLjMt9pwo6qFKClVQZP2vf7+sH7v7LeHIDXr3EnYUnVYnOq
  135. B1FU5PspTp/+J9W25DB9CZLx7Gj8qeslFdiuLSOoIBB4RCToB3kAoeTH0DHqW/Gs
  136. hFTrmJkuDp9zpo/ek6SIXJx5rHAyR9KVw0fizQprH2f6PcgLbTWeM61dJuqowmg3
  137. 7eCOyIKv7VQvFqEhYokLD+JNmrvg+Htg0DXGvdjRjAwPf/NezEXpj67a6cHTp1/C
  138. hwp7pevG+3fTxaCJFesl5/TxxtnaBLE8m2uo/S6Hxgn9l0edonroe1QlTjEqGLy2
  139. 7qi2z5Rem+v6GWNDRgvAWur13v8FNdyduHlioG/NgRsU9mE2MYeFsfi3cfNpJQp/
  140. wC9PSCIXrb/45mkS8KyjZpCrIPB9RV/m0MREq01TPom7rstZc4A1pD0Ot7AtUYS3
  141. e95zLyEmeLziPJ9fV4fgPmEudDr1uItnmV0LOskKlpg5sc0hhdrwYoobfkKt2dx6
  142. DqfMlcM1ZkUbLQYA4jwfpFJG4HmYvjL2xCJxM0ycjvMbqFN+4UjgYWVlRfOrm1V4
  143. Op86FjbRbV6OOCNhznotAg7mul4xtzrrTkK8o3YLBeJseDgl4AWuzXtNa9hE0XpK
  144. 9gJoEHUuBOOsamVh2HpXESFyE5CclOV7JSh541TlZKfnqfZYCg4JSbp0UijkawCL
  145. 5bJJUiGGMD9rZUxIAKQO1DvUEzptS7Jl6S3y5sbIIhilp4KfYWbSk3PPu9CnZD5b
  146. LhEQp0elxnb/IL8PBgD+DpTeC8unkGKXUpbe9x0ISI6V1D6FmJq/FxNg7fMa3QCh
  147. fGiAyoTm80ZETynj+blRaDO3gY4lTLa3Opubof1EqK2QmwXmpyvXEZNYcQfQ2CCS
  148. GOWUCK8jEQamUPf1PWndZXJUmROI1WukhlL71V/ir6zQeVCv1wcwPwclJPnAe87u
  149. pEklnCYpvsEldwHUX9u0BWzoULIEsi+ddtHmT0KTeF/DHRy0W15jIHbjFqhqckj1
  150. /6fmr7l7kIi/kN4vWe0F/0Q8IXX+cVMgbl3aIuaGcvENLGcoAsAtPGx88SfRgmfu
  151. HK64Y7hx1m+Bo215rxJzZRjqHTBPp0BmCi+JKkaavIBrYRbsx20gveI4dzhLcUhB
  152. kiT4Q7oz0/VbGHS1CEf9KFeS/YOGj57s4yHauSVI0XdP9kBRTWmXvBkzsooB2cKH
  153. hwhUN7iiT1k717CiTNUT6Q/pcPFCyNuMoBBGQTU206JEgIjQvI3f8xMUMGmGVVQz
  154. 9/k716ycnhb2JZ/Q/AyQIeHJiQG2BBgBCAAgAhsMFiEEjrR8MQ4fJK44PYMvfN2A
  155. ClLmXiYFAmDcEa4ACgkQfN2AClLmXiZxxQv/XaMN0hPCygtrQMbCsTNb34JbvJzh
  156. hngPuUAfTbRHrR3YeATyQofNbL0DD3fvfzeFF8qESqvzCSZxS6dYsXPd4MCJTzlp
  157. zYBZ2X0sOrgDqZvqCZKN72RKgdk0KvthdzAxsIm2dfcQOxxowXMxhJEXZmsFpusx
  158. jKJxOcrfVRjXJnh9isY0NpCoqMQ+3k3wDJ3VGEHV7G+A+vFkWfbLJF5huQ96uaH9
  159. Uc+jUsREUH9G82ZBqpoioEN8Ith4VXpYnKdTMonK/+ZcyeraJZhXrvbjnEomKdzU
  160. 0pu4bt1HlLR3dcnpjN7b009MBf2xLgEfQk2nPZ4zzY+tDkxygtPllaB4dldFjBpT
  161. j7Q+t49sWMjmlJUbLlHfuJ7nUUK5+cGjBsWVObAEcyfemHWCTVFnEa2BJslGC08X
  162. rFcjRRcMEr9ct4551QFBHsv3O/Wp3/wqczYgE9itSnGT05w+4vLt4smG+dnEHjRJ
  163. brMb2upTHa+kjktjdO96/BgSnKYqmNmPB/qB
  164. =ivA/
  165. -----END PGP PRIVATE KEY BLOCK-----
  166. """
  167. DEFAULT_KEY_ID = "8EB47C310E1F24AE383D832F7CDD800A52E65E26"
  168. NON_DEFAULT_KEY = """
  169. -----BEGIN PGP PRIVATE KEY BLOCK-----
  170. lQVYBGBjI0ABDADGWBRp+t02emfzUlhrc1psqIhhecFm6Em0Kv33cfDpnfoMF1tK
  171. Yy/4eLYIR7FmpdbFPcDThFNHbXJzBi00L1mp0XQE2l50h/2bDAAgREdZ+NVo5a7/
  172. RSZjauNU1PxW6pnXMehEh1tyIQmV78jAukaakwaicrpIenMiFUN3fAKHnLuFffA6
  173. t0f3LqJvTDhUw/o2vPgw5e6UDQhA1C+KTv1KXVrhJNo88a3hZqCZ76z3drKR411Q
  174. zYgT4DUb8lfnbN+z2wfqT9oM5cegh2k86/mxAA3BYOeQrhmQo/7uhezcgbxtdGZr
  175. YlbuaNDTSBrn10ZoaxLPo2dJe2zWxgD6MpvsGU1w3tcRW508qo/+xoWp2/pDzmok
  176. +uhOh1NAj9zB05VWBz1r7oBgCOIKpkD/LD4VKq59etsZ/UnrYDwKdXWZp7uhshkU
  177. M7N35lUJcR76a852dlMdrgpmY18+BP7+o7M+5ElHTiqQbMuE1nHTg8RgVpdV+tUx
  178. dg6GWY/XHf5asm8AEQEAAQAL/A85epOp+GnymmEQfI3+5D178D//Lwu9n86vECB6
  179. xAHCqQtdjZnXpDp/1YUsL59P8nzgYRk7SoMskQDoQ/cB/XFuDOhEdMSgHaTVlnrj
  180. ktCCq6rqGnUosyolbb64vIfVaSqd/5SnCStpAsnaBoBYrAu4ZmV4xfjDQWwn0q5s
  181. u+r56mD0SkjPgbwk/b3qTVagVmf2OFzUgWwm1e/X+bA1oPag1NV8VS4hZPXswT4f
  182. qhiyqUFOgP6vUBcqehkjkIDIl/54xII7/P5tp3LIZawvIXqHKNTqYPCqaCqCj+SL
  183. vMYDIb6acjescfZoM71eAeHAANeFZzr/rwfBT+dEP6qKmPXNcvgE11X44ZCr04nT
  184. zOV/uDUifEvKT5qgtyJpSFEVr7EXubJPKoNNhoYqq9z1pYU7IedX5BloiVXKOKTY
  185. 0pk7JkLqf3g5fYtXh/wol1owemITJy5V5PgaqZvk491LkI6S+kWC7ANYUg+TDPIW
  186. afxW3E5N1CYV6XDAl0ZihbLcoQYAy0Ky/p/wayWKePyuPBLwx9O89GSONK2pQljZ
  187. yaAgxPQ5/i1vx6LIMg7k/722bXR9W3zOjWOin4eatPM3d2hkG96HFvnBqXSmXOPV
  188. 03Xqy1/B5Tj8E9naLKUHE/OBQEc363DgLLG9db5HfPlpAngeppYPdyWkhzXyzkgS
  189. PylaE5eW3zkdjEbYJ6RBTecTZEgBaMvJNPdWbn//frpP7kGvyiCg5Es+WjLInUZ6
  190. 0sdifcNTCewzLXK80v/y5mVOdJhPBgD5zs9cYdyiQJayqAuOr+He1eMHMVUbm9as
  191. qBmPrst398eBW9ZYF7eBfTSlUf6B+WnvyLKEGsUf/7IK0EWDlzoBuWzWiHjUAY1g
  192. m9eTV2MnvCCCefqCErWwfFo2nWOasAZA9sKD+ICIBY4tbtvSl4yfLBzTMwSvs9ZS
  193. K1ocPSYUnhm2miSWZ8RLZPH7roHQasNHpyq/AX7DahFf2S/bJ+46ZGZ8Pigr7hA+
  194. MjmpQ4qVdb5SaViPmZhAKO+PjuCHm+EF/2H0Y3Sl4eXgxZWoQVOUeXdWg9eMfYrj
  195. XDtUMIFppV/QxbeztZKvJdfk64vt/crvLsOp0hOky9cKwY89r4QaHfexU3qR+qDq
  196. UlMvR1rHk7dS5HZAtw0xKsFJNkuDxvBkMqv8Los8zp3nUl+U99dfZOArzNkW38wx
  197. FPa0ixkC9za2BkDrWEA8vTnxw0A2upIFegDUhwOByrSyfPPnG3tKGeqt3Izb/kDk
  198. Q9vmo+HgxBOguMIvlzbBfQZwtbd/gXzlvPqCtCJBbm90aGVyIFRlc3QgVXNlciA8
  199. dGVzdDJAdGVzdC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4B
  200. AheAFiEEapM5P1DF5qzT1vtFuTYhLttOFMAFAmDcEeEACgkQuTYhLttOFMDe0Qv/
  201. Qx/bzXztJ3BCc+CYAVDx7Kr37S68etwwLgcWzhG+CDeMB5F/QE+upKgxy2iaqQFR
  202. mxfOMgf/TIQkUfkbaASzK1LpnesYO85pk7XYjoN1bYEHiXTkeW+bgB6aJIxrRmO2
  203. SrWasdBC/DsI3Mrya8YMt/TiHC6VpRJVxCe5vv7/kZC4CXrgTBnZocXx/YXimbke
  204. poPMVdbvhYh6N0aGeS38jRKgyN10KXmhDTAQDwseVFavBWAjVfx3DEwjtK2Z2GbA
  205. aL8JvAwRtqiPFkDMIKPL4UwxtXFws8SpMt6juroUkNyf6+BxNWYqmwXHPy8zCJAb
  206. xkxIJMlEc+s7qQsP3fILOo8Xn+dVzJ5sa5AoARoXm1GMjsdqaKAzq99Dic/dHnaQ
  207. Civev1PQsdwlYW2C2wNXNeIrxMndbDMFfNuZ6BnGHWJ/wjcp/pFs4YkyyZN8JH7L
  208. hP2FO4Jgham3AuP13kC3Ivea7V6hR8QNcDZRwFPOMIX4tXwQv1T72+7DZGaA25O7
  209. nQVXBGBjI0ABDADJMBYIcG0Yil9YxFs7aYzNbd7alUAr89VbY8eIGPHP3INFPM1w
  210. lBQCu+4j6xdEbhMpppLBZ9A5TEylP4C6qLtPa+oLtPeuSw8gHDE10XE4lbgPs376
  211. rL60XdImSOHhiduACUefYjqpcmFH9Bim1CC+koArYrSQJQx1Jri+OpnTaL/8UID0
  212. KzD/kEgMVGlHIVj9oJmb4+j9pW8I/g0wDSnIaEKFMxqu6SIVJ1GWj+MUMvZigjLC
  213. sNCZd7PnbOC5VeU3SsXj6he74Jx0AmGMPWIHi9M0DjHO5d1cCbXTnud8xxM1bOh4
  214. 7aCTnMK5cVyIr+adihgJpVVhrndSM8aklBPRgtozrGNCgF2CkYU2P1blxfloNr/8
  215. UZpM83o+s1aObBszzRNLxnpNORqoLqjfPtLEPQnagxE+4EapCq0NZ/x6yO5VTwwp
  216. NljdFAEk40uGuKyn1QA3uNMHy5DlpLl+tU7t1KEovdZ+OVYsYKZhVzw0MTpKogk9
  217. JI7AN0q62ronPskAEQEAAQAL+O8BUSt1ZCVjPSIXIsrR+ZOSkszZwgJ1CWIoh0IH
  218. YD2vmcMHGIhFYgBdgerpvhptKhaw7GcXDScEnYkyh5s4GE2hxclik1tbj/x1gYCN
  219. 8BNoyeDdPFxQG73qN12D99QYEctpOsz9xPLIDwmL0j1ehAfhwqHIAPm9Ca+i8JYM
  220. x/F+35S/jnKDXRI+NVlwbiEyXKXxxIqNlpy9i8sDBGexO5H5Sg0zSN/B1duLekGD
  221. biDw6gLc6bCgnS+0JOUpU07Z2fccMOY9ncjKGD2uIb/ePPUaek92GCQyq0eorCIV
  222. brcQsRc5sSsNtnRKQTQtxioROeDg7kf2oWySeHTswlXW/219ihrSXgteHJd+rPm7
  223. DYLEeGLRny8bRKv8rQdAtApHaJE4dAATXeY4RYo4NlXHYaztGYtU6kiM/3zCfWAe
  224. 9Nn+Wh9jMTZrjefUCagS5r6ZqAh7veNo/vgIGaCLh0a1Ypa0Yk9KFrn3LYEM3zgk
  225. 3m3bn+7qgy5cUYXoJ3DGJJEhBgDPonpW0WElqLs5ZMem1ha85SC38F0IkAaSuzuz
  226. v3eORiKWuyJGF32Q2XHa1RHQs1JtUKd8rxFer3b8Oq71zLz6JtVc9dmRudvgcJYX
  227. 0PC11F6WGjZFSSp39dajFp0A5DKUs39F3w7J1yuDM56TDIN810ywufGAHARY1pZb
  228. UJAy/dTqjFnCbNjpAakor3hVzqxcmUG+7Y2X9c2AGncT1MqAQC3M8JZcuZvkK8A9
  229. cMk8B914ryYE7VsZMdMhyTwHmykGAPgNLLa3RDETeGeGCKWI+ZPOoU0ib5JtJZ1d
  230. P3tNwfZKuZBZXKW9gqYqyBa/qhMip84SP30pr/TvulcdAFC759HK8sQZyJ6Vw24P
  231. c+5ssRxrQUEw1rvJPWhmQCmCOZHBMQl5T6eaTOpR5u3aUKTMlxPKhK9eC1dCSTnI
  232. /nyL8An3VKnLy+K/LI42YGphBVLLJmBewuTVDIJviWRdntiG8dElyEJMOywUltk3
  233. 2CEmqgsD9tPO8rXZjnMrMn3gfsiaoQYA6/6/e2utkHr7gAoWBgrBBdqVHsvqh5Ro
  234. 2DjLAOpZItO/EdCJfDAmbTYOa04535sBDP2tcH/vipPOPpbr1Y9Y/mNsKCulNxed
  235. yqAmEkKOcerLUP5UHju0AB6VBjHJFdU2mqT+UjPyBk7WeKXgFomyoYMv3KpNOFWR
  236. xi0Xji4kKHbttA6Hy3UcGPr9acyUAlDYeKmxbSUYIPhw32bbGrX9+F5YriTufRsG
  237. 3jftQVo9zqdcQSD/5pUTMn3EYbEcohYB2YWJAbYEGAEIACACGwwWIQRqkzk/UMXm
  238. rNPW+0W5NiEu204UwAUCYNwR6wAKCRC5NiEu204UwOPnC/92PgB1c3h9FBXH1maz
  239. g29fndHIHH65VLgqMiQ7HAMojwRlT5Xnj5tdkCBmszRkv5vMvdJRa3ZY8Ed/Inqr
  240. hxBFNzpjqX4oj/RYIQLKXWWfkTKYVLJFZFPCSo00jesw2gieu3Ke/Yy4gwhtNodA
  241. v+s6QNMvffTW/K3XNrWDB0E7/LXbdidzhm+MBu8ov2tuC3tp9liLICiE1jv/2xT4
  242. CNSO6yphmk1/1zEYHS/mN9qJ2csBmte2cdmGyOcuVEHk3pyINNMDOamaURBJGRwF
  243. XB5V7gTKUFU4jCp3chywKrBHJHxGGDUmPBmZtDtfWAOgL32drK7/KUyzZL/WO7Fj
  244. akOI0hRDFOcqTYWL20H7+hAiX3oHMP7eou3L5C7wJ9+JMcACklN/WMjG9a536DFJ
  245. 4UgZ6HyKPP+wy837Hbe8b25kNMBwFgiaLR0lcgzxj7NyQWjVCMOEN+M55tRCjvL6
  246. ya6JVZCRbMXfdCy8lVPgtNQ6VlHaj8Wvnn2FLbWWO2n2r3s=
  247. =9zU5
  248. -----END PGP PRIVATE KEY BLOCK-----
  249. """
  250. NON_DEFAULT_KEY_ID = "6A93393F50C5E6ACD3D6FB45B936212EDB4E14C0"
  251. def setUp(self) -> None:
  252. super().setUp()
  253. self.gpg_dir = os.path.join(self.test_dir, "gpg")
  254. os.mkdir(self.gpg_dir, mode=0o700)
  255. # Ignore errors when deleting GNUPGHOME, because of race conditions
  256. # (e.g. the gpg-agent socket having been deleted). See
  257. # https://github.com/jelmer/dulwich/issues/1000
  258. self.addCleanup(shutil.rmtree, self.gpg_dir, ignore_errors=True)
  259. self.overrideEnv("GNUPGHOME", self.gpg_dir)
  260. def import_default_key(self) -> None:
  261. subprocess.run(
  262. ["gpg", "--import"],
  263. stdout=subprocess.DEVNULL,
  264. stderr=subprocess.DEVNULL,
  265. input=PorcelainGpgTestCase.DEFAULT_KEY,
  266. text=True,
  267. )
  268. def import_non_default_key(self) -> None:
  269. subprocess.run(
  270. ["gpg", "--import"],
  271. stdout=subprocess.DEVNULL,
  272. stderr=subprocess.DEVNULL,
  273. input=PorcelainGpgTestCase.NON_DEFAULT_KEY,
  274. text=True,
  275. )
  276. class ArchiveTests(PorcelainTestCase):
  277. """Tests for the archive command."""
  278. def test_simple(self) -> None:
  279. _c1, _c2, c3 = build_commit_graph(
  280. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  281. )
  282. self.repo.refs[b"refs/heads/master"] = c3.id
  283. out = BytesIO()
  284. err = BytesIO()
  285. porcelain.archive(
  286. self.repo.path, b"refs/heads/master", outstream=out, errstream=err
  287. )
  288. self.assertEqual(b"", err.getvalue())
  289. tf = tarfile.TarFile(fileobj=out)
  290. self.addCleanup(tf.close)
  291. self.assertEqual([], tf.getnames())
  292. class UpdateServerInfoTests(PorcelainTestCase):
  293. def test_simple(self) -> None:
  294. _c1, _c2, c3 = build_commit_graph(
  295. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  296. )
  297. self.repo.refs[b"refs/heads/foo"] = c3.id
  298. porcelain.update_server_info(self.repo.path)
  299. self.assertTrue(
  300. os.path.exists(os.path.join(self.repo.controldir(), "info", "refs"))
  301. )
  302. class CommitTests(PorcelainTestCase):
  303. def test_custom_author(self) -> None:
  304. _c1, _c2, c3 = build_commit_graph(
  305. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  306. )
  307. self.repo.refs[b"refs/heads/foo"] = c3.id
  308. sha = porcelain.commit(
  309. self.repo.path,
  310. message=b"Some message",
  311. author=b"Joe <joe@example.com>",
  312. committer=b"Bob <bob@example.com>",
  313. )
  314. self.assertIsInstance(sha, bytes)
  315. self.assertEqual(len(sha), 40)
  316. def test_unicode(self) -> None:
  317. _c1, _c2, c3 = build_commit_graph(
  318. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  319. )
  320. self.repo.refs[b"refs/heads/foo"] = c3.id
  321. sha = porcelain.commit(
  322. self.repo.path,
  323. message="Some message",
  324. author="Joe <joe@example.com>",
  325. committer="Bob <bob@example.com>",
  326. )
  327. self.assertIsInstance(sha, bytes)
  328. self.assertEqual(len(sha), 40)
  329. def test_no_verify(self) -> None:
  330. if os.name != "posix":
  331. self.skipTest("shell hook tests requires POSIX shell")
  332. self.assertTrue(os.path.exists("/bin/sh"))
  333. hooks_dir = os.path.join(self.repo.controldir(), "hooks")
  334. os.makedirs(hooks_dir, exist_ok=True)
  335. self.addCleanup(shutil.rmtree, hooks_dir)
  336. _c1, _c2, _c3 = build_commit_graph(
  337. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  338. )
  339. hook_fail = "#!/bin/sh\nexit 1"
  340. # hooks are executed in pre-commit, commit-msg order
  341. # test commit-msg failure first, then pre-commit failure, then
  342. # no_verify to skip both hooks
  343. commit_msg = os.path.join(hooks_dir, "commit-msg")
  344. with open(commit_msg, "w") as f:
  345. f.write(hook_fail)
  346. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  347. with self.assertRaises(CommitError):
  348. porcelain.commit(
  349. self.repo.path,
  350. message="Some message",
  351. author="Joe <joe@example.com>",
  352. committer="Bob <bob@example.com>",
  353. )
  354. pre_commit = os.path.join(hooks_dir, "pre-commit")
  355. with open(pre_commit, "w") as f:
  356. f.write(hook_fail)
  357. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  358. with self.assertRaises(CommitError):
  359. porcelain.commit(
  360. self.repo.path,
  361. message="Some message",
  362. author="Joe <joe@example.com>",
  363. committer="Bob <bob@example.com>",
  364. )
  365. sha = porcelain.commit(
  366. self.repo.path,
  367. message="Some message",
  368. author="Joe <joe@example.com>",
  369. committer="Bob <bob@example.com>",
  370. no_verify=True,
  371. )
  372. self.assertIsInstance(sha, bytes)
  373. self.assertEqual(len(sha), 40)
  374. def test_timezone(self) -> None:
  375. _c1, _c2, c3 = build_commit_graph(
  376. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  377. )
  378. self.repo.refs[b"refs/heads/foo"] = c3.id
  379. sha = porcelain.commit(
  380. self.repo.path,
  381. message="Some message",
  382. author="Joe <joe@example.com>",
  383. author_timezone=18000,
  384. committer="Bob <bob@example.com>",
  385. commit_timezone=18000,
  386. )
  387. self.assertIsInstance(sha, bytes)
  388. self.assertEqual(len(sha), 40)
  389. commit = self.repo.get_object(sha)
  390. assert isinstance(commit, Commit)
  391. self.assertEqual(commit._author_timezone, 18000)
  392. self.assertEqual(commit._commit_timezone, 18000)
  393. self.overrideEnv("GIT_AUTHOR_DATE", "1995-11-20T19:12:08-0501")
  394. self.overrideEnv("GIT_COMMITTER_DATE", "1995-11-20T19:12:08-0501")
  395. sha = porcelain.commit(
  396. self.repo.path,
  397. message="Some message",
  398. author="Joe <joe@example.com>",
  399. committer="Bob <bob@example.com>",
  400. )
  401. self.assertIsInstance(sha, bytes)
  402. self.assertEqual(len(sha), 40)
  403. commit = self.repo.get_object(sha)
  404. assert isinstance(commit, Commit)
  405. self.assertEqual(commit._author_timezone, -18060)
  406. self.assertEqual(commit._commit_timezone, -18060)
  407. self.overrideEnv("GIT_AUTHOR_DATE", None)
  408. self.overrideEnv("GIT_COMMITTER_DATE", None)
  409. local_timezone = time.localtime().tm_gmtoff
  410. sha = porcelain.commit(
  411. self.repo.path,
  412. message="Some message",
  413. author="Joe <joe@example.com>",
  414. committer="Bob <bob@example.com>",
  415. )
  416. self.assertIsInstance(sha, bytes)
  417. self.assertEqual(len(sha), 40)
  418. commit = self.repo.get_object(sha)
  419. assert isinstance(commit, Commit)
  420. self.assertEqual(commit._author_timezone, local_timezone)
  421. self.assertEqual(commit._commit_timezone, local_timezone)
  422. def test_commit_all(self) -> None:
  423. # Create initial commit
  424. filename = os.path.join(self.repo.path, "test.txt")
  425. with open(filename, "wb") as f:
  426. f.write(b"initial content")
  427. porcelain.add(self.repo.path, paths=["test.txt"])
  428. initial_sha = porcelain.commit(self.repo.path, message=b"Initial commit")
  429. # Modify the file without staging
  430. with open(filename, "wb") as f:
  431. f.write(b"modified content")
  432. # Create an untracked file
  433. untracked_file = os.path.join(self.repo.path, "untracked.txt")
  434. with open(untracked_file, "wb") as f:
  435. f.write(b"untracked content")
  436. # Commit with all=True should stage modified files but not untracked
  437. sha = porcelain.commit(self.repo.path, message=b"Modified commit", all=True)
  438. self.assertIsInstance(sha, bytes)
  439. self.assertEqual(len(sha), 40)
  440. self.assertNotEqual(sha, initial_sha)
  441. # Verify the commit contains the modification
  442. commit = self.repo.get_object(sha)
  443. assert isinstance(commit, Commit)
  444. tree = self.repo.get_object(commit.tree)
  445. # The modified file should be in the commit
  446. self.assertIn(b"test.txt", tree)
  447. # The untracked file should not be in the commit
  448. self.assertNotIn(b"untracked.txt", tree)
  449. def test_commit_all_no_changes(self) -> None:
  450. # Create initial commit
  451. filename = os.path.join(self.repo.path, "test.txt")
  452. with open(filename, "wb") as f:
  453. f.write(b"initial content")
  454. porcelain.add(self.repo.path, paths=["test.txt"])
  455. initial_sha = porcelain.commit(self.repo.path, message=b"Initial commit")
  456. # Try to commit with all=True when there are no unstaged changes
  457. sha = porcelain.commit(self.repo.path, message=b"No changes commit", all=True)
  458. self.assertIsInstance(sha, bytes)
  459. self.assertEqual(len(sha), 40)
  460. self.assertNotEqual(sha, initial_sha)
  461. def test_commit_all_multiple_files(self) -> None:
  462. # Create initial commit with multiple files
  463. file1 = os.path.join(self.repo.path, "file1.txt")
  464. file2 = os.path.join(self.repo.path, "file2.txt")
  465. with open(file1, "wb") as f:
  466. f.write(b"content1")
  467. with open(file2, "wb") as f:
  468. f.write(b"content2")
  469. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  470. initial_sha = porcelain.commit(self.repo.path, message=b"Initial commit")
  471. # Modify both files
  472. with open(file1, "wb") as f:
  473. f.write(b"modified content1")
  474. with open(file2, "wb") as f:
  475. f.write(b"modified content2")
  476. # Commit with all=True should stage both modified files
  477. sha = porcelain.commit(self.repo.path, message=b"Modified both files", all=True)
  478. self.assertIsInstance(sha, bytes)
  479. self.assertEqual(len(sha), 40)
  480. self.assertNotEqual(sha, initial_sha)
  481. # Verify both modifications are in the commit
  482. commit = self.repo.get_object(sha)
  483. assert isinstance(commit, Commit)
  484. tree = self.repo.get_object(commit.tree)
  485. self.assertIn(b"file1.txt", tree)
  486. self.assertIn(b"file2.txt", tree)
  487. def test_commit_amend_message(self) -> None:
  488. # Create initial commit
  489. filename = os.path.join(self.repo.path, "test.txt")
  490. with open(filename, "wb") as f:
  491. f.write(b"initial content")
  492. porcelain.add(self.repo.path, paths=["test.txt"])
  493. original_sha = porcelain.commit(self.repo.path, message=b"Original commit")
  494. # Amend with new message
  495. amended_sha = porcelain.commit(
  496. self.repo.path, message=b"Amended commit", amend=True
  497. )
  498. self.assertIsInstance(amended_sha, bytes)
  499. self.assertEqual(len(amended_sha), 40)
  500. self.assertNotEqual(amended_sha, original_sha)
  501. # Check that the amended commit has the new message
  502. amended_commit = self.repo.get_object(amended_sha)
  503. assert isinstance(amended_commit, Commit)
  504. self.assertEqual(amended_commit.message, b"Amended commit")
  505. # Check that the amended commit uses the original commit's parents
  506. original_commit = self.repo.get_object(original_sha)
  507. assert isinstance(original_commit, Commit)
  508. # Since this was the first commit, it should have no parents,
  509. # and the amended commit should also have no parents
  510. self.assertEqual(amended_commit.parents, original_commit.parents)
  511. def test_commit_amend_no_message(self) -> None:
  512. # Create initial commit
  513. filename = os.path.join(self.repo.path, "test.txt")
  514. with open(filename, "wb") as f:
  515. f.write(b"initial content")
  516. porcelain.add(self.repo.path, paths=["test.txt"])
  517. original_sha = porcelain.commit(self.repo.path, message=b"Original commit")
  518. # Modify file and stage it
  519. with open(filename, "wb") as f:
  520. f.write(b"modified content")
  521. porcelain.add(self.repo.path, paths=["test.txt"])
  522. # Amend without providing message (should reuse original message)
  523. amended_sha = porcelain.commit(self.repo.path, amend=True)
  524. self.assertIsInstance(amended_sha, bytes)
  525. self.assertEqual(len(amended_sha), 40)
  526. self.assertNotEqual(amended_sha, original_sha)
  527. # Check that the amended commit has the original message
  528. amended_commit = self.repo.get_object(amended_sha)
  529. assert isinstance(amended_commit, Commit)
  530. self.assertEqual(amended_commit.message, b"Original commit")
  531. def test_commit_amend_no_existing_commit(self) -> None:
  532. # Try to amend when there's no existing commit
  533. with self.assertRaises(ValueError) as cm:
  534. porcelain.commit(self.repo.path, message=b"Should fail", amend=True)
  535. self.assertIn("Cannot amend: no existing commit found", str(cm.exception))
  536. @skipIf(
  537. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  538. "gpgme not easily available or supported on Windows and PyPy",
  539. )
  540. class CommitSignTests(PorcelainGpgTestCase):
  541. def test_default_key(self) -> None:
  542. _c1, _c2, c3 = build_commit_graph(
  543. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  544. )
  545. self.repo.refs[b"HEAD"] = c3.id
  546. cfg = self.repo.get_config()
  547. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  548. self.import_default_key()
  549. sha = porcelain.commit(
  550. self.repo.path,
  551. message="Some message",
  552. author="Joe <joe@example.com>",
  553. committer="Bob <bob@example.com>",
  554. sign=True,
  555. )
  556. self.assertIsInstance(sha, bytes)
  557. self.assertEqual(len(sha), 40)
  558. commit = self.repo.get_object(sha)
  559. assert isinstance(commit, Commit)
  560. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  561. commit.verify()
  562. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  563. self.import_non_default_key()
  564. self.assertRaises(
  565. gpg.errors.MissingSignatures,
  566. commit.verify,
  567. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  568. )
  569. assert isinstance(commit, Commit)
  570. commit.committer = b"Alice <alice@example.com>"
  571. self.assertRaises(
  572. gpg.errors.BadSignatures,
  573. commit.verify,
  574. )
  575. def test_non_default_key(self) -> None:
  576. _c1, _c2, c3 = build_commit_graph(
  577. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  578. )
  579. self.repo.refs[b"HEAD"] = c3.id
  580. cfg = self.repo.get_config()
  581. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  582. self.import_non_default_key()
  583. sha = porcelain.commit(
  584. self.repo.path,
  585. message="Some message",
  586. author="Joe <joe@example.com>",
  587. committer="Bob <bob@example.com>",
  588. signoff=PorcelainGpgTestCase.NON_DEFAULT_KEY_ID,
  589. )
  590. self.assertIsInstance(sha, bytes)
  591. self.assertEqual(len(sha), 40)
  592. commit = self.repo.get_object(sha)
  593. assert isinstance(commit, Commit)
  594. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  595. commit.verify()
  596. def test_sign_uses_config_signingkey(self) -> None:
  597. """Test that sign=True uses user.signingKey from config."""
  598. _c1, _c2, c3 = build_commit_graph(
  599. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  600. )
  601. self.repo.refs[b"HEAD"] = c3.id
  602. # Set up user.signingKey in config
  603. cfg = self.repo.get_config()
  604. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  605. cfg.write_to_path()
  606. self.import_default_key()
  607. # Create commit with sign=True (should use signingKey from config)
  608. sha = porcelain.commit(
  609. self.repo.path,
  610. message="Signed with configured key",
  611. author="Joe <joe@example.com>",
  612. committer="Bob <bob@example.com>",
  613. sign=True, # This should read user.signingKey from config
  614. )
  615. self.assertIsInstance(sha, bytes)
  616. self.assertEqual(len(sha), 40)
  617. commit = self.repo.get_object(sha)
  618. assert isinstance(commit, Commit)
  619. # Verify the commit is signed with the configured key
  620. commit.verify()
  621. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  622. def test_commit_gpg_sign_config_enabled(self) -> None:
  623. """Test that commit.gpgSign=true automatically signs commits."""
  624. _c1, _c2, c3 = build_commit_graph(
  625. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  626. )
  627. self.repo.refs[b"HEAD"] = c3.id
  628. # Set up user.signingKey and commit.gpgSign in config
  629. cfg = self.repo.get_config()
  630. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  631. cfg.set(("commit",), "gpgSign", True)
  632. cfg.write_to_path()
  633. self.import_default_key()
  634. # Create commit without explicit signoff parameter (should auto-sign due to config)
  635. sha = porcelain.commit(
  636. self.repo.path,
  637. message="Auto-signed commit",
  638. author="Joe <joe@example.com>",
  639. committer="Bob <bob@example.com>",
  640. # No signoff parameter - should use commit.gpgSign config
  641. )
  642. self.assertIsInstance(sha, bytes)
  643. self.assertEqual(len(sha), 40)
  644. commit = self.repo.get_object(sha)
  645. assert isinstance(commit, Commit)
  646. # Verify the commit is signed due to config
  647. commit.verify()
  648. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  649. def test_commit_gpg_sign_config_disabled(self) -> None:
  650. """Test that commit.gpgSign=false does not sign commits."""
  651. _c1, _c2, c3 = build_commit_graph(
  652. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  653. )
  654. self.repo.refs[b"HEAD"] = c3.id
  655. # Set up user.signingKey and commit.gpgSign=false in config
  656. cfg = self.repo.get_config()
  657. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  658. cfg.set(("commit",), "gpgSign", False)
  659. cfg.write_to_path()
  660. self.import_default_key()
  661. # Create commit without explicit signoff parameter (should not sign)
  662. sha = porcelain.commit(
  663. self.repo.path,
  664. message="Unsigned commit",
  665. author="Joe <joe@example.com>",
  666. committer="Bob <bob@example.com>",
  667. # No signoff parameter - should use commit.gpgSign=false config
  668. )
  669. self.assertIsInstance(sha, bytes)
  670. self.assertEqual(len(sha), 40)
  671. commit = self.repo.get_object(sha)
  672. assert isinstance(commit, Commit)
  673. # Verify the commit is not signed
  674. self.assertIsNone(commit._gpgsig)
  675. def test_commit_gpg_sign_config_no_signing_key(self) -> None:
  676. """Test that commit.gpgSign=true works without user.signingKey (uses default)."""
  677. _c1, _c2, c3 = build_commit_graph(
  678. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  679. )
  680. self.repo.refs[b"HEAD"] = c3.id
  681. # Set up commit.gpgSign but no user.signingKey
  682. cfg = self.repo.get_config()
  683. cfg.set(("commit",), "gpgSign", True)
  684. cfg.write_to_path()
  685. self.import_default_key()
  686. # Create commit without explicit signoff parameter (should auto-sign with default key)
  687. sha = porcelain.commit(
  688. self.repo.path,
  689. message="Default signed commit",
  690. author="Joe <joe@example.com>",
  691. committer="Bob <bob@example.com>",
  692. # No signoff parameter - should use commit.gpgSign config with default key
  693. )
  694. self.assertIsInstance(sha, bytes)
  695. self.assertEqual(len(sha), 40)
  696. commit = self.repo.get_object(sha)
  697. assert isinstance(commit, Commit)
  698. # Verify the commit is signed with default key
  699. commit.verify()
  700. def test_explicit_signoff_overrides_config(self) -> None:
  701. """Test that explicit signoff parameter overrides commit.gpgSign config."""
  702. _c1, _c2, c3 = build_commit_graph(
  703. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  704. )
  705. self.repo.refs[b"HEAD"] = c3.id
  706. # Set up commit.gpgSign=false but explicitly pass sign=True
  707. cfg = self.repo.get_config()
  708. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  709. cfg.set(("commit",), "gpgSign", False)
  710. cfg.write_to_path()
  711. self.import_default_key()
  712. # Create commit with explicit sign=True (should override config)
  713. sha = porcelain.commit(
  714. self.repo.path,
  715. message="Explicitly signed commit",
  716. author="Joe <joe@example.com>",
  717. committer="Bob <bob@example.com>",
  718. sign=True, # This should override commit.gpgSign=false
  719. )
  720. self.assertIsInstance(sha, bytes)
  721. self.assertEqual(len(sha), 40)
  722. commit = self.repo.get_object(sha)
  723. assert isinstance(commit, Commit)
  724. # Verify the commit is signed despite config=false
  725. commit.verify()
  726. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  727. def test_explicit_false_disables_signing(self) -> None:
  728. """Test that explicit signoff=False disables signing even with config=true."""
  729. _c1, _c2, c3 = build_commit_graph(
  730. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  731. )
  732. self.repo.refs[b"HEAD"] = c3.id
  733. # Set up commit.gpgSign=true but explicitly pass sign=False
  734. cfg = self.repo.get_config()
  735. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  736. cfg.set(("commit",), "gpgSign", True)
  737. cfg.write_to_path()
  738. self.import_default_key()
  739. # Create commit with explicit sign=False (should disable signing)
  740. sha = porcelain.commit(
  741. self.repo.path,
  742. message="Explicitly unsigned commit",
  743. author="Joe <joe@example.com>",
  744. committer="Bob <bob@example.com>",
  745. sign=False, # This should override commit.gpgSign=true
  746. )
  747. self.assertIsInstance(sha, bytes)
  748. self.assertEqual(len(sha), 40)
  749. commit = self.repo.get_object(sha)
  750. assert isinstance(commit, Commit)
  751. # Verify the commit is NOT signed despite config=true
  752. self.assertIsNone(commit._gpgsig)
  753. @skipIf(
  754. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  755. "gpgme not easily available or supported on Windows and PyPy",
  756. )
  757. class VerifyCommitTests(PorcelainGpgTestCase):
  758. def test_verify_commit_valid_signature(self) -> None:
  759. """Test verifying a commit with a valid GPG signature."""
  760. _c1, _c2, c3 = build_commit_graph(
  761. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  762. )
  763. self.repo.refs[b"HEAD"] = c3.id
  764. cfg = self.repo.get_config()
  765. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  766. cfg.write_to_path()
  767. self.import_default_key()
  768. # Create a signed commit
  769. sha = porcelain.commit(
  770. self.repo.path,
  771. message="Signed commit",
  772. author="Joe <joe@example.com>",
  773. committer="Bob <bob@example.com>",
  774. sign=True,
  775. )
  776. # Verify should not raise
  777. porcelain.verify_commit(self.repo.path, sha)
  778. porcelain.verify_commit(
  779. self.repo.path, sha, keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID]
  780. )
  781. def test_verify_commit_with_wrong_key(self) -> None:
  782. """Test that verifying with wrong keyid raises MissingSignatures."""
  783. _c1, _c2, c3 = build_commit_graph(
  784. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  785. )
  786. self.repo.refs[b"HEAD"] = c3.id
  787. cfg = self.repo.get_config()
  788. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  789. cfg.write_to_path()
  790. self.import_default_key()
  791. sha = porcelain.commit(
  792. self.repo.path,
  793. message="Signed commit",
  794. author="Joe <joe@example.com>",
  795. committer="Bob <bob@example.com>",
  796. sign=True,
  797. )
  798. self.import_non_default_key()
  799. self.assertRaises(
  800. gpg.errors.MissingSignatures,
  801. porcelain.verify_commit,
  802. self.repo.path,
  803. sha,
  804. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  805. )
  806. def test_verify_commit_unsigned(self) -> None:
  807. """Test that verifying an unsigned commit succeeds (no signature to verify)."""
  808. _c1, _c2, c3 = build_commit_graph(
  809. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  810. )
  811. self.repo.refs[b"HEAD"] = c3.id
  812. sha = porcelain.commit(
  813. self.repo.path,
  814. message="Unsigned commit",
  815. author="Joe <joe@example.com>",
  816. committer="Bob <bob@example.com>",
  817. sign=False,
  818. )
  819. # Verify should not raise for unsigned commits
  820. porcelain.verify_commit(self.repo.path, sha)
  821. @skipIf(
  822. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  823. "gpgme not easily available or supported on Windows and PyPy",
  824. )
  825. class VerifyTagTests(PorcelainGpgTestCase):
  826. def test_verify_tag_valid_signature(self) -> None:
  827. """Test verifying a tag with a valid GPG signature."""
  828. _c1, _c2, c3 = build_commit_graph(
  829. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  830. )
  831. self.repo.refs[b"HEAD"] = c3.id
  832. cfg = self.repo.get_config()
  833. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  834. cfg.write_to_path()
  835. self.import_default_key()
  836. # Create a signed tag
  837. porcelain.tag_create(
  838. self.repo.path,
  839. b"signed-tag",
  840. b"Tagger <tagger@example.com>",
  841. b"Signed tag message",
  842. annotated=True,
  843. sign=True,
  844. )
  845. # Verify should not raise
  846. porcelain.verify_tag(self.repo.path, b"signed-tag")
  847. porcelain.verify_tag(
  848. self.repo.path, b"signed-tag", keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID]
  849. )
  850. def test_verify_tag_with_wrong_key(self) -> None:
  851. """Test that verifying with wrong keyid raises MissingSignatures."""
  852. _c1, _c2, c3 = build_commit_graph(
  853. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  854. )
  855. self.repo.refs[b"HEAD"] = c3.id
  856. cfg = self.repo.get_config()
  857. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  858. cfg.write_to_path()
  859. self.import_default_key()
  860. porcelain.tag_create(
  861. self.repo.path,
  862. b"signed-tag",
  863. b"Tagger <tagger@example.com>",
  864. b"Signed tag message",
  865. annotated=True,
  866. sign=True,
  867. )
  868. self.import_non_default_key()
  869. self.assertRaises(
  870. gpg.errors.MissingSignatures,
  871. porcelain.verify_tag,
  872. self.repo.path,
  873. b"signed-tag",
  874. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  875. )
  876. def test_verify_tag_unsigned(self) -> None:
  877. """Test that verifying an unsigned tag succeeds (no signature to verify)."""
  878. _c1, _c2, c3 = build_commit_graph(
  879. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  880. )
  881. self.repo.refs[b"HEAD"] = c3.id
  882. porcelain.tag_create(
  883. self.repo.path,
  884. b"unsigned-tag",
  885. b"Tagger <tagger@example.com>",
  886. b"Unsigned tag message",
  887. annotated=True,
  888. sign=False,
  889. )
  890. # Verify should not raise for unsigned tags
  891. porcelain.verify_tag(self.repo.path, b"unsigned-tag")
  892. class TimezoneTests(PorcelainTestCase):
  893. def put_envs(self, value) -> None:
  894. self.overrideEnv("GIT_AUTHOR_DATE", value)
  895. self.overrideEnv("GIT_COMMITTER_DATE", value)
  896. def fallback(self, value) -> None:
  897. self.put_envs(value)
  898. self.assertRaises(porcelain.TimezoneFormatError, porcelain.get_user_timezones)
  899. def test_internal_format(self) -> None:
  900. self.put_envs("0 +0500")
  901. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  902. def test_rfc_2822(self) -> None:
  903. self.put_envs("Mon, 20 Nov 1995 19:12:08 -0500")
  904. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  905. self.put_envs("Mon, 20 Nov 1995 19:12:08")
  906. self.assertTupleEqual((0, 0), porcelain.get_user_timezones())
  907. def test_iso8601(self) -> None:
  908. self.put_envs("1995-11-20T19:12:08-0501")
  909. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  910. self.put_envs("1995-11-20T19:12:08+0501")
  911. self.assertTupleEqual((18060, 18060), porcelain.get_user_timezones())
  912. self.put_envs("1995-11-20T19:12:08-05:01")
  913. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  914. self.put_envs("1995-11-20 19:12:08-05")
  915. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  916. # https://github.com/git/git/blob/96b2d4fa927c5055adc5b1d08f10a5d7352e2989/t/t6300-for-each-ref.sh#L128
  917. self.put_envs("2006-07-03 17:18:44 +0200")
  918. self.assertTupleEqual((7200, 7200), porcelain.get_user_timezones())
  919. def test_missing_or_malformed(self) -> None:
  920. # TODO: add more here
  921. self.fallback("0 + 0500")
  922. self.fallback("a +0500")
  923. self.fallback("1995-11-20T19:12:08")
  924. self.fallback("1995-11-20T19:12:08-05:")
  925. self.fallback("1995.11.20")
  926. self.fallback("11/20/1995")
  927. self.fallback("20.11.1995")
  928. def test_different_envs(self) -> None:
  929. self.overrideEnv("GIT_AUTHOR_DATE", "0 +0500")
  930. self.overrideEnv("GIT_COMMITTER_DATE", "0 +0501")
  931. self.assertTupleEqual((18000, 18060), porcelain.get_user_timezones())
  932. def test_no_envs(self) -> None:
  933. local_timezone = time.localtime().tm_gmtoff
  934. self.put_envs("0 +0500")
  935. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  936. self.overrideEnv("GIT_COMMITTER_DATE", None)
  937. self.assertTupleEqual((18000, local_timezone), porcelain.get_user_timezones())
  938. self.put_envs("0 +0500")
  939. self.overrideEnv("GIT_AUTHOR_DATE", None)
  940. self.assertTupleEqual((local_timezone, 18000), porcelain.get_user_timezones())
  941. self.put_envs("0 +0500")
  942. self.overrideEnv("GIT_AUTHOR_DATE", None)
  943. self.overrideEnv("GIT_COMMITTER_DATE", None)
  944. self.assertTupleEqual(
  945. (local_timezone, local_timezone), porcelain.get_user_timezones()
  946. )
  947. class CleanTests(PorcelainTestCase):
  948. def put_files(self, tracked, ignored, untracked, empty_dirs) -> None:
  949. """Put the described files in the wd."""
  950. all_files = tracked | ignored | untracked
  951. for file_path in all_files:
  952. abs_path = os.path.join(self.repo.path, file_path)
  953. # File may need to be written in a dir that doesn't exist yet, so
  954. # create the parent dir(s) as necessary
  955. parent_dir = os.path.dirname(abs_path)
  956. try:
  957. os.makedirs(parent_dir)
  958. except FileExistsError:
  959. pass
  960. with open(abs_path, "w") as f:
  961. f.write("")
  962. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  963. f.writelines(ignored)
  964. for dir_path in empty_dirs:
  965. os.mkdir(os.path.join(self.repo.path, "empty_dir"))
  966. files_to_add = [os.path.join(self.repo.path, t) for t in tracked]
  967. porcelain.add(repo=self.repo.path, paths=files_to_add)
  968. porcelain.commit(repo=self.repo.path, message="init commit")
  969. def assert_wd(self, expected_paths) -> None:
  970. """Assert paths of files and dirs in wd are same as expected_paths."""
  971. control_dir_rel = os.path.relpath(self.repo._controldir, self.repo.path)
  972. # normalize paths to simplify comparison across platforms
  973. found_paths = {
  974. os.path.normpath(p)
  975. for p in flat_walk_dir(self.repo.path)
  976. if not p.split(os.sep)[0] == control_dir_rel
  977. }
  978. norm_expected_paths = {os.path.normpath(p) for p in expected_paths}
  979. self.assertEqual(found_paths, norm_expected_paths)
  980. def test_from_root(self) -> None:
  981. self.put_files(
  982. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  983. ignored={"ignored_file"},
  984. untracked={
  985. "untracked_file",
  986. "tracked_dir/untracked_dir/untracked_file",
  987. "untracked_dir/untracked_dir/untracked_file",
  988. },
  989. empty_dirs={"empty_dir"},
  990. )
  991. porcelain.clean(repo=self.repo.path, target_dir=self.repo.path)
  992. self.assert_wd(
  993. {
  994. "tracked_file",
  995. "tracked_dir/tracked_file",
  996. ".gitignore",
  997. "ignored_file",
  998. "tracked_dir",
  999. }
  1000. )
  1001. def test_from_subdir(self) -> None:
  1002. self.put_files(
  1003. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  1004. ignored={"ignored_file"},
  1005. untracked={
  1006. "untracked_file",
  1007. "tracked_dir/untracked_dir/untracked_file",
  1008. "untracked_dir/untracked_dir/untracked_file",
  1009. },
  1010. empty_dirs={"empty_dir"},
  1011. )
  1012. porcelain.clean(
  1013. repo=self.repo,
  1014. target_dir=os.path.join(self.repo.path, "untracked_dir"),
  1015. )
  1016. self.assert_wd(
  1017. {
  1018. "tracked_file",
  1019. "tracked_dir/tracked_file",
  1020. ".gitignore",
  1021. "ignored_file",
  1022. "untracked_file",
  1023. "tracked_dir/untracked_dir/untracked_file",
  1024. "empty_dir",
  1025. "untracked_dir",
  1026. "tracked_dir",
  1027. "tracked_dir/untracked_dir",
  1028. }
  1029. )
  1030. class CloneTests(PorcelainTestCase):
  1031. def test_simple_local(self) -> None:
  1032. f1_1 = make_object(Blob, data=b"f1")
  1033. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1034. trees = {
  1035. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1036. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1037. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1038. }
  1039. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1040. self.repo.refs[b"refs/heads/master"] = c3.id
  1041. self.repo.refs[b"refs/tags/foo"] = c3.id
  1042. target_path = tempfile.mkdtemp()
  1043. errstream = BytesIO()
  1044. self.addCleanup(shutil.rmtree, target_path)
  1045. r = porcelain.clone(
  1046. self.repo.path, target_path, checkout=False, errstream=errstream
  1047. )
  1048. self.addCleanup(r.close)
  1049. self.assertEqual(r.path, target_path)
  1050. target_repo = Repo(target_path)
  1051. self.addCleanup(target_repo.close)
  1052. self.assertEqual(0, len(target_repo.open_index()))
  1053. self.assertEqual(c3.id, target_repo.refs[b"refs/tags/foo"])
  1054. self.assertNotIn(b"f1", os.listdir(target_path))
  1055. self.assertNotIn(b"f2", os.listdir(target_path))
  1056. c = r.get_config()
  1057. encoded_path = self.repo.path
  1058. if not isinstance(encoded_path, bytes):
  1059. encoded_path_bytes = encoded_path.encode("utf-8")
  1060. else:
  1061. encoded_path_bytes = encoded_path
  1062. self.assertEqual(encoded_path_bytes, c.get((b"remote", b"origin"), b"url"))
  1063. self.assertEqual(
  1064. b"+refs/heads/*:refs/remotes/origin/*",
  1065. c.get((b"remote", b"origin"), b"fetch"),
  1066. )
  1067. def test_simple_local_with_checkout(self) -> None:
  1068. f1_1 = make_object(Blob, data=b"f1")
  1069. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1070. trees = {
  1071. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1072. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1073. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1074. }
  1075. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1076. self.repo.refs[b"refs/heads/master"] = c3.id
  1077. target_path = tempfile.mkdtemp()
  1078. errstream = BytesIO()
  1079. self.addCleanup(shutil.rmtree, target_path)
  1080. with porcelain.clone(
  1081. self.repo.path, target_path, checkout=True, errstream=errstream
  1082. ) as r:
  1083. self.assertEqual(r.path, target_path)
  1084. with Repo(target_path) as r:
  1085. self.assertEqual(r.head(), c3.id)
  1086. self.assertIn("f1", os.listdir(target_path))
  1087. self.assertIn("f2", os.listdir(target_path))
  1088. def test_bare_local_with_checkout(self) -> None:
  1089. f1_1 = make_object(Blob, data=b"f1")
  1090. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1091. trees = {
  1092. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1093. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1094. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1095. }
  1096. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1097. self.repo.refs[b"refs/heads/master"] = c3.id
  1098. target_path = tempfile.mkdtemp()
  1099. errstream = BytesIO()
  1100. self.addCleanup(shutil.rmtree, target_path)
  1101. with porcelain.clone(
  1102. self.repo.path, target_path, bare=True, errstream=errstream
  1103. ) as r:
  1104. self.assertEqual(r.path, target_path)
  1105. with Repo(target_path) as r:
  1106. r.head()
  1107. self.assertRaises(NoIndexPresent, r.open_index)
  1108. self.assertNotIn(b"f1", os.listdir(target_path))
  1109. self.assertNotIn(b"f2", os.listdir(target_path))
  1110. def test_no_checkout_with_bare(self) -> None:
  1111. f1_1 = make_object(Blob, data=b"f1")
  1112. commit_spec = [[1]]
  1113. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1114. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1115. self.repo.refs[b"refs/heads/master"] = c1.id
  1116. self.repo.refs[b"HEAD"] = c1.id
  1117. target_path = tempfile.mkdtemp()
  1118. errstream = BytesIO()
  1119. self.addCleanup(shutil.rmtree, target_path)
  1120. self.assertRaises(
  1121. porcelain.Error,
  1122. porcelain.clone,
  1123. self.repo.path,
  1124. target_path,
  1125. checkout=True,
  1126. bare=True,
  1127. errstream=errstream,
  1128. )
  1129. def test_no_head_no_checkout(self) -> None:
  1130. f1_1 = make_object(Blob, data=b"f1")
  1131. commit_spec = [[1]]
  1132. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1133. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1134. self.repo.refs[b"refs/heads/master"] = c1.id
  1135. target_path = tempfile.mkdtemp()
  1136. self.addCleanup(shutil.rmtree, target_path)
  1137. errstream = BytesIO()
  1138. r = porcelain.clone(
  1139. self.repo.path, target_path, checkout=True, errstream=errstream
  1140. )
  1141. r.close()
  1142. def test_no_head_no_checkout_outstream_errstream_autofallback(self) -> None:
  1143. f1_1 = make_object(Blob, data=b"f1")
  1144. commit_spec = [[1]]
  1145. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1146. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1147. self.repo.refs[b"refs/heads/master"] = c1.id
  1148. target_path = tempfile.mkdtemp()
  1149. self.addCleanup(shutil.rmtree, target_path)
  1150. errstream = porcelain.NoneStream()
  1151. r = porcelain.clone(
  1152. self.repo.path, target_path, checkout=True, errstream=errstream
  1153. )
  1154. r.close()
  1155. def test_source_broken(self) -> None:
  1156. with tempfile.TemporaryDirectory() as parent:
  1157. target_path = os.path.join(parent, "target")
  1158. self.assertRaises(
  1159. Exception, porcelain.clone, "/nonexistent/repo", target_path
  1160. )
  1161. self.assertFalse(os.path.exists(target_path))
  1162. def test_fetch_symref(self) -> None:
  1163. f1_1 = make_object(Blob, data=b"f1")
  1164. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1165. [c1] = build_commit_graph(self.repo.object_store, [[1]], trees)
  1166. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/else")
  1167. self.repo.refs[b"refs/heads/else"] = c1.id
  1168. target_path = tempfile.mkdtemp()
  1169. errstream = BytesIO()
  1170. self.addCleanup(shutil.rmtree, target_path)
  1171. r = porcelain.clone(
  1172. self.repo.path, target_path, checkout=False, errstream=errstream
  1173. )
  1174. self.addCleanup(r.close)
  1175. self.assertEqual(r.path, target_path)
  1176. target_repo = Repo(target_path)
  1177. self.addCleanup(target_repo.close)
  1178. self.assertEqual(0, len(target_repo.open_index()))
  1179. self.assertEqual(c1.id, target_repo.refs[b"refs/heads/else"])
  1180. self.assertEqual(c1.id, target_repo.refs[b"HEAD"])
  1181. self.assertEqual(
  1182. {
  1183. b"HEAD": b"refs/heads/else",
  1184. b"refs/remotes/origin/HEAD": b"refs/remotes/origin/else",
  1185. },
  1186. target_repo.refs.get_symrefs(),
  1187. )
  1188. def test_detached_head(self) -> None:
  1189. f1_1 = make_object(Blob, data=b"f1")
  1190. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1191. trees = {
  1192. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1193. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1194. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1195. }
  1196. _c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1197. self.repo.refs[b"refs/heads/master"] = c2.id
  1198. self.repo.refs.remove_if_equals(b"HEAD", None)
  1199. self.repo.refs[b"HEAD"] = c3.id
  1200. target_path = tempfile.mkdtemp()
  1201. self.addCleanup(shutil.rmtree, target_path)
  1202. errstream = porcelain.NoneStream()
  1203. with porcelain.clone(
  1204. self.repo.path, target_path, checkout=True, errstream=errstream
  1205. ) as r:
  1206. self.assertEqual(c3.id, r.refs[b"HEAD"])
  1207. def test_clone_pathlib(self) -> None:
  1208. from pathlib import Path
  1209. f1_1 = make_object(Blob, data=b"f1")
  1210. commit_spec = [[1]]
  1211. trees = {1: [(b"f1", f1_1)]}
  1212. c1 = build_commit_graph(self.repo.object_store, commit_spec, trees)[0]
  1213. self.repo.refs[b"refs/heads/master"] = c1.id
  1214. target_dir = tempfile.mkdtemp()
  1215. self.addCleanup(shutil.rmtree, target_dir)
  1216. target_path = Path(target_dir) / "clone_repo"
  1217. errstream = BytesIO()
  1218. r = porcelain.clone(
  1219. self.repo.path, target_path, checkout=False, errstream=errstream
  1220. )
  1221. self.addCleanup(r.close)
  1222. self.assertEqual(r.path, str(target_path))
  1223. self.assertTrue(os.path.exists(str(target_path)))
  1224. def test_clone_with_recurse_submodules(self) -> None:
  1225. # Create a submodule repository
  1226. sub_repo_path = tempfile.mkdtemp()
  1227. self.addCleanup(shutil.rmtree, sub_repo_path)
  1228. sub_repo = Repo.init(sub_repo_path)
  1229. self.addCleanup(sub_repo.close)
  1230. # Add a file to the submodule repo
  1231. sub_file = os.path.join(sub_repo_path, "subfile.txt")
  1232. with open(sub_file, "w") as f:
  1233. f.write("submodule content")
  1234. porcelain.add(sub_repo, paths=[sub_file])
  1235. sub_commit = porcelain.commit(
  1236. sub_repo,
  1237. message=b"Initial submodule commit",
  1238. author=b"Test Author <test@example.com>",
  1239. committer=b"Test Committer <test@example.com>",
  1240. )
  1241. # Create main repository with submodule
  1242. main_file = os.path.join(self.repo.path, "main.txt")
  1243. with open(main_file, "w") as f:
  1244. f.write("main content")
  1245. porcelain.add(self.repo, paths=[main_file])
  1246. porcelain.submodule_add(self.repo, sub_repo_path, "sub")
  1247. # Manually add the submodule to the index since submodule_add doesn't do it
  1248. # when the repository is local (to maintain backward compatibility)
  1249. from dulwich.index import IndexEntry
  1250. from dulwich.objects import S_IFGITLINK
  1251. index = self.repo.open_index()
  1252. index[b"sub"] = IndexEntry(
  1253. ctime=0,
  1254. mtime=0,
  1255. dev=0,
  1256. ino=0,
  1257. mode=S_IFGITLINK,
  1258. uid=0,
  1259. gid=0,
  1260. size=0,
  1261. sha=sub_commit,
  1262. flags=0,
  1263. )
  1264. index.write()
  1265. porcelain.add(self.repo, paths=[".gitmodules"])
  1266. porcelain.commit(
  1267. self.repo,
  1268. message=b"Add submodule",
  1269. author=b"Test Author <test@example.com>",
  1270. committer=b"Test Committer <test@example.com>",
  1271. )
  1272. # Clone with recurse_submodules
  1273. target_path = tempfile.mkdtemp()
  1274. self.addCleanup(shutil.rmtree, target_path)
  1275. cloned = porcelain.clone(
  1276. self.repo.path,
  1277. target_path,
  1278. recurse_submodules=True,
  1279. )
  1280. self.addCleanup(cloned.close)
  1281. # Check main file exists
  1282. cloned_main = os.path.join(target_path, "main.txt")
  1283. self.assertTrue(os.path.exists(cloned_main))
  1284. with open(cloned_main) as f:
  1285. self.assertEqual(f.read(), "main content")
  1286. # Check submodule file exists
  1287. cloned_sub_file = os.path.join(target_path, "sub", "subfile.txt")
  1288. self.assertTrue(os.path.exists(cloned_sub_file))
  1289. with open(cloned_sub_file) as f:
  1290. self.assertEqual(f.read(), "submodule content")
  1291. def test_clone_with_refspec_kwarg(self) -> None:
  1292. """Test that clone accepts refspec as a kwarg without TypeError.
  1293. This reproduces a bug where passing refspec as a kwarg to clone()
  1294. would cause a TypeError because it was being passed to
  1295. get_transport_and_path() which doesn't accept that parameter.
  1296. """
  1297. f1_1 = make_object(Blob, data=b"f1")
  1298. commit_spec = [[1]]
  1299. trees = {1: [(b"f1", f1_1)]}
  1300. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1301. self.repo.refs[b"refs/heads/master"] = c1.id
  1302. target_path = tempfile.mkdtemp()
  1303. errstream = BytesIO()
  1304. self.addCleanup(shutil.rmtree, target_path)
  1305. # This should not raise TypeError
  1306. r = porcelain.clone(
  1307. self.repo.path,
  1308. target_path,
  1309. checkout=False,
  1310. errstream=errstream,
  1311. refspec="refs/heads/master",
  1312. )
  1313. self.addCleanup(r.close)
  1314. self.assertEqual(r.path, target_path)
  1315. class InitTests(TestCase):
  1316. def test_non_bare(self) -> None:
  1317. repo_dir = tempfile.mkdtemp()
  1318. self.addCleanup(shutil.rmtree, repo_dir)
  1319. porcelain.init(repo_dir)
  1320. def test_bare(self) -> None:
  1321. repo_dir = tempfile.mkdtemp()
  1322. self.addCleanup(shutil.rmtree, repo_dir)
  1323. porcelain.init(repo_dir, bare=True)
  1324. def test_init_pathlib(self) -> None:
  1325. from pathlib import Path
  1326. repo_dir = tempfile.mkdtemp()
  1327. self.addCleanup(shutil.rmtree, repo_dir)
  1328. repo_path = Path(repo_dir)
  1329. # Test non-bare repo with pathlib
  1330. repo = porcelain.init(repo_path)
  1331. self.assertTrue(os.path.exists(os.path.join(repo_dir, ".git")))
  1332. repo.close()
  1333. def test_init_bare_pathlib(self) -> None:
  1334. from pathlib import Path
  1335. repo_dir = tempfile.mkdtemp()
  1336. self.addCleanup(shutil.rmtree, repo_dir)
  1337. repo_path = Path(repo_dir)
  1338. # Test bare repo with pathlib
  1339. repo = porcelain.init(repo_path, bare=True)
  1340. self.assertTrue(os.path.exists(os.path.join(repo_dir, "refs")))
  1341. repo.close()
  1342. class AddTests(PorcelainTestCase):
  1343. def test_add_default_paths(self) -> None:
  1344. # create a file for initial commit
  1345. fullpath = os.path.join(self.repo.path, "blah")
  1346. with open(fullpath, "w") as f:
  1347. f.write("\n")
  1348. porcelain.add(repo=self.repo.path, paths=[fullpath])
  1349. porcelain.commit(
  1350. repo=self.repo.path,
  1351. message=b"test",
  1352. author=b"test <email>",
  1353. committer=b"test <email>",
  1354. )
  1355. # Add a second test file and a file in a directory
  1356. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1357. f.write("\n")
  1358. os.mkdir(os.path.join(self.repo.path, "adir"))
  1359. with open(os.path.join(self.repo.path, "adir", "afile"), "w") as f:
  1360. f.write("\n")
  1361. cwd = os.getcwd()
  1362. self.addCleanup(os.chdir, cwd)
  1363. os.chdir(self.repo.path)
  1364. self.assertEqual({"foo", "blah", "adir", ".git"}, set(os.listdir(".")))
  1365. added, ignored = porcelain.add(self.repo.path)
  1366. # Normalize paths to use forward slashes for comparison
  1367. added_normalized = [path.replace(os.sep, "/") for path in added]
  1368. self.assertEqual(
  1369. (added_normalized, ignored),
  1370. (["foo", "adir/afile"], set()),
  1371. )
  1372. # Check that foo was added and nothing in .git was modified
  1373. index = self.repo.open_index()
  1374. self.assertEqual(sorted(index), [b"adir/afile", b"blah", b"foo"])
  1375. def test_add_default_paths_subdir(self) -> None:
  1376. os.mkdir(os.path.join(self.repo.path, "foo"))
  1377. with open(os.path.join(self.repo.path, "blah"), "w") as f:
  1378. f.write("\n")
  1379. with open(os.path.join(self.repo.path, "foo", "blie"), "w") as f:
  1380. f.write("\n")
  1381. cwd = os.getcwd()
  1382. self.addCleanup(os.chdir, cwd)
  1383. os.chdir(os.path.join(self.repo.path, "foo"))
  1384. porcelain.add(repo=self.repo.path)
  1385. porcelain.commit(
  1386. repo=self.repo.path,
  1387. message=b"test",
  1388. author=b"test <email>",
  1389. committer=b"test <email>",
  1390. )
  1391. index = self.repo.open_index()
  1392. # After fix: add() with no paths should behave like git add -A (add everything)
  1393. self.assertEqual(sorted(index), [b"blah", b"foo/blie"])
  1394. def test_add_file(self) -> None:
  1395. fullpath = os.path.join(self.repo.path, "foo")
  1396. with open(fullpath, "w") as f:
  1397. f.write("BAR")
  1398. porcelain.add(self.repo.path, paths=[fullpath])
  1399. self.assertIn(b"foo", self.repo.open_index())
  1400. def test_add_ignored(self) -> None:
  1401. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1402. f.write("foo\nsubdir/")
  1403. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1404. f.write("BAR")
  1405. with open(os.path.join(self.repo.path, "bar"), "w") as f:
  1406. f.write("BAR")
  1407. os.mkdir(os.path.join(self.repo.path, "subdir"))
  1408. with open(os.path.join(self.repo.path, "subdir", "baz"), "w") as f:
  1409. f.write("BAZ")
  1410. (added, ignored) = porcelain.add(
  1411. self.repo.path,
  1412. paths=[
  1413. os.path.join(self.repo.path, "foo"),
  1414. os.path.join(self.repo.path, "bar"),
  1415. os.path.join(self.repo.path, "subdir"),
  1416. ],
  1417. )
  1418. self.assertIn(b"bar", self.repo.open_index())
  1419. self.assertEqual({"bar"}, set(added))
  1420. self.assertEqual({"foo", "subdir/"}, ignored)
  1421. def test_add_from_ignored_directory(self) -> None:
  1422. # Test for issue #550 - adding files when cwd is in ignored directory
  1423. # Create .gitignore that ignores build/
  1424. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1425. f.write("build/\n")
  1426. # Create ignored directory
  1427. build_dir = os.path.join(self.repo.path, "build")
  1428. os.mkdir(build_dir)
  1429. # Create a file in the repo (not in ignored directory)
  1430. src_file = os.path.join(self.repo.path, "source.py")
  1431. with open(src_file, "w") as f:
  1432. f.write("print('hello')\n")
  1433. # Save current directory and change to ignored directory
  1434. original_cwd = os.getcwd()
  1435. try:
  1436. os.chdir(build_dir)
  1437. # Add file using absolute path from within ignored directory
  1438. (added, _ignored) = porcelain.add(self.repo.path, paths=[src_file])
  1439. self.assertIn(b"source.py", self.repo.open_index())
  1440. self.assertEqual({"source.py"}, set(added))
  1441. finally:
  1442. os.chdir(original_cwd)
  1443. def test_add_file_absolute_path(self) -> None:
  1444. # Absolute paths are (not yet) supported
  1445. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1446. f.write("BAR")
  1447. porcelain.add(self.repo, paths=[os.path.join(self.repo.path, "foo")])
  1448. self.assertIn(b"foo", self.repo.open_index())
  1449. def test_add_not_in_repo(self) -> None:
  1450. with open(os.path.join(self.test_dir, "foo"), "w") as f:
  1451. f.write("BAR")
  1452. self.assertRaises(
  1453. ValueError,
  1454. porcelain.add,
  1455. self.repo,
  1456. paths=[os.path.join(self.test_dir, "foo")],
  1457. )
  1458. self.assertRaises(
  1459. (ValueError, FileNotFoundError),
  1460. porcelain.add,
  1461. self.repo,
  1462. paths=["../foo"],
  1463. )
  1464. self.assertEqual([], list(self.repo.open_index()))
  1465. def test_add_file_clrf_conversion(self) -> None:
  1466. from dulwich.index import IndexEntry
  1467. # Set the right configuration to the repo
  1468. c = self.repo.get_config()
  1469. c.set("core", "autocrlf", "input")
  1470. c.write_to_path()
  1471. # Add a file with CRLF line-ending
  1472. fullpath = os.path.join(self.repo.path, "foo")
  1473. with open(fullpath, "wb") as f:
  1474. f.write(b"line1\r\nline2")
  1475. porcelain.add(self.repo.path, paths=[fullpath])
  1476. # The line-endings should have been converted to LF
  1477. index = self.repo.open_index()
  1478. self.assertIn(b"foo", index)
  1479. entry = index[b"foo"]
  1480. assert isinstance(entry, IndexEntry)
  1481. blob = self.repo[entry.sha]
  1482. self.assertEqual(blob.data, b"line1\nline2")
  1483. def test_add_symlink_outside_repo(self) -> None:
  1484. """Test adding a symlink that points outside the repository."""
  1485. # Create a symlink pointing outside the repository
  1486. symlink_path = os.path.join(self.repo.path, "symlink_to_nowhere")
  1487. os.symlink("/nonexistent/path", symlink_path)
  1488. # Adding the symlink should succeed (matching Git's behavior)
  1489. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1490. # Should successfully add the symlink
  1491. self.assertIn("symlink_to_nowhere", added)
  1492. self.assertEqual(len(ignored), 0)
  1493. # Verify symlink is actually staged
  1494. index = self.repo.open_index()
  1495. self.assertIn(b"symlink_to_nowhere", index)
  1496. def test_add_symlink_to_file_inside_repo(self) -> None:
  1497. """Test adding a symlink that points to a file inside the repository."""
  1498. # Create a regular file
  1499. target_file = os.path.join(self.repo.path, "target.txt")
  1500. with open(target_file, "w") as f:
  1501. f.write("target content")
  1502. # Create a symlink to the file
  1503. symlink_path = os.path.join(self.repo.path, "link_to_target")
  1504. os.symlink("target.txt", symlink_path)
  1505. # Add both the target and the symlink
  1506. added, ignored = porcelain.add(
  1507. self.repo.path, paths=[target_file, symlink_path]
  1508. )
  1509. # Both should be added successfully
  1510. self.assertIn("target.txt", added)
  1511. self.assertIn("link_to_target", added)
  1512. self.assertEqual(len(ignored), 0)
  1513. # Verify both are in the index
  1514. index = self.repo.open_index()
  1515. self.assertIn(b"target.txt", index)
  1516. self.assertIn(b"link_to_target", index)
  1517. def test_add_symlink_to_directory_inside_repo(self) -> None:
  1518. """Test adding a symlink that points to a directory inside the repository."""
  1519. # Create a directory with some files
  1520. target_dir = os.path.join(self.repo.path, "target_dir")
  1521. os.mkdir(target_dir)
  1522. with open(os.path.join(target_dir, "file1.txt"), "w") as f:
  1523. f.write("content1")
  1524. with open(os.path.join(target_dir, "file2.txt"), "w") as f:
  1525. f.write("content2")
  1526. # Create a symlink to the directory
  1527. symlink_path = os.path.join(self.repo.path, "link_to_dir")
  1528. os.symlink("target_dir", symlink_path)
  1529. # Add the symlink
  1530. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1531. # When adding a symlink to a directory, it follows the symlink and adds contents
  1532. self.assertEqual(len(added), 2)
  1533. self.assertIn("link_to_dir/file1.txt", added)
  1534. self.assertIn("link_to_dir/file2.txt", added)
  1535. self.assertEqual(len(ignored), 0)
  1536. # Verify files are added through the symlink path
  1537. index = self.repo.open_index()
  1538. self.assertIn(b"link_to_dir/file1.txt", index)
  1539. self.assertIn(b"link_to_dir/file2.txt", index)
  1540. # The original target directory files are not added
  1541. self.assertNotIn(b"target_dir/file1.txt", index)
  1542. self.assertNotIn(b"target_dir/file2.txt", index)
  1543. def test_add_symlink_chain(self) -> None:
  1544. """Test adding a chain of symlinks (symlink to symlink)."""
  1545. # Create a regular file
  1546. target_file = os.path.join(self.repo.path, "original.txt")
  1547. with open(target_file, "w") as f:
  1548. f.write("original content")
  1549. # Create first symlink
  1550. first_link = os.path.join(self.repo.path, "link1")
  1551. os.symlink("original.txt", first_link)
  1552. # Create second symlink pointing to first
  1553. second_link = os.path.join(self.repo.path, "link2")
  1554. os.symlink("link1", second_link)
  1555. # Add all files
  1556. added, _ignored = porcelain.add(
  1557. self.repo.path, paths=[target_file, first_link, second_link]
  1558. )
  1559. # All should be added
  1560. self.assertEqual(len(added), 3)
  1561. self.assertIn("original.txt", added)
  1562. self.assertIn("link1", added)
  1563. self.assertIn("link2", added)
  1564. # Verify all are in the index
  1565. index = self.repo.open_index()
  1566. self.assertIn(b"original.txt", index)
  1567. self.assertIn(b"link1", index)
  1568. self.assertIn(b"link2", index)
  1569. def test_add_broken_symlink(self) -> None:
  1570. """Test adding a broken symlink (points to non-existent target)."""
  1571. # Create a symlink to a non-existent file
  1572. broken_link = os.path.join(self.repo.path, "broken_link")
  1573. os.symlink("does_not_exist.txt", broken_link)
  1574. # Add the broken symlink
  1575. added, ignored = porcelain.add(self.repo.path, paths=[broken_link])
  1576. # Should be added successfully (Git tracks the symlink, not its target)
  1577. self.assertIn("broken_link", added)
  1578. self.assertEqual(len(ignored), 0)
  1579. # Verify it's in the index
  1580. index = self.repo.open_index()
  1581. self.assertIn(b"broken_link", index)
  1582. def test_add_symlink_relative_outside_repo(self) -> None:
  1583. """Test adding a symlink that uses '..' to point outside the repository."""
  1584. # Create a file outside the repo
  1585. outside_file = os.path.join(self.test_dir, "outside.txt")
  1586. with open(outside_file, "w") as f:
  1587. f.write("outside content")
  1588. # Create a symlink using relative path to go outside
  1589. symlink_path = os.path.join(self.repo.path, "link_outside")
  1590. os.symlink("../outside.txt", symlink_path)
  1591. # Add the symlink
  1592. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1593. # Should be added successfully
  1594. self.assertIn("link_outside", added)
  1595. self.assertEqual(len(ignored), 0)
  1596. # Verify it's in the index
  1597. index = self.repo.open_index()
  1598. self.assertIn(b"link_outside", index)
  1599. def test_add_symlink_absolute_to_system(self) -> None:
  1600. """Test adding a symlink with absolute path to system directory."""
  1601. # Create a symlink to a system directory
  1602. symlink_path = os.path.join(self.repo.path, "link_to_tmp")
  1603. if os.name == "nt":
  1604. # On Windows, use a system directory like TEMP
  1605. symlink_target = os.environ["TEMP"]
  1606. else:
  1607. # On Unix-like systems, use /tmp
  1608. symlink_target = os.environ.get("TMPDIR", "/tmp")
  1609. os.symlink(symlink_target, symlink_path)
  1610. # Adding a symlink to a directory outside the repo should raise ValueError
  1611. with self.assertRaises(ValueError) as cm:
  1612. porcelain.add(self.repo.path, paths=[symlink_path])
  1613. # Check that the error indicates the path is outside the repository
  1614. self.assertIn("is not in the subpath of", str(cm.exception))
  1615. def test_add_file_through_symlink(self) -> None:
  1616. """Test adding a file through a symlinked directory."""
  1617. # Create a directory with a file
  1618. real_dir = os.path.join(self.repo.path, "real_dir")
  1619. os.mkdir(real_dir)
  1620. real_file = os.path.join(real_dir, "file.txt")
  1621. with open(real_file, "w") as f:
  1622. f.write("content")
  1623. # Create a symlink to the directory
  1624. link_dir = os.path.join(self.repo.path, "link_dir")
  1625. os.symlink("real_dir", link_dir)
  1626. # Try to add the file through the symlink path
  1627. symlink_file_path = os.path.join(link_dir, "file.txt")
  1628. # This should add the real file, not create a new entry
  1629. added, _ignored = porcelain.add(self.repo.path, paths=[symlink_file_path])
  1630. # The real file should be added
  1631. self.assertIn("real_dir/file.txt", added)
  1632. self.assertEqual(len(added), 1)
  1633. # Verify correct path in index
  1634. index = self.repo.open_index()
  1635. self.assertIn(b"real_dir/file.txt", index)
  1636. # Should not create a separate entry for the symlink path
  1637. self.assertNotIn(b"link_dir/file.txt", index)
  1638. def test_add_repo_path(self) -> None:
  1639. """Test adding the repository path itself should add all untracked files."""
  1640. # Create some untracked files
  1641. with open(os.path.join(self.repo.path, "file1.txt"), "w") as f:
  1642. f.write("content1")
  1643. with open(os.path.join(self.repo.path, "file2.txt"), "w") as f:
  1644. f.write("content2")
  1645. # Add the repository path itself
  1646. added, _ignored = porcelain.add(self.repo.path, paths=[self.repo.path])
  1647. # Should add all untracked files, not stage './'
  1648. self.assertIn("file1.txt", added)
  1649. self.assertIn("file2.txt", added)
  1650. self.assertNotIn("./", added)
  1651. # Verify files are actually staged
  1652. index = self.repo.open_index()
  1653. self.assertIn(b"file1.txt", index)
  1654. self.assertIn(b"file2.txt", index)
  1655. def test_add_directory_contents(self) -> None:
  1656. """Test adding a directory adds all files within it."""
  1657. # Create a subdirectory with multiple files
  1658. subdir = os.path.join(self.repo.path, "subdir")
  1659. os.mkdir(subdir)
  1660. with open(os.path.join(subdir, "file1.txt"), "w") as f:
  1661. f.write("content1")
  1662. with open(os.path.join(subdir, "file2.txt"), "w") as f:
  1663. f.write("content2")
  1664. with open(os.path.join(subdir, "file3.txt"), "w") as f:
  1665. f.write("content3")
  1666. # Add the directory
  1667. added, _ignored = porcelain.add(self.repo.path, paths=["subdir"])
  1668. # Should add all files in the directory
  1669. self.assertEqual(len(added), 3)
  1670. # Normalize paths to use forward slashes for comparison
  1671. added_normalized = [path.replace(os.sep, "/") for path in added]
  1672. self.assertIn("subdir/file1.txt", added_normalized)
  1673. self.assertIn("subdir/file2.txt", added_normalized)
  1674. self.assertIn("subdir/file3.txt", added_normalized)
  1675. # Verify files are actually staged
  1676. index = self.repo.open_index()
  1677. self.assertIn(b"subdir/file1.txt", index)
  1678. self.assertIn(b"subdir/file2.txt", index)
  1679. self.assertIn(b"subdir/file3.txt", index)
  1680. def test_add_nested_directories(self) -> None:
  1681. """Test adding a directory with nested subdirectories."""
  1682. # Create nested directory structure
  1683. dir1 = os.path.join(self.repo.path, "dir1")
  1684. dir2 = os.path.join(dir1, "dir2")
  1685. dir3 = os.path.join(dir2, "dir3")
  1686. os.makedirs(dir3)
  1687. # Add files at each level
  1688. with open(os.path.join(dir1, "file1.txt"), "w") as f:
  1689. f.write("level1")
  1690. with open(os.path.join(dir2, "file2.txt"), "w") as f:
  1691. f.write("level2")
  1692. with open(os.path.join(dir3, "file3.txt"), "w") as f:
  1693. f.write("level3")
  1694. # Add the top-level directory
  1695. added, _ignored = porcelain.add(self.repo.path, paths=["dir1"])
  1696. # Should add all files recursively
  1697. self.assertEqual(len(added), 3)
  1698. # Normalize paths to use forward slashes for comparison
  1699. added_normalized = [path.replace(os.sep, "/") for path in added]
  1700. self.assertIn("dir1/file1.txt", added_normalized)
  1701. self.assertIn("dir1/dir2/file2.txt", added_normalized)
  1702. self.assertIn("dir1/dir2/dir3/file3.txt", added_normalized)
  1703. # Verify files are actually staged
  1704. index = self.repo.open_index()
  1705. self.assertIn(b"dir1/file1.txt", index)
  1706. self.assertIn(b"dir1/dir2/file2.txt", index)
  1707. self.assertIn(b"dir1/dir2/dir3/file3.txt", index)
  1708. def test_add_directory_with_tracked_files(self) -> None:
  1709. """Test adding a directory with some files already tracked."""
  1710. # Create a subdirectory with files
  1711. subdir = os.path.join(self.repo.path, "mixed")
  1712. os.mkdir(subdir)
  1713. # Create and commit one file
  1714. tracked_file = os.path.join(subdir, "tracked.txt")
  1715. with open(tracked_file, "w") as f:
  1716. f.write("already tracked")
  1717. porcelain.add(self.repo.path, paths=[tracked_file])
  1718. porcelain.commit(
  1719. repo=self.repo.path,
  1720. message=b"Add tracked file",
  1721. author=b"test <email>",
  1722. committer=b"test <email>",
  1723. )
  1724. # Add more untracked files
  1725. with open(os.path.join(subdir, "untracked1.txt"), "w") as f:
  1726. f.write("new file 1")
  1727. with open(os.path.join(subdir, "untracked2.txt"), "w") as f:
  1728. f.write("new file 2")
  1729. # Add the directory
  1730. added, _ignored = porcelain.add(self.repo.path, paths=["mixed"])
  1731. # Should only add the untracked files
  1732. self.assertEqual(len(added), 2)
  1733. # Normalize paths to use forward slashes for comparison
  1734. added_normalized = [path.replace(os.sep, "/") for path in added]
  1735. self.assertIn("mixed/untracked1.txt", added_normalized)
  1736. self.assertIn("mixed/untracked2.txt", added_normalized)
  1737. self.assertNotIn("mixed/tracked.txt", added)
  1738. # Verify the index contains all files
  1739. index = self.repo.open_index()
  1740. self.assertIn(b"mixed/tracked.txt", index)
  1741. self.assertIn(b"mixed/untracked1.txt", index)
  1742. self.assertIn(b"mixed/untracked2.txt", index)
  1743. def test_add_directory_with_gitignore(self) -> None:
  1744. """Test adding a directory respects .gitignore patterns."""
  1745. # Create .gitignore
  1746. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1747. f.write("*.log\n*.tmp\nbuild/\n")
  1748. # Create directory with mixed files
  1749. testdir = os.path.join(self.repo.path, "testdir")
  1750. os.mkdir(testdir)
  1751. # Create various files
  1752. with open(os.path.join(testdir, "important.txt"), "w") as f:
  1753. f.write("keep this")
  1754. with open(os.path.join(testdir, "debug.log"), "w") as f:
  1755. f.write("ignore this")
  1756. with open(os.path.join(testdir, "temp.tmp"), "w") as f:
  1757. f.write("ignore this too")
  1758. with open(os.path.join(testdir, "readme.md"), "w") as f:
  1759. f.write("keep this too")
  1760. # Create a build directory that should be ignored
  1761. builddir = os.path.join(testdir, "build")
  1762. os.mkdir(builddir)
  1763. with open(os.path.join(builddir, "output.txt"), "w") as f:
  1764. f.write("ignore entire directory")
  1765. # Add the directory
  1766. added, ignored = porcelain.add(self.repo.path, paths=["testdir"])
  1767. # Should only add non-ignored files
  1768. # Normalize paths to use forward slashes for comparison
  1769. added_normalized = {path.replace(os.sep, "/") for path in added}
  1770. self.assertEqual(
  1771. added_normalized, {"testdir/important.txt", "testdir/readme.md"}
  1772. )
  1773. # Check ignored files
  1774. # Normalize paths to use forward slashes for comparison
  1775. ignored_normalized = {path.replace(os.sep, "/") for path in ignored}
  1776. self.assertIn("testdir/debug.log", ignored_normalized)
  1777. self.assertIn("testdir/temp.tmp", ignored_normalized)
  1778. self.assertIn("testdir/build/", ignored_normalized)
  1779. def test_add_multiple_directories(self) -> None:
  1780. """Test adding multiple directories in one call."""
  1781. # Create multiple directories
  1782. for dirname in ["dir1", "dir2", "dir3"]:
  1783. dirpath = os.path.join(self.repo.path, dirname)
  1784. os.mkdir(dirpath)
  1785. # Add files to each directory
  1786. for i in range(2):
  1787. with open(os.path.join(dirpath, f"file{i}.txt"), "w") as f:
  1788. f.write(f"content {dirname} {i}")
  1789. # Add all directories at once
  1790. added, _ignored = porcelain.add(self.repo.path, paths=["dir1", "dir2", "dir3"])
  1791. # Should add all files from all directories
  1792. self.assertEqual(len(added), 6)
  1793. # Normalize paths to use forward slashes for comparison
  1794. added_normalized = [path.replace(os.sep, "/") for path in added]
  1795. for dirname in ["dir1", "dir2", "dir3"]:
  1796. for i in range(2):
  1797. self.assertIn(f"{dirname}/file{i}.txt", added_normalized)
  1798. # Verify all files are staged
  1799. index = self.repo.open_index()
  1800. self.assertEqual(len(index), 6)
  1801. def test_add_default_paths_includes_modified_files(self) -> None:
  1802. """Test that add() with no paths includes both untracked and modified files."""
  1803. # Create and commit initial file
  1804. initial_file = os.path.join(self.repo.path, "existing.txt")
  1805. with open(initial_file, "w") as f:
  1806. f.write("initial content\n")
  1807. porcelain.add(repo=self.repo.path, paths=[initial_file])
  1808. porcelain.commit(
  1809. repo=self.repo.path,
  1810. message=b"initial commit",
  1811. author=b"test <email>",
  1812. committer=b"test <email>",
  1813. )
  1814. # Modify the existing file (this creates an unstaged change)
  1815. with open(initial_file, "w") as f:
  1816. f.write("modified content\n")
  1817. # Create a new untracked file
  1818. new_file = os.path.join(self.repo.path, "new.txt")
  1819. with open(new_file, "w") as f:
  1820. f.write("new file content\n")
  1821. # Call add() with no paths - should stage both modified and untracked files
  1822. added_files, ignored_files = porcelain.add(repo=self.repo.path)
  1823. # Verify both files were added
  1824. self.assertIn("existing.txt", added_files)
  1825. self.assertIn("new.txt", added_files)
  1826. self.assertEqual(len(ignored_files), 0)
  1827. # Verify both files are now staged
  1828. index = self.repo.open_index()
  1829. self.assertIn(b"existing.txt", index)
  1830. self.assertIn(b"new.txt", index)
  1831. class RemoveTests(PorcelainTestCase):
  1832. def test_remove_file(self) -> None:
  1833. fullpath = os.path.join(self.repo.path, "foo")
  1834. with open(fullpath, "w") as f:
  1835. f.write("BAR")
  1836. porcelain.add(self.repo.path, paths=[fullpath])
  1837. porcelain.commit(
  1838. repo=self.repo,
  1839. message=b"test",
  1840. author=b"test <email>",
  1841. committer=b"test <email>",
  1842. )
  1843. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "foo")))
  1844. cwd = os.getcwd()
  1845. self.addCleanup(os.chdir, cwd)
  1846. os.chdir(self.repo.path)
  1847. porcelain.remove(self.repo.path, paths=["foo"])
  1848. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1849. def test_remove_file_staged(self) -> None:
  1850. fullpath = os.path.join(self.repo.path, "foo")
  1851. with open(fullpath, "w") as f:
  1852. f.write("BAR")
  1853. cwd = os.getcwd()
  1854. self.addCleanup(os.chdir, cwd)
  1855. os.chdir(self.repo.path)
  1856. porcelain.add(self.repo.path, paths=[fullpath])
  1857. self.assertRaises(Exception, porcelain.rm, self.repo.path, paths=["foo"])
  1858. def test_remove_file_removed_on_disk(self) -> None:
  1859. fullpath = os.path.join(self.repo.path, "foo")
  1860. with open(fullpath, "w") as f:
  1861. f.write("BAR")
  1862. porcelain.add(self.repo.path, paths=[fullpath])
  1863. cwd = os.getcwd()
  1864. self.addCleanup(os.chdir, cwd)
  1865. os.chdir(self.repo.path)
  1866. os.remove(fullpath)
  1867. porcelain.remove(self.repo.path, paths=["foo"])
  1868. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1869. def test_remove_from_different_directory(self) -> None:
  1870. # Create a subdirectory with a file
  1871. subdir = os.path.join(self.repo.path, "mydir")
  1872. os.makedirs(subdir)
  1873. fullpath = os.path.join(subdir, "myfile")
  1874. with open(fullpath, "w") as f:
  1875. f.write("BAR")
  1876. # Add and commit the file
  1877. porcelain.add(self.repo.path, paths=[fullpath])
  1878. porcelain.commit(
  1879. repo=self.repo,
  1880. message=b"test",
  1881. author=b"test <email>",
  1882. committer=b"test <email>",
  1883. )
  1884. # Change to a different directory
  1885. cwd = os.getcwd()
  1886. tempdir = tempfile.mkdtemp()
  1887. def cleanup():
  1888. os.chdir(cwd)
  1889. shutil.rmtree(tempdir)
  1890. self.addCleanup(cleanup)
  1891. os.chdir(tempdir)
  1892. # Remove the file using relative path from repository root
  1893. porcelain.remove(self.repo.path, paths=["mydir/myfile"])
  1894. # Verify file was removed
  1895. self.assertFalse(os.path.exists(fullpath))
  1896. def test_remove_with_absolute_path(self) -> None:
  1897. # Create a file
  1898. fullpath = os.path.join(self.repo.path, "foo")
  1899. with open(fullpath, "w") as f:
  1900. f.write("BAR")
  1901. # Add and commit the file
  1902. porcelain.add(self.repo.path, paths=[fullpath])
  1903. porcelain.commit(
  1904. repo=self.repo,
  1905. message=b"test",
  1906. author=b"test <email>",
  1907. committer=b"test <email>",
  1908. )
  1909. # Change to a different directory
  1910. cwd = os.getcwd()
  1911. tempdir = tempfile.mkdtemp()
  1912. def cleanup():
  1913. os.chdir(cwd)
  1914. shutil.rmtree(tempdir)
  1915. self.addCleanup(cleanup)
  1916. os.chdir(tempdir)
  1917. # Remove the file using absolute path
  1918. porcelain.remove(self.repo.path, paths=[fullpath])
  1919. # Verify file was removed
  1920. self.assertFalse(os.path.exists(fullpath))
  1921. def test_remove_with_filter_normalization(self) -> None:
  1922. # Enable autocrlf to normalize line endings
  1923. config = self.repo.get_config()
  1924. config.set(("core",), "autocrlf", b"true")
  1925. config.write_to_path()
  1926. # Create a file with LF line endings (will be stored with LF in index)
  1927. fullpath = os.path.join(self.repo.path, "foo.txt")
  1928. with open(fullpath, "wb") as f:
  1929. f.write(b"line1\nline2\nline3")
  1930. # Add and commit the file (stored with LF in index)
  1931. porcelain.add(self.repo.path, paths=[fullpath])
  1932. porcelain.commit(
  1933. repo=self.repo,
  1934. message=b"Add file with LF",
  1935. author=b"test <email>",
  1936. committer=b"test <email>",
  1937. )
  1938. # Simulate checkout with CRLF conversion (as would happen on Windows)
  1939. with open(fullpath, "wb") as f:
  1940. f.write(b"line1\r\nline2\r\nline3")
  1941. # Verify file exists
  1942. self.assertTrue(os.path.exists(fullpath))
  1943. # Remove the file - this should not fail even though working tree has CRLF
  1944. # and index has LF (thanks to the normalization in the commit)
  1945. cwd = os.getcwd()
  1946. os.chdir(self.repo.path)
  1947. self.addCleanup(os.chdir, cwd)
  1948. porcelain.remove(self.repo.path, paths=["foo.txt"])
  1949. # Verify file was removed
  1950. self.assertFalse(os.path.exists(fullpath))
  1951. class MvTests(PorcelainTestCase):
  1952. def test_mv_file(self) -> None:
  1953. # Create a file
  1954. fullpath = os.path.join(self.repo.path, "foo")
  1955. with open(fullpath, "w") as f:
  1956. f.write("BAR")
  1957. # Add and commit the file
  1958. porcelain.add(self.repo.path, paths=[fullpath])
  1959. porcelain.commit(
  1960. repo=self.repo,
  1961. message=b"test",
  1962. author=b"test <email>",
  1963. committer=b"test <email>",
  1964. )
  1965. # Move the file
  1966. porcelain.mv(self.repo.path, "foo", "bar")
  1967. # Verify old path doesn't exist and new path does
  1968. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1969. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "bar")))
  1970. # Verify index was updated
  1971. index = self.repo.open_index()
  1972. self.assertNotIn(b"foo", index)
  1973. self.assertIn(b"bar", index)
  1974. def test_mv_file_to_existing_directory(self) -> None:
  1975. # Create a file and a directory
  1976. fullpath = os.path.join(self.repo.path, "foo")
  1977. with open(fullpath, "w") as f:
  1978. f.write("BAR")
  1979. dirpath = os.path.join(self.repo.path, "mydir")
  1980. os.makedirs(dirpath)
  1981. # Add and commit the file
  1982. porcelain.add(self.repo.path, paths=[fullpath])
  1983. porcelain.commit(
  1984. repo=self.repo,
  1985. message=b"test",
  1986. author=b"test <email>",
  1987. committer=b"test <email>",
  1988. )
  1989. # Move the file into the directory
  1990. porcelain.mv(self.repo.path, "foo", "mydir")
  1991. # Verify file moved into directory
  1992. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1993. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "mydir", "foo")))
  1994. # Verify index was updated
  1995. index = self.repo.open_index()
  1996. self.assertNotIn(b"foo", index)
  1997. self.assertIn(b"mydir/foo", index)
  1998. def test_mv_file_force_overwrite(self) -> None:
  1999. # Create two files
  2000. fullpath1 = os.path.join(self.repo.path, "foo")
  2001. with open(fullpath1, "w") as f:
  2002. f.write("FOO")
  2003. fullpath2 = os.path.join(self.repo.path, "bar")
  2004. with open(fullpath2, "w") as f:
  2005. f.write("BAR")
  2006. # Add and commit both files
  2007. porcelain.add(self.repo.path, paths=[fullpath1, fullpath2])
  2008. porcelain.commit(
  2009. repo=self.repo,
  2010. message=b"test",
  2011. author=b"test <email>",
  2012. committer=b"test <email>",
  2013. )
  2014. # Try to move without force (should fail)
  2015. self.assertRaises(porcelain.Error, porcelain.mv, self.repo.path, "foo", "bar")
  2016. # Move with force
  2017. porcelain.mv(self.repo.path, "foo", "bar", force=True)
  2018. # Verify foo doesn't exist and bar has foo's content
  2019. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  2020. with open(os.path.join(self.repo.path, "bar")) as f:
  2021. self.assertEqual(f.read(), "FOO")
  2022. def test_mv_file_not_tracked(self) -> None:
  2023. # Create an untracked file
  2024. fullpath = os.path.join(self.repo.path, "untracked")
  2025. with open(fullpath, "w") as f:
  2026. f.write("UNTRACKED")
  2027. # Try to move it (should fail)
  2028. self.assertRaises(
  2029. porcelain.Error, porcelain.mv, self.repo.path, "untracked", "tracked"
  2030. )
  2031. def test_mv_file_not_exists(self) -> None:
  2032. # Try to move a non-existent file
  2033. self.assertRaises(
  2034. porcelain.Error, porcelain.mv, self.repo.path, "nonexistent", "destination"
  2035. )
  2036. def test_mv_absolute_paths(self) -> None:
  2037. # Create a file
  2038. fullpath = os.path.join(self.repo.path, "foo")
  2039. with open(fullpath, "w") as f:
  2040. f.write("BAR")
  2041. # Add and commit the file
  2042. porcelain.add(self.repo.path, paths=[fullpath])
  2043. porcelain.commit(
  2044. repo=self.repo,
  2045. message=b"test",
  2046. author=b"test <email>",
  2047. committer=b"test <email>",
  2048. )
  2049. # Move using absolute paths
  2050. dest_path = os.path.join(self.repo.path, "bar")
  2051. porcelain.mv(self.repo.path, fullpath, dest_path)
  2052. # Verify file moved
  2053. self.assertFalse(os.path.exists(fullpath))
  2054. self.assertTrue(os.path.exists(dest_path))
  2055. def test_mv_from_different_directory(self) -> None:
  2056. # Create a subdirectory with a file
  2057. subdir = os.path.join(self.repo.path, "mydir")
  2058. os.makedirs(subdir)
  2059. fullpath = os.path.join(subdir, "myfile")
  2060. with open(fullpath, "w") as f:
  2061. f.write("BAR")
  2062. # Add and commit the file
  2063. porcelain.add(self.repo.path, paths=[fullpath])
  2064. porcelain.commit(
  2065. repo=self.repo,
  2066. message=b"test",
  2067. author=b"test <email>",
  2068. committer=b"test <email>",
  2069. )
  2070. # Change to a different directory and move the file
  2071. cwd = os.getcwd()
  2072. tempdir = tempfile.mkdtemp()
  2073. def cleanup():
  2074. os.chdir(cwd)
  2075. shutil.rmtree(tempdir)
  2076. self.addCleanup(cleanup)
  2077. os.chdir(tempdir)
  2078. # Move the file using relative path from repository root
  2079. porcelain.mv(self.repo.path, "mydir/myfile", "renamed")
  2080. # Verify file was moved
  2081. self.assertFalse(os.path.exists(fullpath))
  2082. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "renamed")))
  2083. class LogTests(PorcelainTestCase):
  2084. def test_simple(self) -> None:
  2085. _c1, _c2, c3 = build_commit_graph(
  2086. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2087. )
  2088. self.repo.refs[b"HEAD"] = c3.id
  2089. self.maxDiff = None
  2090. outstream = StringIO()
  2091. porcelain.log(self.repo.path, outstream=outstream)
  2092. self.assertEqual(
  2093. outstream.getvalue(),
  2094. """\
  2095. --------------------------------------------------
  2096. commit: 4a3b887baa9ecb2d054d2469b628aef84e2d74f0
  2097. merge: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  2098. Author: Test Author <test@nodomain.com>
  2099. Committer: Test Committer <test@nodomain.com>
  2100. Date: Fri Jan 01 2010 00:00:00 +0000
  2101. Commit 3
  2102. --------------------------------------------------
  2103. commit: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  2104. Author: Test Author <test@nodomain.com>
  2105. Committer: Test Committer <test@nodomain.com>
  2106. Date: Fri Jan 01 2010 00:00:00 +0000
  2107. Commit 2
  2108. --------------------------------------------------
  2109. commit: 11d3cf672a19366435c1983c7340b008ec6b8bf3
  2110. Author: Test Author <test@nodomain.com>
  2111. Committer: Test Committer <test@nodomain.com>
  2112. Date: Fri Jan 01 2010 00:00:00 +0000
  2113. Commit 1
  2114. """,
  2115. )
  2116. def test_max_entries(self) -> None:
  2117. _c1, _c2, c3 = build_commit_graph(
  2118. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2119. )
  2120. self.repo.refs[b"HEAD"] = c3.id
  2121. outstream = StringIO()
  2122. porcelain.log(self.repo.path, outstream=outstream, max_entries=1)
  2123. self.assertEqual(1, outstream.getvalue().count("-" * 50))
  2124. def test_no_revisions(self) -> None:
  2125. outstream = StringIO()
  2126. porcelain.log(self.repo.path, outstream=outstream)
  2127. self.assertEqual("", outstream.getvalue())
  2128. def test_empty_message(self) -> None:
  2129. c1 = make_commit(message="")
  2130. self.repo.object_store.add_object(c1)
  2131. self.repo.refs[b"HEAD"] = c1.id
  2132. outstream = StringIO()
  2133. porcelain.log(self.repo.path, outstream=outstream)
  2134. self.assertEqual(
  2135. outstream.getvalue(),
  2136. """\
  2137. --------------------------------------------------
  2138. commit: 4a7ad5552fad70647a81fb9a4a923ccefcca4b76
  2139. Author: Test Author <test@nodomain.com>
  2140. Committer: Test Committer <test@nodomain.com>
  2141. Date: Fri Jan 01 2010 00:00:00 +0000
  2142. """,
  2143. )
  2144. class ShowTests(PorcelainTestCase):
  2145. def test_nolist(self) -> None:
  2146. _c1, _c2, c3 = build_commit_graph(
  2147. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2148. )
  2149. self.repo.refs[b"HEAD"] = c3.id
  2150. outstream = StringIO()
  2151. porcelain.show(self.repo.path, objects=c3.id, outstream=outstream)
  2152. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  2153. def test_simple(self) -> None:
  2154. _c1, _c2, c3 = build_commit_graph(
  2155. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2156. )
  2157. self.repo.refs[b"HEAD"] = c3.id
  2158. outstream = StringIO()
  2159. porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream)
  2160. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  2161. def test_blob(self) -> None:
  2162. b = Blob.from_string(b"The Foo\n")
  2163. self.repo.object_store.add_object(b)
  2164. outstream = StringIO()
  2165. porcelain.show(self.repo.path, objects=[b.id], outstream=outstream)
  2166. self.assertEqual(outstream.getvalue(), "The Foo\n")
  2167. def test_commit_no_parent(self) -> None:
  2168. a = Blob.from_string(b"The Foo\n")
  2169. ta = Tree()
  2170. ta.add(b"somename", 0o100644, a.id)
  2171. ca = make_commit(tree=ta.id)
  2172. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2173. outstream = StringIO()
  2174. porcelain.show(self.repo.path, objects=[ca.id], outstream=outstream)
  2175. self.assertMultiLineEqual(
  2176. outstream.getvalue(),
  2177. """\
  2178. --------------------------------------------------
  2179. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2180. Author: Test Author <test@nodomain.com>
  2181. Committer: Test Committer <test@nodomain.com>
  2182. Date: Fri Jan 01 2010 00:00:00 +0000
  2183. Test message.
  2184. diff --git a/somename b/somename
  2185. new file mode 100644
  2186. index 0000000..ea5c7bf
  2187. --- /dev/null
  2188. +++ b/somename
  2189. @@ -0,0 +1 @@
  2190. +The Foo
  2191. """,
  2192. )
  2193. def test_tag(self) -> None:
  2194. a = Blob.from_string(b"The Foo\n")
  2195. ta = Tree()
  2196. ta.add(b"somename", 0o100644, a.id)
  2197. ca = make_commit(tree=ta.id)
  2198. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2199. porcelain.tag_create(
  2200. self.repo.path,
  2201. b"tryme",
  2202. b"foo <foo@bar.com>",
  2203. b"bar",
  2204. annotated=True,
  2205. objectish=ca.id,
  2206. tag_time=1552854211,
  2207. tag_timezone=0,
  2208. )
  2209. outstream = StringIO()
  2210. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2211. self.maxDiff = None
  2212. self.assertMultiLineEqual(
  2213. outstream.getvalue(),
  2214. """\
  2215. Tagger: foo <foo@bar.com>
  2216. Date: Sun Mar 17 2019 20:23:31 +0000
  2217. bar
  2218. --------------------------------------------------
  2219. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2220. Author: Test Author <test@nodomain.com>
  2221. Committer: Test Committer <test@nodomain.com>
  2222. Date: Fri Jan 01 2010 00:00:00 +0000
  2223. Test message.
  2224. diff --git a/somename b/somename
  2225. new file mode 100644
  2226. index 0000000..ea5c7bf
  2227. --- /dev/null
  2228. +++ b/somename
  2229. @@ -0,0 +1 @@
  2230. +The Foo
  2231. """,
  2232. )
  2233. def test_tag_unicode(self) -> None:
  2234. a = Blob.from_string(b"The Foo\n")
  2235. ta = Tree()
  2236. ta.add(b"somename", 0o100644, a.id)
  2237. ca = make_commit(tree=ta.id)
  2238. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2239. porcelain.tag_create(
  2240. self.repo.path,
  2241. "tryme",
  2242. "foo <foo@bar.com>",
  2243. "bar",
  2244. annotated=True,
  2245. objectish=ca.id,
  2246. tag_time=1552854211,
  2247. tag_timezone=0,
  2248. )
  2249. outstream = StringIO()
  2250. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2251. self.maxDiff = None
  2252. self.assertMultiLineEqual(
  2253. outstream.getvalue(),
  2254. """\
  2255. Tagger: foo <foo@bar.com>
  2256. Date: Sun Mar 17 2019 20:23:31 +0000
  2257. bar
  2258. --------------------------------------------------
  2259. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2260. Author: Test Author <test@nodomain.com>
  2261. Committer: Test Committer <test@nodomain.com>
  2262. Date: Fri Jan 01 2010 00:00:00 +0000
  2263. Test message.
  2264. diff --git a/somename b/somename
  2265. new file mode 100644
  2266. index 0000000..ea5c7bf
  2267. --- /dev/null
  2268. +++ b/somename
  2269. @@ -0,0 +1 @@
  2270. +The Foo
  2271. """,
  2272. )
  2273. def test_commit_with_change(self) -> None:
  2274. a = Blob.from_string(b"The Foo\n")
  2275. ta = Tree()
  2276. ta.add(b"somename", 0o100644, a.id)
  2277. ca = make_commit(tree=ta.id)
  2278. b = Blob.from_string(b"The Bar\n")
  2279. tb = Tree()
  2280. tb.add(b"somename", 0o100644, b.id)
  2281. cb = make_commit(tree=tb.id, parents=[ca.id])
  2282. self.repo.object_store.add_objects(
  2283. [
  2284. (a, None),
  2285. (b, None),
  2286. (ta, None),
  2287. (tb, None),
  2288. (ca, None),
  2289. (cb, None),
  2290. ]
  2291. )
  2292. outstream = StringIO()
  2293. porcelain.show(self.repo.path, objects=[cb.id], outstream=outstream)
  2294. self.assertMultiLineEqual(
  2295. outstream.getvalue(),
  2296. """\
  2297. --------------------------------------------------
  2298. commit: 2c6b6c9cb72c130956657e1fdae58e5b103744fa
  2299. Author: Test Author <test@nodomain.com>
  2300. Committer: Test Committer <test@nodomain.com>
  2301. Date: Fri Jan 01 2010 00:00:00 +0000
  2302. Test message.
  2303. diff --git a/somename b/somename
  2304. index ea5c7bf..fd38bcb 100644
  2305. --- a/somename
  2306. +++ b/somename
  2307. @@ -1 +1 @@
  2308. -The Foo
  2309. +The Bar
  2310. """,
  2311. )
  2312. class FormatPatchTests(PorcelainTestCase):
  2313. def test_format_patch_single_commit(self) -> None:
  2314. # Create initial commit
  2315. tree1 = Tree()
  2316. c1 = make_commit(
  2317. tree=tree1,
  2318. message=b"Initial commit",
  2319. )
  2320. self.repo.object_store.add_objects([(tree1, None), (c1, None)])
  2321. # Create second commit
  2322. b = Blob.from_string(b"modified")
  2323. tree = Tree()
  2324. tree.add(b"test.txt", 0o100644, b.id)
  2325. c2 = make_commit(
  2326. tree=tree,
  2327. parents=[c1.id],
  2328. message=b"Add test.txt",
  2329. )
  2330. self.repo.object_store.add_objects([(b, None), (tree, None), (c2, None)])
  2331. self.repo[b"HEAD"] = c2.id
  2332. # Generate patch for single commit
  2333. with tempfile.TemporaryDirectory() as tmpdir:
  2334. patches = porcelain.format_patch(
  2335. self.repo.path,
  2336. committish=c2.id,
  2337. outdir=tmpdir,
  2338. )
  2339. self.assertEqual(len(patches), 1)
  2340. self.assertTrue(patches[0].endswith("-Add-test.txt.patch"))
  2341. # Verify patch content
  2342. with open(patches[0], "rb") as f:
  2343. content = f.read()
  2344. self.assertIn(b"Subject: [PATCH 1/1] Add test.txt", content)
  2345. self.assertIn(b"+modified", content)
  2346. def test_format_patch_multiple_commits(self) -> None:
  2347. # Create commit chain
  2348. commits = []
  2349. for i in range(3):
  2350. blob = Blob.from_string(f"content {i}".encode())
  2351. tree = Tree()
  2352. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  2353. parents = [commits[-1].id] if commits else []
  2354. commit = make_commit(
  2355. tree=tree,
  2356. parents=parents,
  2357. message=f"Commit {i}".encode(),
  2358. )
  2359. self.repo.object_store.add_objects(
  2360. [(blob, None), (tree, None), (commit, None)]
  2361. )
  2362. commits.append(commit)
  2363. self.repo[b"HEAD"] = commits[-1].id
  2364. # Test generating last 2 commits
  2365. with tempfile.TemporaryDirectory() as tmpdir:
  2366. patches = porcelain.format_patch(
  2367. self.repo.path,
  2368. n=2,
  2369. outdir=tmpdir,
  2370. )
  2371. self.assertEqual(len(patches), 2)
  2372. self.assertTrue(patches[0].endswith("-Commit-1.patch"))
  2373. self.assertTrue(patches[1].endswith("-Commit-2.patch"))
  2374. # Check patch numbering
  2375. with open(patches[0], "rb") as f:
  2376. self.assertIn(b"Subject: [PATCH 1/2] Commit 1", f.read())
  2377. with open(patches[1], "rb") as f:
  2378. self.assertIn(b"Subject: [PATCH 2/2] Commit 2", f.read())
  2379. def test_format_patch_range(self) -> None:
  2380. # Create commit chain
  2381. c1, _c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  2382. self.repo[b"HEAD"] = c3.id
  2383. # Test commit range
  2384. with tempfile.TemporaryDirectory() as tmpdir:
  2385. patches = porcelain.format_patch(
  2386. self.repo.path,
  2387. committish=(c1.id, c3.id),
  2388. outdir=tmpdir,
  2389. )
  2390. # Should include c2 and c3
  2391. self.assertEqual(len(patches), 2)
  2392. def test_format_patch_stdout(self) -> None:
  2393. # Create a commit
  2394. blob = Blob.from_string(b"test content")
  2395. tree = Tree()
  2396. tree.add(b"test.txt", 0o100644, blob.id)
  2397. commit = make_commit(
  2398. tree=tree,
  2399. message=b"Test commit",
  2400. )
  2401. self.repo.object_store.add_objects([(blob, None), (tree, None), (commit, None)])
  2402. self.repo[b"HEAD"] = commit.id
  2403. # Test stdout output
  2404. outstream = BytesIO()
  2405. patches = porcelain.format_patch(
  2406. self.repo.path,
  2407. committish=commit.id,
  2408. stdout=True,
  2409. outstream=outstream,
  2410. )
  2411. # Should return empty list when writing to stdout
  2412. self.assertEqual(patches, [])
  2413. # Check stdout content
  2414. outstream.seek(0)
  2415. content = outstream.read()
  2416. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  2417. self.assertIn(b"diff --git", content)
  2418. def test_format_patch_no_commits(self) -> None:
  2419. # Test with a new repository with no commits
  2420. # Just remove HEAD to simulate empty repo
  2421. patches = porcelain.format_patch(
  2422. self.repo.path,
  2423. n=5,
  2424. )
  2425. self.assertEqual(patches, [])
  2426. class SymbolicRefTests(PorcelainTestCase):
  2427. def test_set_wrong_symbolic_ref(self) -> None:
  2428. _c1, _c2, c3 = build_commit_graph(
  2429. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2430. )
  2431. self.repo.refs[b"HEAD"] = c3.id
  2432. self.assertRaises(
  2433. porcelain.Error, porcelain.symbolic_ref, self.repo.path, b"foobar"
  2434. )
  2435. def test_set_force_wrong_symbolic_ref(self) -> None:
  2436. _c1, _c2, c3 = build_commit_graph(
  2437. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2438. )
  2439. self.repo.refs[b"HEAD"] = c3.id
  2440. porcelain.symbolic_ref(self.repo.path, b"force_foobar", force=True)
  2441. # test if we actually changed the file
  2442. with self.repo.get_named_file("HEAD") as f:
  2443. new_ref = f.read()
  2444. self.assertEqual(new_ref, b"ref: refs/heads/force_foobar\n")
  2445. def test_set_symbolic_ref(self) -> None:
  2446. _c1, _c2, c3 = build_commit_graph(
  2447. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2448. )
  2449. self.repo.refs[b"HEAD"] = c3.id
  2450. porcelain.symbolic_ref(self.repo.path, b"master")
  2451. def test_set_symbolic_ref_other_than_master(self) -> None:
  2452. _c1, _c2, c3 = build_commit_graph(
  2453. self.repo.object_store,
  2454. [[1], [2, 1], [3, 1, 2]],
  2455. attrs=dict(refs="develop"),
  2456. )
  2457. self.repo.refs[b"HEAD"] = c3.id
  2458. self.repo.refs[b"refs/heads/develop"] = c3.id
  2459. porcelain.symbolic_ref(self.repo.path, b"develop")
  2460. # test if we actually changed the file
  2461. with self.repo.get_named_file("HEAD") as f:
  2462. new_ref = f.read()
  2463. self.assertEqual(new_ref, b"ref: refs/heads/develop\n")
  2464. class DiffTreeTests(PorcelainTestCase):
  2465. def test_empty(self) -> None:
  2466. _c1, c2, c3 = build_commit_graph(
  2467. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2468. )
  2469. self.repo.refs[b"HEAD"] = c3.id
  2470. outstream = BytesIO()
  2471. porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream)
  2472. self.assertEqual(outstream.getvalue(), b"")
  2473. class DiffTests(PorcelainTestCase):
  2474. def test_diff_uncommitted_stage(self) -> None:
  2475. # Test diff in repository with no commits yet
  2476. fullpath = os.path.join(self.repo.path, "test.txt")
  2477. with open(fullpath, "w") as f:
  2478. f.write("Hello, world!\n")
  2479. porcelain.add(self.repo.path, paths=["test.txt"])
  2480. outstream = BytesIO()
  2481. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2482. diff_output = outstream.getvalue()
  2483. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2484. self.assertIn(b"new file mode", diff_output)
  2485. self.assertIn(b"+Hello, world!", diff_output)
  2486. def test_diff_uncommitted_working_tree(self) -> None:
  2487. # Test unstaged changes in repository with no commits
  2488. fullpath = os.path.join(self.repo.path, "test.txt")
  2489. with open(fullpath, "w") as f:
  2490. f.write("Hello, world!\n")
  2491. porcelain.add(self.repo.path, paths=["test.txt"])
  2492. # Modify file in working tree
  2493. with open(fullpath, "w") as f:
  2494. f.write("Hello, world!\nNew line\n")
  2495. outstream = BytesIO()
  2496. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2497. diff_output = outstream.getvalue()
  2498. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2499. self.assertIn(b"+New line", diff_output)
  2500. def test_diff_with_commits_staged(self) -> None:
  2501. # Test staged changes with existing commits
  2502. fullpath = os.path.join(self.repo.path, "test.txt")
  2503. with open(fullpath, "w") as f:
  2504. f.write("Initial content\n")
  2505. porcelain.add(self.repo.path, paths=["test.txt"])
  2506. porcelain.commit(self.repo.path, message=b"Initial commit")
  2507. # Modify and stage
  2508. with open(fullpath, "w") as f:
  2509. f.write("Initial content\nModified\n")
  2510. porcelain.add(self.repo.path, paths=["test.txt"])
  2511. outstream = BytesIO()
  2512. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2513. diff_output = outstream.getvalue()
  2514. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2515. self.assertIn(b"+Modified", diff_output)
  2516. def test_diff_with_commits_unstaged(self) -> None:
  2517. # Test unstaged changes with existing commits
  2518. fullpath = os.path.join(self.repo.path, "test.txt")
  2519. with open(fullpath, "w") as f:
  2520. f.write("Initial content\n")
  2521. porcelain.add(self.repo.path, paths=["test.txt"])
  2522. porcelain.commit(self.repo.path, message=b"Initial commit")
  2523. # Modify without staging
  2524. with open(fullpath, "w") as f:
  2525. f.write("Initial content\nModified\n")
  2526. outstream = BytesIO()
  2527. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2528. diff_output = outstream.getvalue()
  2529. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2530. self.assertIn(b"+Modified", diff_output)
  2531. def test_diff_file_deletion(self) -> None:
  2532. # Test showing file deletion
  2533. fullpath = os.path.join(self.repo.path, "test.txt")
  2534. with open(fullpath, "w") as f:
  2535. f.write("Content to delete\n")
  2536. porcelain.add(self.repo.path, paths=["test.txt"])
  2537. porcelain.commit(self.repo.path, message=b"Add file")
  2538. # Delete file
  2539. os.unlink(fullpath)
  2540. outstream = BytesIO()
  2541. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2542. diff_output = outstream.getvalue()
  2543. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2544. self.assertIn(b"deleted file mode", diff_output)
  2545. self.assertIn(b"-Content to delete", diff_output)
  2546. def test_diff_with_paths(self) -> None:
  2547. # Test diff with specific paths
  2548. # Create two files
  2549. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2550. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2551. with open(fullpath1, "w") as f:
  2552. f.write("File 1 content\n")
  2553. with open(fullpath2, "w") as f:
  2554. f.write("File 2 content\n")
  2555. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2556. porcelain.commit(self.repo.path, message=b"Add two files")
  2557. # Modify both files
  2558. with open(fullpath1, "w") as f:
  2559. f.write("File 1 modified\n")
  2560. with open(fullpath2, "w") as f:
  2561. f.write("File 2 modified\n")
  2562. # Test diff with specific path
  2563. outstream = BytesIO()
  2564. porcelain.diff(self.repo.path, paths=["file1.txt"], outstream=outstream)
  2565. diff_output = outstream.getvalue()
  2566. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2567. self.assertIn(b"-File 1 content", diff_output)
  2568. self.assertIn(b"+File 1 modified", diff_output)
  2569. # file2.txt should not appear in diff
  2570. self.assertNotIn(b"file2.txt", diff_output)
  2571. def test_diff_with_paths_multiple(self) -> None:
  2572. # Test diff with multiple paths
  2573. # Create three files
  2574. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2575. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2576. fullpath3 = os.path.join(self.repo.path, "file3.txt")
  2577. with open(fullpath1, "w") as f:
  2578. f.write("File 1 content\n")
  2579. with open(fullpath2, "w") as f:
  2580. f.write("File 2 content\n")
  2581. with open(fullpath3, "w") as f:
  2582. f.write("File 3 content\n")
  2583. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt", "file3.txt"])
  2584. porcelain.commit(self.repo.path, message=b"Add three files")
  2585. # Modify all files
  2586. with open(fullpath1, "w") as f:
  2587. f.write("File 1 modified\n")
  2588. with open(fullpath2, "w") as f:
  2589. f.write("File 2 modified\n")
  2590. with open(fullpath3, "w") as f:
  2591. f.write("File 3 modified\n")
  2592. # Test diff with two specific paths
  2593. outstream = BytesIO()
  2594. porcelain.diff(
  2595. self.repo.path, paths=["file1.txt", "file3.txt"], outstream=outstream
  2596. )
  2597. diff_output = outstream.getvalue()
  2598. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2599. self.assertIn(b"diff --git a/file3.txt b/file3.txt", diff_output)
  2600. # file2.txt should not appear in diff
  2601. self.assertNotIn(b"file2.txt", diff_output)
  2602. def test_diff_with_paths_directory(self) -> None:
  2603. # Test diff with directory paths
  2604. # Create files in subdirectory
  2605. os.mkdir(os.path.join(self.repo.path, "subdir"))
  2606. fullpath1 = os.path.join(self.repo.path, "subdir", "file1.txt")
  2607. fullpath2 = os.path.join(self.repo.path, "subdir", "file2.txt")
  2608. fullpath3 = os.path.join(self.repo.path, "root.txt")
  2609. with open(fullpath1, "w") as f:
  2610. f.write("Subdir file 1\n")
  2611. with open(fullpath2, "w") as f:
  2612. f.write("Subdir file 2\n")
  2613. with open(fullpath3, "w") as f:
  2614. f.write("Root file\n")
  2615. porcelain.add(
  2616. self.repo.path, paths=["subdir/file1.txt", "subdir/file2.txt", "root.txt"]
  2617. )
  2618. porcelain.commit(self.repo.path, message=b"Add files in subdir")
  2619. # Modify all files
  2620. with open(fullpath1, "w") as f:
  2621. f.write("Subdir file 1 modified\n")
  2622. with open(fullpath2, "w") as f:
  2623. f.write("Subdir file 2 modified\n")
  2624. with open(fullpath3, "w") as f:
  2625. f.write("Root file modified\n")
  2626. # Test diff with directory path
  2627. outstream = BytesIO()
  2628. porcelain.diff(self.repo.path, paths=["subdir"], outstream=outstream)
  2629. diff_output = outstream.getvalue()
  2630. self.assertIn(b"subdir/file1.txt", diff_output)
  2631. self.assertIn(b"subdir/file2.txt", diff_output)
  2632. # root.txt should not appear in diff
  2633. self.assertNotIn(b"root.txt", diff_output)
  2634. def test_diff_staged_with_paths(self) -> None:
  2635. # Test staged diff with specific paths
  2636. # Create two files
  2637. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2638. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2639. with open(fullpath1, "w") as f:
  2640. f.write("File 1 content\n")
  2641. with open(fullpath2, "w") as f:
  2642. f.write("File 2 content\n")
  2643. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2644. porcelain.commit(self.repo.path, message=b"Add two files")
  2645. # Modify and stage both files
  2646. with open(fullpath1, "w") as f:
  2647. f.write("File 1 staged\n")
  2648. with open(fullpath2, "w") as f:
  2649. f.write("File 2 staged\n")
  2650. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2651. # Test staged diff with specific path
  2652. outstream = BytesIO()
  2653. porcelain.diff(
  2654. self.repo.path, staged=True, paths=["file1.txt"], outstream=outstream
  2655. )
  2656. diff_output = outstream.getvalue()
  2657. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2658. self.assertIn(b"-File 1 content", diff_output)
  2659. self.assertIn(b"+File 1 staged", diff_output)
  2660. # file2.txt should not appear in diff
  2661. self.assertNotIn(b"file2.txt", diff_output)
  2662. def test_diff_with_commit_and_paths(self) -> None:
  2663. # Test diff against specific commit with paths
  2664. # Create initial file
  2665. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2666. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2667. with open(fullpath1, "w") as f:
  2668. f.write("Initial content 1\n")
  2669. with open(fullpath2, "w") as f:
  2670. f.write("Initial content 2\n")
  2671. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2672. first_commit = porcelain.commit(self.repo.path, message=b"Initial commit")
  2673. # Make second commit
  2674. with open(fullpath1, "w") as f:
  2675. f.write("Second content 1\n")
  2676. with open(fullpath2, "w") as f:
  2677. f.write("Second content 2\n")
  2678. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2679. porcelain.commit(self.repo.path, message=b"Second commit")
  2680. # Modify working tree
  2681. with open(fullpath1, "w") as f:
  2682. f.write("Working content 1\n")
  2683. with open(fullpath2, "w") as f:
  2684. f.write("Working content 2\n")
  2685. # Test diff against first commit with specific path
  2686. outstream = BytesIO()
  2687. porcelain.diff(
  2688. self.repo.path,
  2689. commit=first_commit,
  2690. paths=["file1.txt"],
  2691. outstream=outstream,
  2692. )
  2693. diff_output = outstream.getvalue()
  2694. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2695. self.assertIn(b"-Initial content 1", diff_output)
  2696. self.assertIn(b"+Working content 1", diff_output)
  2697. # file2.txt should not appear in diff
  2698. self.assertNotIn(b"file2.txt", diff_output)
  2699. class CommitTreeTests(PorcelainTestCase):
  2700. def test_simple(self) -> None:
  2701. _c1, _c2, _c3 = build_commit_graph(
  2702. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2703. )
  2704. b = Blob()
  2705. b.data = b"foo the bar"
  2706. t = Tree()
  2707. t.add(b"somename", 0o100644, b.id)
  2708. self.repo.object_store.add_object(t)
  2709. self.repo.object_store.add_object(b)
  2710. sha = porcelain.commit_tree(
  2711. self.repo.path,
  2712. t.id,
  2713. message=b"Withcommit.",
  2714. author=b"Joe <joe@example.com>",
  2715. committer=b"Jane <jane@example.com>",
  2716. )
  2717. self.assertIsInstance(sha, bytes)
  2718. self.assertEqual(len(sha), 40)
  2719. class RevListTests(PorcelainTestCase):
  2720. def test_simple(self) -> None:
  2721. c1, c2, c3 = build_commit_graph(
  2722. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2723. )
  2724. outstream = BytesIO()
  2725. porcelain.rev_list(self.repo.path, [c3.id], outstream=outstream)
  2726. self.assertEqual(
  2727. c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue()
  2728. )
  2729. @skipIf(
  2730. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  2731. "gpgme not easily available or supported on Windows and PyPy",
  2732. )
  2733. class TagCreateSignTests(PorcelainGpgTestCase):
  2734. def test_default_key(self) -> None:
  2735. _c1, _c2, c3 = build_commit_graph(
  2736. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2737. )
  2738. self.repo.refs[b"HEAD"] = c3.id
  2739. cfg = self.repo.get_config()
  2740. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2741. self.import_default_key()
  2742. porcelain.tag_create(
  2743. self.repo.path,
  2744. b"tryme",
  2745. b"foo <foo@bar.com>",
  2746. b"bar",
  2747. annotated=True,
  2748. sign=True,
  2749. )
  2750. tags = self.repo.refs.as_dict(b"refs/tags")
  2751. self.assertEqual(list(tags.keys()), [b"tryme"])
  2752. tag = self.repo[b"refs/tags/tryme"]
  2753. self.assertIsInstance(tag, Tag)
  2754. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2755. self.assertEqual(b"bar\n", tag.message)
  2756. self.assertRecentTimestamp(tag.tag_time)
  2757. tag = self.repo[b"refs/tags/tryme"]
  2758. assert isinstance(tag, Tag)
  2759. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2760. tag.verify()
  2761. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2762. self.import_non_default_key()
  2763. self.assertRaises(
  2764. gpg.errors.MissingSignatures,
  2765. tag.verify,
  2766. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  2767. )
  2768. assert tag.signature is not None
  2769. tag._chunked_text = [b"bad data", tag.signature]
  2770. self.assertRaises(
  2771. gpg.errors.BadSignatures,
  2772. tag.verify,
  2773. )
  2774. def test_non_default_key(self) -> None:
  2775. _c1, _c2, c3 = build_commit_graph(
  2776. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2777. )
  2778. self.repo.refs[b"HEAD"] = c3.id
  2779. cfg = self.repo.get_config()
  2780. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2781. self.import_non_default_key()
  2782. porcelain.tag_create(
  2783. self.repo.path,
  2784. b"tryme",
  2785. b"foo <foo@bar.com>",
  2786. b"bar",
  2787. annotated=True,
  2788. sign=True,
  2789. )
  2790. tags = self.repo.refs.as_dict(b"refs/tags")
  2791. self.assertEqual(list(tags.keys()), [b"tryme"])
  2792. tag = self.repo[b"refs/tags/tryme"]
  2793. self.assertIsInstance(tag, Tag)
  2794. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2795. self.assertEqual(b"bar\n", tag.message)
  2796. self.assertRecentTimestamp(tag.tag_time)
  2797. tag = self.repo[b"refs/tags/tryme"]
  2798. assert isinstance(tag, Tag)
  2799. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2800. tag.verify()
  2801. def test_sign_uses_config_signingkey(self) -> None:
  2802. """Test that sign=True uses user.signingKey from config."""
  2803. _c1, _c2, c3 = build_commit_graph(
  2804. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2805. )
  2806. self.repo.refs[b"HEAD"] = c3.id
  2807. # Set up user.signingKey in config
  2808. cfg = self.repo.get_config()
  2809. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2810. cfg.write_to_path()
  2811. self.import_default_key()
  2812. # Create tag with sign=True (should use signingKey from config)
  2813. porcelain.tag_create(
  2814. self.repo.path,
  2815. b"signed-tag",
  2816. b"foo <foo@bar.com>",
  2817. b"Tag with configured key",
  2818. annotated=True,
  2819. sign=True, # This should read user.signingKey from config
  2820. )
  2821. tags = self.repo.refs.as_dict(b"refs/tags")
  2822. self.assertEqual(list(tags.keys()), [b"signed-tag"])
  2823. tag = self.repo[b"refs/tags/signed-tag"]
  2824. self.assertIsInstance(tag, Tag)
  2825. # Verify the tag is signed with the configured key
  2826. tag.verify()
  2827. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2828. def test_tag_gpg_sign_config_enabled(self) -> None:
  2829. """Test that tag.gpgSign=true automatically signs tags."""
  2830. _c1, _c2, c3 = build_commit_graph(
  2831. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2832. )
  2833. self.repo.refs[b"HEAD"] = c3.id
  2834. # Set up user.signingKey and tag.gpgSign in config
  2835. cfg = self.repo.get_config()
  2836. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2837. cfg.set(("tag",), "gpgSign", True)
  2838. cfg.write_to_path()
  2839. self.import_default_key()
  2840. # Create tag without explicit sign parameter (should auto-sign due to config)
  2841. porcelain.tag_create(
  2842. self.repo.path,
  2843. b"auto-signed-tag",
  2844. b"foo <foo@bar.com>",
  2845. b"Auto-signed tag",
  2846. annotated=True,
  2847. # No sign parameter - should use tag.gpgSign config
  2848. )
  2849. tags = self.repo.refs.as_dict(b"refs/tags")
  2850. self.assertEqual(list(tags.keys()), [b"auto-signed-tag"])
  2851. tag = self.repo[b"refs/tags/auto-signed-tag"]
  2852. self.assertIsInstance(tag, Tag)
  2853. # Verify the tag is signed due to config
  2854. tag.verify()
  2855. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2856. def test_tag_gpg_sign_config_disabled(self) -> None:
  2857. """Test that tag.gpgSign=false does not sign tags."""
  2858. _c1, _c2, c3 = build_commit_graph(
  2859. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2860. )
  2861. self.repo.refs[b"HEAD"] = c3.id
  2862. # Set up user.signingKey and tag.gpgSign=false in config
  2863. cfg = self.repo.get_config()
  2864. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2865. cfg.set(("tag",), "gpgSign", False)
  2866. cfg.write_to_path()
  2867. self.import_default_key()
  2868. # Create tag without explicit sign parameter (should not sign)
  2869. porcelain.tag_create(
  2870. self.repo.path,
  2871. b"unsigned-tag",
  2872. b"foo <foo@bar.com>",
  2873. b"Unsigned tag",
  2874. annotated=True,
  2875. # No sign parameter - should use tag.gpgSign=false config
  2876. )
  2877. tags = self.repo.refs.as_dict(b"refs/tags")
  2878. self.assertEqual(list(tags.keys()), [b"unsigned-tag"])
  2879. tag = self.repo[b"refs/tags/unsigned-tag"]
  2880. self.assertIsInstance(tag, Tag)
  2881. # Verify the tag is not signed
  2882. self.assertIsNone(tag._signature)
  2883. def test_tag_gpg_sign_config_no_signing_key(self) -> None:
  2884. """Test that tag.gpgSign=true works without user.signingKey (uses default)."""
  2885. _c1, _c2, c3 = build_commit_graph(
  2886. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2887. )
  2888. self.repo.refs[b"HEAD"] = c3.id
  2889. # Set up tag.gpgSign but no user.signingKey
  2890. cfg = self.repo.get_config()
  2891. cfg.set(("tag",), "gpgSign", True)
  2892. cfg.write_to_path()
  2893. self.import_default_key()
  2894. # Create tag without explicit sign parameter (should auto-sign with default key)
  2895. porcelain.tag_create(
  2896. self.repo.path,
  2897. b"default-signed-tag",
  2898. b"foo <foo@bar.com>",
  2899. b"Default signed tag",
  2900. annotated=True,
  2901. # No sign parameter - should use tag.gpgSign config with default key
  2902. )
  2903. tags = self.repo.refs.as_dict(b"refs/tags")
  2904. self.assertEqual(list(tags.keys()), [b"default-signed-tag"])
  2905. tag = self.repo[b"refs/tags/default-signed-tag"]
  2906. self.assertIsInstance(tag, Tag)
  2907. # Verify the tag is signed with default key
  2908. tag.verify()
  2909. def test_explicit_sign_overrides_config(self) -> None:
  2910. """Test that explicit sign parameter overrides tag.gpgSign config."""
  2911. _c1, _c2, c3 = build_commit_graph(
  2912. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2913. )
  2914. self.repo.refs[b"HEAD"] = c3.id
  2915. # Set up tag.gpgSign=false but explicitly pass sign=True
  2916. cfg = self.repo.get_config()
  2917. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2918. cfg.set(("tag",), "gpgSign", False)
  2919. cfg.write_to_path()
  2920. self.import_default_key()
  2921. # Create tag with explicit sign=True (should override config)
  2922. porcelain.tag_create(
  2923. self.repo.path,
  2924. b"explicit-signed-tag",
  2925. b"foo <foo@bar.com>",
  2926. b"Explicitly signed tag",
  2927. annotated=True,
  2928. sign=True, # This should override tag.gpgSign=false
  2929. )
  2930. tags = self.repo.refs.as_dict(b"refs/tags")
  2931. self.assertEqual(list(tags.keys()), [b"explicit-signed-tag"])
  2932. tag = self.repo[b"refs/tags/explicit-signed-tag"]
  2933. self.assertIsInstance(tag, Tag)
  2934. # Verify the tag is signed despite config=false
  2935. tag.verify()
  2936. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2937. def test_explicit_false_disables_tag_signing(self) -> None:
  2938. """Test that explicit sign=False disables signing even with config=true."""
  2939. _c1, _c2, c3 = build_commit_graph(
  2940. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2941. )
  2942. self.repo.refs[b"HEAD"] = c3.id
  2943. # Set up tag.gpgSign=true but explicitly pass sign=False
  2944. cfg = self.repo.get_config()
  2945. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2946. cfg.set(("tag",), "gpgSign", True)
  2947. cfg.write_to_path()
  2948. self.import_default_key()
  2949. # Create tag with explicit sign=False (should disable signing)
  2950. porcelain.tag_create(
  2951. self.repo.path,
  2952. b"explicit-unsigned-tag",
  2953. b"foo <foo@bar.com>",
  2954. b"Explicitly unsigned tag",
  2955. annotated=True,
  2956. sign=False, # This should override tag.gpgSign=true
  2957. )
  2958. tags = self.repo.refs.as_dict(b"refs/tags")
  2959. self.assertEqual(list(tags.keys()), [b"explicit-unsigned-tag"])
  2960. tag = self.repo[b"refs/tags/explicit-unsigned-tag"]
  2961. self.assertIsInstance(tag, Tag)
  2962. # Verify the tag is NOT signed despite config=true
  2963. self.assertIsNone(tag._signature)
  2964. class TagCreateTests(PorcelainTestCase):
  2965. def test_annotated(self) -> None:
  2966. _c1, _c2, c3 = build_commit_graph(
  2967. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2968. )
  2969. self.repo.refs[b"HEAD"] = c3.id
  2970. porcelain.tag_create(
  2971. self.repo.path,
  2972. b"tryme",
  2973. b"foo <foo@bar.com>",
  2974. b"bar",
  2975. annotated=True,
  2976. )
  2977. tags = self.repo.refs.as_dict(b"refs/tags")
  2978. self.assertEqual(list(tags.keys()), [b"tryme"])
  2979. tag = self.repo[b"refs/tags/tryme"]
  2980. self.assertIsInstance(tag, Tag)
  2981. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2982. self.assertEqual(b"bar\n", tag.message)
  2983. self.assertRecentTimestamp(tag.tag_time)
  2984. def test_unannotated(self) -> None:
  2985. _c1, _c2, c3 = build_commit_graph(
  2986. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2987. )
  2988. self.repo.refs[b"HEAD"] = c3.id
  2989. porcelain.tag_create(self.repo.path, b"tryme", annotated=False)
  2990. tags = self.repo.refs.as_dict(b"refs/tags")
  2991. self.assertEqual(list(tags.keys()), [b"tryme"])
  2992. self.repo[b"refs/tags/tryme"]
  2993. self.assertEqual(list(tags.values()), [self.repo.head()])
  2994. def test_unannotated_unicode(self) -> None:
  2995. _c1, _c2, c3 = build_commit_graph(
  2996. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2997. )
  2998. self.repo.refs[b"HEAD"] = c3.id
  2999. porcelain.tag_create(self.repo.path, "tryme", annotated=False)
  3000. tags = self.repo.refs.as_dict(b"refs/tags")
  3001. self.assertEqual(list(tags.keys()), [b"tryme"])
  3002. self.repo[b"refs/tags/tryme"]
  3003. self.assertEqual(list(tags.values()), [self.repo.head()])
  3004. class TagListTests(PorcelainTestCase):
  3005. def test_empty(self) -> None:
  3006. tags = porcelain.tag_list(self.repo.path)
  3007. self.assertEqual([], tags)
  3008. def test_simple(self) -> None:
  3009. self.repo.refs[b"refs/tags/foo"] = b"aa" * 20
  3010. self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20
  3011. tags = porcelain.tag_list(self.repo.path)
  3012. self.assertEqual([b"bar/bla", b"foo"], tags)
  3013. class TagDeleteTests(PorcelainTestCase):
  3014. def test_simple(self) -> None:
  3015. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3016. self.repo[b"HEAD"] = c1.id
  3017. porcelain.tag_create(self.repo, b"foo")
  3018. self.assertIn(b"foo", porcelain.tag_list(self.repo))
  3019. porcelain.tag_delete(self.repo, b"foo")
  3020. self.assertNotIn(b"foo", porcelain.tag_list(self.repo))
  3021. class ResetTests(PorcelainTestCase):
  3022. def test_hard_head(self) -> None:
  3023. fullpath = os.path.join(self.repo.path, "foo")
  3024. with open(fullpath, "w") as f:
  3025. f.write("BAR")
  3026. porcelain.add(self.repo.path, paths=[fullpath])
  3027. porcelain.commit(
  3028. self.repo.path,
  3029. message=b"Some message",
  3030. committer=b"Jane <jane@example.com>",
  3031. author=b"John <john@example.com>",
  3032. )
  3033. with open(os.path.join(self.repo.path, "foo"), "wb") as f:
  3034. f.write(b"OOH")
  3035. porcelain.reset(self.repo, "hard", b"HEAD")
  3036. index = self.repo.open_index()
  3037. changes = list(
  3038. tree_changes(
  3039. self.repo.object_store,
  3040. index.commit(self.repo.object_store),
  3041. self.repo[b"HEAD"].tree,
  3042. )
  3043. )
  3044. self.assertEqual([], changes)
  3045. def test_hard_commit(self) -> None:
  3046. fullpath = os.path.join(self.repo.path, "foo")
  3047. with open(fullpath, "w") as f:
  3048. f.write("BAR")
  3049. porcelain.add(self.repo.path, paths=[fullpath])
  3050. sha = porcelain.commit(
  3051. self.repo.path,
  3052. message=b"Some message",
  3053. committer=b"Jane <jane@example.com>",
  3054. author=b"John <john@example.com>",
  3055. )
  3056. with open(fullpath, "wb") as f:
  3057. f.write(b"BAZ")
  3058. porcelain.add(self.repo.path, paths=[fullpath])
  3059. porcelain.commit(
  3060. self.repo.path,
  3061. message=b"Some other message",
  3062. committer=b"Jane <jane@example.com>",
  3063. author=b"John <john@example.com>",
  3064. )
  3065. porcelain.reset(self.repo, "hard", sha)
  3066. index = self.repo.open_index()
  3067. changes = list(
  3068. tree_changes(
  3069. self.repo.object_store,
  3070. index.commit(self.repo.object_store),
  3071. self.repo[sha].tree,
  3072. )
  3073. )
  3074. self.assertEqual([], changes)
  3075. def test_hard_commit_short_hash(self) -> None:
  3076. fullpath = os.path.join(self.repo.path, "foo")
  3077. with open(fullpath, "w") as f:
  3078. f.write("BAR")
  3079. porcelain.add(self.repo.path, paths=[fullpath])
  3080. sha = porcelain.commit(
  3081. self.repo.path,
  3082. message=b"Some message",
  3083. committer=b"Jane <jane@example.com>",
  3084. author=b"John <john@example.com>",
  3085. )
  3086. with open(fullpath, "wb") as f:
  3087. f.write(b"BAZ")
  3088. porcelain.add(self.repo.path, paths=[fullpath])
  3089. porcelain.commit(
  3090. self.repo.path,
  3091. message=b"Some other message",
  3092. committer=b"Jane <jane@example.com>",
  3093. author=b"John <john@example.com>",
  3094. )
  3095. # Test with short hash (7 characters)
  3096. short_sha = sha[:7].decode("ascii")
  3097. porcelain.reset(self.repo, "hard", short_sha)
  3098. index = self.repo.open_index()
  3099. changes = list(
  3100. tree_changes(
  3101. self.repo.object_store,
  3102. index.commit(self.repo.object_store),
  3103. self.repo[sha].tree,
  3104. )
  3105. )
  3106. self.assertEqual([], changes)
  3107. def test_hard_deletes_untracked_files(self) -> None:
  3108. """Test that reset --hard deletes files that don't exist in target tree."""
  3109. # Create and commit a file
  3110. fullpath = os.path.join(self.repo.path, "foo")
  3111. with open(fullpath, "w") as f:
  3112. f.write("BAR")
  3113. porcelain.add(self.repo.path, paths=[fullpath])
  3114. sha1 = porcelain.commit(
  3115. self.repo.path,
  3116. message=b"First commit",
  3117. committer=b"Jane <jane@example.com>",
  3118. author=b"John <john@example.com>",
  3119. )
  3120. # Create another file and commit
  3121. fullpath2 = os.path.join(self.repo.path, "bar")
  3122. with open(fullpath2, "w") as f:
  3123. f.write("BAZ")
  3124. porcelain.add(self.repo.path, paths=[fullpath2])
  3125. porcelain.commit(
  3126. self.repo.path,
  3127. message=b"Second commit",
  3128. committer=b"Jane <jane@example.com>",
  3129. author=b"John <john@example.com>",
  3130. )
  3131. # Reset hard to first commit - this should delete 'bar'
  3132. porcelain.reset(self.repo, "hard", sha1)
  3133. # Check that 'foo' still exists and 'bar' is deleted
  3134. self.assertTrue(os.path.exists(fullpath))
  3135. self.assertFalse(os.path.exists(fullpath2))
  3136. # Check index matches first commit
  3137. index = self.repo.open_index()
  3138. self.assertIn(b"foo", index)
  3139. self.assertNotIn(b"bar", index)
  3140. def test_hard_deletes_files_in_subdirs(self) -> None:
  3141. """Test that reset --hard deletes files in subdirectories."""
  3142. # Create and commit files in subdirectory
  3143. subdir = os.path.join(self.repo.path, "subdir")
  3144. os.makedirs(subdir)
  3145. file1 = os.path.join(subdir, "file1")
  3146. file2 = os.path.join(subdir, "file2")
  3147. with open(file1, "w") as f:
  3148. f.write("content1")
  3149. with open(file2, "w") as f:
  3150. f.write("content2")
  3151. porcelain.add(self.repo.path, paths=[file1, file2])
  3152. porcelain.commit(
  3153. self.repo.path,
  3154. message=b"First commit",
  3155. committer=b"Jane <jane@example.com>",
  3156. author=b"John <john@example.com>",
  3157. )
  3158. # Remove one file from subdirectory and commit
  3159. porcelain.rm(self.repo.path, paths=[file2])
  3160. sha2 = porcelain.commit(
  3161. self.repo.path,
  3162. message=b"Remove file2",
  3163. committer=b"Jane <jane@example.com>",
  3164. author=b"John <john@example.com>",
  3165. )
  3166. # Create file2 again (untracked)
  3167. with open(file2, "w") as f:
  3168. f.write("new content")
  3169. # Reset to commit that has file2 removed - untracked file2 should remain
  3170. porcelain.reset(self.repo, "hard", sha2)
  3171. self.assertTrue(os.path.exists(file1))
  3172. # Untracked files are not removed by reset --hard
  3173. self.assertTrue(os.path.exists(file2))
  3174. def test_hard_reset_to_remote_branch(self) -> None:
  3175. """Test reset --hard to remote branch deletes local files not in remote."""
  3176. # Create a file and commit
  3177. file1 = os.path.join(self.repo.path, "file1")
  3178. with open(file1, "w") as f:
  3179. f.write("content1")
  3180. porcelain.add(self.repo.path, paths=[file1])
  3181. sha1 = porcelain.commit(
  3182. self.repo.path,
  3183. message=b"Initial commit",
  3184. committer=b"Jane <jane@example.com>",
  3185. author=b"John <john@example.com>",
  3186. )
  3187. # Create a "remote" ref that doesn't have additional files
  3188. self.repo.refs[b"refs/remotes/origin/master"] = sha1
  3189. # Add another file locally and commit
  3190. file2 = os.path.join(self.repo.path, "file2")
  3191. with open(file2, "w") as f:
  3192. f.write("content2")
  3193. porcelain.add(self.repo.path, paths=[file2])
  3194. porcelain.commit(
  3195. self.repo.path,
  3196. message=b"Add file2",
  3197. committer=b"Jane <jane@example.com>",
  3198. author=b"John <john@example.com>",
  3199. )
  3200. # Both files should exist
  3201. self.assertTrue(os.path.exists(file1))
  3202. self.assertTrue(os.path.exists(file2))
  3203. # Reset to remote branch - should delete file2
  3204. porcelain.reset(self.repo, "hard", b"refs/remotes/origin/master")
  3205. # file1 should exist, file2 should be deleted
  3206. self.assertTrue(os.path.exists(file1))
  3207. self.assertFalse(os.path.exists(file2))
  3208. def test_mixed_reset(self) -> None:
  3209. # Create initial commit
  3210. fullpath = os.path.join(self.repo.path, "foo")
  3211. with open(fullpath, "w") as f:
  3212. f.write("BAR")
  3213. porcelain.add(self.repo.path, paths=[fullpath])
  3214. first_sha = porcelain.commit(
  3215. self.repo.path,
  3216. message=b"First commit",
  3217. committer=b"Jane <jane@example.com>",
  3218. author=b"John <john@example.com>",
  3219. )
  3220. # Make second commit with modified content
  3221. with open(fullpath, "w") as f:
  3222. f.write("BAZ")
  3223. porcelain.add(self.repo.path, paths=[fullpath])
  3224. porcelain.commit(
  3225. self.repo.path,
  3226. message=b"Second commit",
  3227. committer=b"Jane <jane@example.com>",
  3228. author=b"John <john@example.com>",
  3229. )
  3230. # Modify working tree without staging
  3231. with open(fullpath, "w") as f:
  3232. f.write("MODIFIED")
  3233. # Mixed reset to first commit
  3234. porcelain.reset(self.repo, "mixed", first_sha)
  3235. # Check that HEAD points to first commit
  3236. self.assertEqual(self.repo.head(), first_sha)
  3237. # Check that index matches first commit
  3238. index = self.repo.open_index()
  3239. changes = list(
  3240. tree_changes(
  3241. self.repo.object_store,
  3242. index.commit(self.repo.object_store),
  3243. self.repo[first_sha].tree,
  3244. )
  3245. )
  3246. self.assertEqual([], changes)
  3247. # Check that working tree is unchanged (still has "MODIFIED")
  3248. with open(fullpath) as f:
  3249. self.assertEqual(f.read(), "MODIFIED")
  3250. def test_soft_reset(self) -> None:
  3251. # Create initial commit
  3252. fullpath = os.path.join(self.repo.path, "foo")
  3253. with open(fullpath, "w") as f:
  3254. f.write("BAR")
  3255. porcelain.add(self.repo.path, paths=[fullpath])
  3256. first_sha = porcelain.commit(
  3257. self.repo.path,
  3258. message=b"First commit",
  3259. committer=b"Jane <jane@example.com>",
  3260. author=b"John <john@example.com>",
  3261. )
  3262. # Make second commit with modified content
  3263. with open(fullpath, "w") as f:
  3264. f.write("BAZ")
  3265. porcelain.add(self.repo.path, paths=[fullpath])
  3266. porcelain.commit(
  3267. self.repo.path,
  3268. message=b"Second commit",
  3269. committer=b"Jane <jane@example.com>",
  3270. author=b"John <john@example.com>",
  3271. )
  3272. # Stage a new change
  3273. with open(fullpath, "w") as f:
  3274. f.write("STAGED")
  3275. porcelain.add(self.repo.path, paths=[fullpath])
  3276. # Soft reset to first commit
  3277. porcelain.reset(self.repo, "soft", first_sha)
  3278. # Check that HEAD points to first commit
  3279. self.assertEqual(self.repo.head(), first_sha)
  3280. # Check that index still has the staged change (not reset)
  3281. index = self.repo.open_index()
  3282. # The index should still contain the staged content, not the first commit's content
  3283. self.assertIn(b"foo", index)
  3284. # Check that working tree is unchanged
  3285. with open(fullpath) as f:
  3286. self.assertEqual(f.read(), "STAGED")
  3287. class ResetFileTests(PorcelainTestCase):
  3288. def test_reset_modify_file_to_commit(self) -> None:
  3289. file = "foo"
  3290. full_path = os.path.join(self.repo.path, file)
  3291. with open(full_path, "w") as f:
  3292. f.write("hello")
  3293. porcelain.add(self.repo, paths=[full_path])
  3294. sha = porcelain.commit(
  3295. self.repo,
  3296. message=b"unitest",
  3297. committer=b"Jane <jane@example.com>",
  3298. author=b"John <john@example.com>",
  3299. )
  3300. with open(full_path, "a") as f:
  3301. f.write("something new")
  3302. porcelain.reset_file(self.repo, file, target=sha)
  3303. with open(full_path) as f:
  3304. self.assertEqual("hello", f.read())
  3305. def test_reset_remove_file_to_commit(self) -> None:
  3306. file = "foo"
  3307. full_path = os.path.join(self.repo.path, file)
  3308. with open(full_path, "w") as f:
  3309. f.write("hello")
  3310. porcelain.add(self.repo, paths=[full_path])
  3311. sha = porcelain.commit(
  3312. self.repo,
  3313. message=b"unitest",
  3314. committer=b"Jane <jane@example.com>",
  3315. author=b"John <john@example.com>",
  3316. )
  3317. os.remove(full_path)
  3318. porcelain.reset_file(self.repo, file, target=sha)
  3319. with open(full_path) as f:
  3320. self.assertEqual("hello", f.read())
  3321. def test_resetfile_with_dir(self) -> None:
  3322. os.mkdir(os.path.join(self.repo.path, "new_dir"))
  3323. full_path = os.path.join(self.repo.path, "new_dir", "foo")
  3324. with open(full_path, "w") as f:
  3325. f.write("hello")
  3326. porcelain.add(self.repo, paths=[full_path])
  3327. sha = porcelain.commit(
  3328. self.repo,
  3329. message=b"unitest",
  3330. committer=b"Jane <jane@example.com>",
  3331. author=b"John <john@example.com>",
  3332. )
  3333. with open(full_path, "a") as f:
  3334. f.write("something new")
  3335. porcelain.commit(
  3336. self.repo,
  3337. message=b"unitest 2",
  3338. committer=b"Jane <jane@example.com>",
  3339. author=b"John <john@example.com>",
  3340. )
  3341. porcelain.reset_file(self.repo, os.path.join("new_dir", "foo"), target=sha)
  3342. with open(full_path) as f:
  3343. self.assertEqual("hello", f.read())
  3344. def _commit_file_with_content(repo, filename, content):
  3345. file_path = os.path.join(repo.path, filename)
  3346. with open(file_path, "w") as f:
  3347. f.write(content)
  3348. porcelain.add(repo, paths=[file_path])
  3349. sha = porcelain.commit(
  3350. repo,
  3351. message=b"add " + filename.encode(),
  3352. committer=b"Jane <jane@example.com>",
  3353. author=b"John <john@example.com>",
  3354. )
  3355. return sha, file_path
  3356. class RevertTests(PorcelainTestCase):
  3357. def test_revert_simple(self) -> None:
  3358. # Create initial commit
  3359. fullpath = os.path.join(self.repo.path, "foo")
  3360. with open(fullpath, "w") as f:
  3361. f.write("initial content\n")
  3362. porcelain.add(self.repo.path, paths=[fullpath])
  3363. porcelain.commit(
  3364. self.repo.path,
  3365. message=b"Initial commit",
  3366. committer=b"Jane <jane@example.com>",
  3367. author=b"John <john@example.com>",
  3368. )
  3369. # Make a change
  3370. with open(fullpath, "w") as f:
  3371. f.write("modified content\n")
  3372. porcelain.add(self.repo.path, paths=[fullpath])
  3373. change_sha = porcelain.commit(
  3374. self.repo.path,
  3375. message=b"Change content",
  3376. committer=b"Jane <jane@example.com>",
  3377. author=b"John <john@example.com>",
  3378. )
  3379. # Revert the change
  3380. revert_sha = porcelain.revert(self.repo.path, commits=[change_sha])
  3381. # Check the file content is back to initial
  3382. with open(fullpath) as f:
  3383. self.assertEqual("initial content\n", f.read())
  3384. # Check the revert commit message
  3385. revert_commit = self.repo[revert_sha]
  3386. self.assertIn(b'Revert "Change content"', revert_commit.message)
  3387. self.assertIn(change_sha[:7], revert_commit.message)
  3388. def test_revert_multiple(self) -> None:
  3389. # Create initial commit
  3390. fullpath = os.path.join(self.repo.path, "foo")
  3391. with open(fullpath, "w") as f:
  3392. f.write("line1\n")
  3393. porcelain.add(self.repo.path, paths=[fullpath])
  3394. porcelain.commit(
  3395. self.repo.path,
  3396. message=b"Initial commit",
  3397. committer=b"Jane <jane@example.com>",
  3398. author=b"John <john@example.com>",
  3399. )
  3400. # Add line2
  3401. with open(fullpath, "a") as f:
  3402. f.write("line2\n")
  3403. porcelain.add(self.repo.path, paths=[fullpath])
  3404. commit1 = porcelain.commit(
  3405. self.repo.path,
  3406. message=b"Add line2",
  3407. committer=b"Jane <jane@example.com>",
  3408. author=b"John <john@example.com>",
  3409. )
  3410. # Add line3
  3411. with open(fullpath, "a") as f:
  3412. f.write("line3\n")
  3413. porcelain.add(self.repo.path, paths=[fullpath])
  3414. commit2 = porcelain.commit(
  3415. self.repo.path,
  3416. message=b"Add line3",
  3417. committer=b"Jane <jane@example.com>",
  3418. author=b"John <john@example.com>",
  3419. )
  3420. # Revert both commits (in reverse order)
  3421. porcelain.revert(self.repo.path, commits=[commit2, commit1])
  3422. # Check file is back to initial state
  3423. with open(fullpath) as f:
  3424. self.assertEqual("line1\n", f.read())
  3425. def test_revert_no_commit(self) -> None:
  3426. # Create initial commit
  3427. fullpath = os.path.join(self.repo.path, "foo")
  3428. with open(fullpath, "w") as f:
  3429. f.write("initial\n")
  3430. porcelain.add(self.repo.path, paths=[fullpath])
  3431. porcelain.commit(
  3432. self.repo.path,
  3433. message=b"Initial",
  3434. committer=b"Jane <jane@example.com>",
  3435. author=b"John <john@example.com>",
  3436. )
  3437. # Make a change
  3438. with open(fullpath, "w") as f:
  3439. f.write("changed\n")
  3440. porcelain.add(self.repo.path, paths=[fullpath])
  3441. change_sha = porcelain.commit(
  3442. self.repo.path,
  3443. message=b"Change",
  3444. committer=b"Jane <jane@example.com>",
  3445. author=b"John <john@example.com>",
  3446. )
  3447. # Revert with no_commit
  3448. result = porcelain.revert(self.repo.path, commits=[change_sha], no_commit=True)
  3449. # Should return None
  3450. self.assertIsNone(result)
  3451. # File should be reverted
  3452. with open(fullpath) as f:
  3453. self.assertEqual("initial\n", f.read())
  3454. # HEAD should still point to the change commit
  3455. self.assertEqual(self.repo.refs[b"HEAD"], change_sha)
  3456. def test_revert_custom_message(self) -> None:
  3457. # Create commits
  3458. fullpath = os.path.join(self.repo.path, "foo")
  3459. with open(fullpath, "w") as f:
  3460. f.write("initial\n")
  3461. porcelain.add(self.repo.path, paths=[fullpath])
  3462. porcelain.commit(
  3463. self.repo.path,
  3464. message=b"Initial",
  3465. committer=b"Jane <jane@example.com>",
  3466. author=b"John <john@example.com>",
  3467. )
  3468. with open(fullpath, "w") as f:
  3469. f.write("changed\n")
  3470. porcelain.add(self.repo.path, paths=[fullpath])
  3471. change_sha = porcelain.commit(
  3472. self.repo.path,
  3473. message=b"Change",
  3474. committer=b"Jane <jane@example.com>",
  3475. author=b"John <john@example.com>",
  3476. )
  3477. # Revert with custom message
  3478. custom_msg = "Custom revert message"
  3479. revert_sha = porcelain.revert(
  3480. self.repo.path, commits=[change_sha], message=custom_msg
  3481. )
  3482. # Check the message
  3483. revert_commit = self.repo[revert_sha]
  3484. self.assertEqual(custom_msg.encode("utf-8"), revert_commit.message)
  3485. def test_revert_no_parent(self) -> None:
  3486. # Try to revert the initial commit (no parent)
  3487. fullpath = os.path.join(self.repo.path, "foo")
  3488. with open(fullpath, "w") as f:
  3489. f.write("content\n")
  3490. porcelain.add(self.repo.path, paths=[fullpath])
  3491. initial_sha = porcelain.commit(
  3492. self.repo.path,
  3493. message=b"Initial",
  3494. committer=b"Jane <jane@example.com>",
  3495. author=b"John <john@example.com>",
  3496. )
  3497. # Should raise an error
  3498. with self.assertRaises(porcelain.Error) as cm:
  3499. porcelain.revert(self.repo.path, commits=[initial_sha])
  3500. self.assertIn("no parents", str(cm.exception))
  3501. class CheckoutTests(PorcelainTestCase):
  3502. def setUp(self) -> None:
  3503. super().setUp()
  3504. self._sha, self._foo_path = _commit_file_with_content(
  3505. self.repo, "foo", "hello\n"
  3506. )
  3507. porcelain.branch_create(self.repo, "uni")
  3508. def test_checkout_to_existing_branch(self) -> None:
  3509. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3510. porcelain.checkout(self.repo, b"uni")
  3511. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3512. def test_checkout_to_non_existing_branch(self) -> None:
  3513. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3514. with self.assertRaises(KeyError):
  3515. porcelain.checkout(self.repo, b"bob")
  3516. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3517. def test_checkout_to_branch_with_modified_files(self) -> None:
  3518. with open(self._foo_path, "a") as f:
  3519. f.write("new message\n")
  3520. porcelain.add(self.repo, paths=[self._foo_path])
  3521. status = list(porcelain.status(self.repo))
  3522. self.assertEqual(
  3523. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  3524. )
  3525. # The new checkout behavior prevents switching with staged changes
  3526. with self.assertRaises(porcelain.CheckoutError):
  3527. porcelain.checkout(self.repo, b"uni")
  3528. # Should still be on master
  3529. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3530. # Force checkout should work
  3531. porcelain.checkout(self.repo, b"uni", force=True)
  3532. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3533. def test_checkout_with_deleted_files(self) -> None:
  3534. porcelain.remove(self.repo.path, [os.path.join(self.repo.path, "foo")])
  3535. status = list(porcelain.status(self.repo))
  3536. self.assertEqual(
  3537. [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status
  3538. )
  3539. # The new checkout behavior prevents switching with staged deletions
  3540. with self.assertRaises(porcelain.CheckoutError):
  3541. porcelain.checkout(self.repo, b"uni")
  3542. # Should still be on master
  3543. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3544. # Force checkout should work
  3545. porcelain.checkout(self.repo, b"uni", force=True)
  3546. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3547. def test_checkout_to_branch_with_added_files(self) -> None:
  3548. file_path = os.path.join(self.repo.path, "bar")
  3549. with open(file_path, "w") as f:
  3550. f.write("bar content\n")
  3551. porcelain.add(self.repo, paths=[file_path])
  3552. status = list(porcelain.status(self.repo))
  3553. self.assertEqual(
  3554. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3555. )
  3556. # Both branches have file 'foo' checkout should be fine.
  3557. porcelain.checkout(self.repo, b"uni")
  3558. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3559. status = list(porcelain.status(self.repo))
  3560. self.assertEqual(
  3561. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3562. )
  3563. def test_checkout_to_branch_with_modified_file_not_present(self) -> None:
  3564. # Commit a new file that the other branch doesn't have.
  3565. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3566. # Modify the file the other branch doesn't have.
  3567. with open(nee_path, "a") as f:
  3568. f.write("bar content\n")
  3569. porcelain.add(self.repo, paths=[nee_path])
  3570. status = list(porcelain.status(self.repo))
  3571. self.assertEqual(
  3572. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3573. )
  3574. # Checkout should fail when there are staged changes that would be lost
  3575. # This matches Git's behavior to prevent data loss
  3576. from dulwich.errors import WorkingTreeModifiedError
  3577. with self.assertRaises(WorkingTreeModifiedError) as cm:
  3578. porcelain.checkout(self.repo, b"uni")
  3579. self.assertIn("nee", str(cm.exception))
  3580. # Should still be on master branch
  3581. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3582. # The staged changes should still be present
  3583. status = list(porcelain.status(self.repo))
  3584. self.assertEqual(
  3585. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3586. )
  3587. self.assertTrue(os.path.exists(nee_path))
  3588. # Force checkout should work and lose the changes
  3589. porcelain.checkout(self.repo, b"uni", force=True)
  3590. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3591. # Now the file should be gone
  3592. self.assertFalse(os.path.exists(nee_path))
  3593. def test_checkout_to_branch_with_modified_file_not_present_forced(self) -> None:
  3594. # Commit a new file that the other branch doesn't have.
  3595. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3596. # Modify the file the other branch doesn't have.
  3597. with open(nee_path, "a") as f:
  3598. f.write("bar content\n")
  3599. porcelain.add(self.repo, paths=[nee_path])
  3600. status = list(porcelain.status(self.repo))
  3601. self.assertEqual(
  3602. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3603. )
  3604. # 'uni' branch doesn't have 'nee' and it has been modified, but we force to reset the entire index.
  3605. porcelain.checkout(self.repo, b"uni", force=True)
  3606. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3607. status = list(porcelain.status(self.repo))
  3608. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3609. def test_checkout_to_branch_with_unstaged_files(self) -> None:
  3610. # Edit `foo`.
  3611. with open(self._foo_path, "a") as f:
  3612. f.write("new message")
  3613. status = list(porcelain.status(self.repo))
  3614. self.assertEqual(
  3615. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  3616. )
  3617. # The new checkout behavior prevents switching with unstaged changes
  3618. with self.assertRaises(porcelain.CheckoutError):
  3619. porcelain.checkout(self.repo, b"uni")
  3620. # Should still be on master
  3621. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3622. # Force checkout should work
  3623. porcelain.checkout(self.repo, b"uni", force=True)
  3624. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3625. def test_checkout_to_branch_with_untracked_files(self) -> None:
  3626. with open(os.path.join(self.repo.path, "neu"), "a") as f:
  3627. f.write("new message\n")
  3628. status = list(porcelain.status(self.repo))
  3629. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3630. porcelain.checkout(self.repo, b"uni")
  3631. status = list(porcelain.status(self.repo))
  3632. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3633. def test_checkout_to_branch_with_new_files(self) -> None:
  3634. porcelain.checkout(self.repo, b"uni")
  3635. sub_directory = os.path.join(self.repo.path, "sub1")
  3636. os.mkdir(sub_directory)
  3637. for index in range(5):
  3638. _commit_file_with_content(
  3639. self.repo, "new_file_" + str(index + 1), "Some content\n"
  3640. )
  3641. _commit_file_with_content(
  3642. self.repo,
  3643. os.path.join("sub1", "new_file_" + str(index + 10)),
  3644. "Good content\n",
  3645. )
  3646. status = list(porcelain.status(self.repo))
  3647. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3648. porcelain.checkout(self.repo, b"master")
  3649. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3650. status = list(porcelain.status(self.repo))
  3651. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3652. porcelain.checkout(self.repo, b"uni")
  3653. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3654. status = list(porcelain.status(self.repo))
  3655. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3656. def test_checkout_to_branch_with_file_in_sub_directory(self) -> None:
  3657. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3658. os.makedirs(sub_directory)
  3659. sub_directory_file = os.path.join(sub_directory, "neu")
  3660. with open(sub_directory_file, "w") as f:
  3661. f.write("new message\n")
  3662. porcelain.add(self.repo, paths=[sub_directory_file])
  3663. porcelain.commit(
  3664. self.repo,
  3665. message=b"add " + sub_directory_file.encode(),
  3666. committer=b"Jane <jane@example.com>",
  3667. author=b"John <john@example.com>",
  3668. )
  3669. status = list(porcelain.status(self.repo))
  3670. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3671. self.assertTrue(os.path.isdir(sub_directory))
  3672. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3673. porcelain.checkout(self.repo, b"uni")
  3674. status = list(porcelain.status(self.repo))
  3675. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3676. self.assertFalse(os.path.isdir(sub_directory))
  3677. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3678. porcelain.checkout(self.repo, b"master")
  3679. self.assertTrue(os.path.isdir(sub_directory))
  3680. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3681. def test_checkout_to_branch_with_multiple_files_in_sub_directory(self) -> None:
  3682. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3683. os.makedirs(sub_directory)
  3684. sub_directory_file_1 = os.path.join(sub_directory, "neu")
  3685. with open(sub_directory_file_1, "w") as f:
  3686. f.write("new message\n")
  3687. sub_directory_file_2 = os.path.join(sub_directory, "gus")
  3688. with open(sub_directory_file_2, "w") as f:
  3689. f.write("alternative message\n")
  3690. porcelain.add(self.repo, paths=[sub_directory_file_1, sub_directory_file_2])
  3691. porcelain.commit(
  3692. self.repo,
  3693. message=b"add files neu and gus.",
  3694. committer=b"Jane <jane@example.com>",
  3695. author=b"John <john@example.com>",
  3696. )
  3697. status = list(porcelain.status(self.repo))
  3698. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3699. self.assertTrue(os.path.isdir(sub_directory))
  3700. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3701. porcelain.checkout(self.repo, b"uni")
  3702. status = list(porcelain.status(self.repo))
  3703. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3704. self.assertFalse(os.path.isdir(sub_directory))
  3705. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3706. def _commit_something_wrong(self):
  3707. with open(self._foo_path, "a") as f:
  3708. f.write("something wrong")
  3709. porcelain.add(self.repo, paths=[self._foo_path])
  3710. return porcelain.commit(
  3711. self.repo,
  3712. message=b"I may added something wrong",
  3713. committer=b"Jane <jane@example.com>",
  3714. author=b"John <john@example.com>",
  3715. )
  3716. def test_checkout_to_commit_sha(self) -> None:
  3717. self._commit_something_wrong()
  3718. porcelain.checkout(self.repo, self._sha)
  3719. self.assertEqual(self._sha, self.repo.head())
  3720. def test_checkout_to_head(self) -> None:
  3721. new_sha = self._commit_something_wrong()
  3722. porcelain.checkout(self.repo, b"HEAD")
  3723. self.assertEqual(new_sha, self.repo.head())
  3724. def _checkout_remote_branch(self):
  3725. errstream = BytesIO()
  3726. outstream = BytesIO()
  3727. porcelain.commit(
  3728. repo=self.repo.path,
  3729. message=b"init",
  3730. author=b"author <email>",
  3731. committer=b"committer <email>",
  3732. )
  3733. # Setup target repo cloned from temp test repo
  3734. clone_path = tempfile.mkdtemp()
  3735. self.addCleanup(shutil.rmtree, clone_path)
  3736. target_repo = porcelain.clone(
  3737. self.repo.path, target=clone_path, errstream=errstream
  3738. )
  3739. self.addCleanup(target_repo.close)
  3740. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  3741. # create a second file to be pushed back to origin
  3742. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3743. os.close(handle)
  3744. porcelain.add(repo=clone_path, paths=[fullpath])
  3745. porcelain.commit(
  3746. repo=clone_path,
  3747. message=b"push",
  3748. author=b"author <email>",
  3749. committer=b"committer <email>",
  3750. )
  3751. # Setup a non-checked out branch in the remote
  3752. refs_path = b"refs/heads/foo"
  3753. new_id = self.repo[b"HEAD"].id
  3754. self.assertNotEqual(new_id, ZERO_SHA)
  3755. self.repo.refs[refs_path] = new_id
  3756. # Push to the remote
  3757. porcelain.push(
  3758. clone_path,
  3759. "origin",
  3760. b"HEAD:" + refs_path,
  3761. outstream=outstream,
  3762. errstream=errstream,
  3763. )
  3764. self.assertEqual(
  3765. target_repo.refs[b"refs/remotes/origin/foo"],
  3766. target_repo.refs[b"HEAD"],
  3767. )
  3768. # The new checkout behavior treats origin/foo as a ref and creates detached HEAD
  3769. porcelain.checkout(target_repo, b"origin/foo")
  3770. original_id = target_repo[b"HEAD"].id
  3771. uni_id = target_repo[b"refs/remotes/origin/uni"].id
  3772. # Should be in detached HEAD state
  3773. with self.assertRaises((ValueError, IndexError)):
  3774. porcelain.active_branch(target_repo)
  3775. expected_refs = {
  3776. b"HEAD": original_id,
  3777. b"refs/heads/master": original_id,
  3778. # No local foo branch is created anymore
  3779. b"refs/remotes/origin/foo": original_id,
  3780. b"refs/remotes/origin/uni": uni_id,
  3781. b"refs/remotes/origin/HEAD": new_id,
  3782. b"refs/remotes/origin/master": new_id,
  3783. }
  3784. self.assertEqual(expected_refs, target_repo.get_refs())
  3785. return target_repo
  3786. def test_checkout_remote_branch(self) -> None:
  3787. repo = self._checkout_remote_branch()
  3788. repo.close()
  3789. def test_checkout_remote_branch_then_master_then_remote_branch_again(self) -> None:
  3790. target_repo = self._checkout_remote_branch()
  3791. # Should be in detached HEAD state
  3792. with self.assertRaises((ValueError, IndexError)):
  3793. porcelain.active_branch(target_repo)
  3794. # Save the commit SHA before adding bar
  3795. detached_commit_sha, _ = _commit_file_with_content(
  3796. target_repo, "bar", "something\n"
  3797. )
  3798. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3799. porcelain.checkout(target_repo, b"master")
  3800. self.assertEqual(b"master", porcelain.active_branch(target_repo))
  3801. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3802. # Going back to origin/foo won't have bar because the commit was made in detached state
  3803. porcelain.checkout(target_repo, b"origin/foo")
  3804. # Should be in detached HEAD state again
  3805. with self.assertRaises((ValueError, IndexError)):
  3806. porcelain.active_branch(target_repo)
  3807. # bar is NOT there because we're back at the original origin/foo commit
  3808. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3809. # But we can checkout the specific commit to get bar back
  3810. porcelain.checkout(target_repo, detached_commit_sha.decode())
  3811. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3812. target_repo.close()
  3813. def test_checkout_new_branch_from_remote_sets_tracking(self) -> None:
  3814. # Create a "remote" repository
  3815. remote_path = tempfile.mkdtemp()
  3816. self.addCleanup(shutil.rmtree, remote_path)
  3817. remote_repo = porcelain.init(remote_path)
  3818. # Add a commit to the remote
  3819. remote_sha, _ = _commit_file_with_content(
  3820. remote_repo, "bar", "remote content\n"
  3821. )
  3822. # Clone the remote repository
  3823. target_path = tempfile.mkdtemp()
  3824. self.addCleanup(shutil.rmtree, target_path)
  3825. target_repo = porcelain.clone(remote_path, target_path)
  3826. self.addCleanup(target_repo.close)
  3827. # Create a remote tracking branch reference
  3828. remote_branch_ref = b"refs/remotes/origin/feature"
  3829. target_repo.refs[remote_branch_ref] = remote_sha
  3830. # Checkout a new branch from the remote branch
  3831. porcelain.checkout(target_repo, remote_branch_ref, new_branch=b"local-feature")
  3832. # Verify the branch was created and is active
  3833. self.assertEqual(b"local-feature", porcelain.active_branch(target_repo))
  3834. # Verify tracking configuration was set
  3835. config = target_repo.get_config()
  3836. self.assertEqual(
  3837. b"origin", config.get((b"branch", b"local-feature"), b"remote")
  3838. )
  3839. self.assertEqual(
  3840. b"refs/heads/feature", config.get((b"branch", b"local-feature"), b"merge")
  3841. )
  3842. target_repo.close()
  3843. remote_repo.close()
  3844. class GeneralCheckoutTests(PorcelainTestCase):
  3845. """Tests for the general checkout function that handles branches, tags, and commits."""
  3846. def setUp(self) -> None:
  3847. super().setUp()
  3848. # Create initial commit
  3849. self._sha1, self._foo_path = _commit_file_with_content(
  3850. self.repo, "foo", "initial content\n"
  3851. )
  3852. # Create a branch
  3853. porcelain.branch_create(self.repo, "feature")
  3854. # Create another commit on master
  3855. self._sha2, self._bar_path = _commit_file_with_content(
  3856. self.repo, "bar", "bar content\n"
  3857. )
  3858. # Create a tag
  3859. porcelain.tag_create(self.repo, "v1.0", objectish=self._sha1)
  3860. def test_checkout_branch(self) -> None:
  3861. """Test checking out a branch."""
  3862. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3863. # Checkout feature branch
  3864. porcelain.checkout(self.repo, "feature")
  3865. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3866. # File 'bar' should not exist in feature branch
  3867. self.assertFalse(os.path.exists(self._bar_path))
  3868. # Go back to master
  3869. porcelain.checkout(self.repo, "master")
  3870. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3871. # File 'bar' should exist again
  3872. self.assertTrue(os.path.exists(self._bar_path))
  3873. def test_checkout_commit(self) -> None:
  3874. """Test checking out a specific commit (detached HEAD)."""
  3875. # Checkout first commit by SHA
  3876. porcelain.checkout(self.repo, self._sha1.decode("ascii"))
  3877. # Should be in detached HEAD state - active_branch raises IndexError
  3878. with self.assertRaises((ValueError, IndexError)):
  3879. porcelain.active_branch(self.repo)
  3880. # File 'bar' should not exist
  3881. self.assertFalse(os.path.exists(self._bar_path))
  3882. # HEAD should point to the commit
  3883. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3884. def test_checkout_tag(self) -> None:
  3885. """Test checking out a tag (detached HEAD)."""
  3886. # Checkout tag
  3887. porcelain.checkout(self.repo, "v1.0")
  3888. # Should be in detached HEAD state - active_branch raises IndexError
  3889. with self.assertRaises((ValueError, IndexError)):
  3890. porcelain.active_branch(self.repo)
  3891. # File 'bar' should not exist (tag points to first commit)
  3892. self.assertFalse(os.path.exists(self._bar_path))
  3893. # HEAD should point to the tagged commit
  3894. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3895. def test_checkout_new_branch(self) -> None:
  3896. """Test creating a new branch during checkout (like git checkout -b)."""
  3897. # Create and checkout new branch from current HEAD
  3898. porcelain.checkout(self.repo, "master", new_branch="new-feature")
  3899. self.assertEqual(b"new-feature", porcelain.active_branch(self.repo))
  3900. self.assertTrue(os.path.exists(self._bar_path))
  3901. # Create and checkout new branch from specific commit
  3902. porcelain.checkout(self.repo, self._sha1.decode("ascii"), new_branch="from-old")
  3903. self.assertEqual(b"from-old", porcelain.active_branch(self.repo))
  3904. self.assertFalse(os.path.exists(self._bar_path))
  3905. def test_checkout_with_uncommitted_changes(self) -> None:
  3906. """Test checkout behavior with uncommitted changes."""
  3907. # Modify a file
  3908. with open(self._foo_path, "w") as f:
  3909. f.write("modified content\n")
  3910. # Should raise error when trying to checkout
  3911. with self.assertRaises(porcelain.CheckoutError) as cm:
  3912. porcelain.checkout(self.repo, "feature")
  3913. self.assertIn("local changes", str(cm.exception))
  3914. self.assertIn("foo", str(cm.exception))
  3915. # Should still be on master
  3916. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3917. def test_checkout_force(self) -> None:
  3918. """Test forced checkout discards local changes for files that differ between branches."""
  3919. # Modify a file
  3920. with open(self._foo_path, "w") as f:
  3921. f.write("modified content\n")
  3922. # Force checkout should succeed
  3923. porcelain.checkout(self.repo, "feature", force=True)
  3924. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3925. # Since foo has the same content in master and feature branches,
  3926. # checkout should NOT restore it - the modified content should remain
  3927. with open(self._foo_path) as f:
  3928. content = f.read()
  3929. self.assertEqual("modified content\n", content)
  3930. def test_checkout_nonexistent_ref(self) -> None:
  3931. """Test checkout of non-existent branch/commit."""
  3932. with self.assertRaises(KeyError):
  3933. porcelain.checkout(self.repo, "nonexistent")
  3934. def test_checkout_partial_sha(self) -> None:
  3935. """Test checkout with partial SHA."""
  3936. # Git typically allows checkout with partial SHA
  3937. partial_sha = self._sha1.decode("ascii")[:7]
  3938. porcelain.checkout(self.repo, partial_sha)
  3939. # Should be in detached HEAD state at the right commit
  3940. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3941. def test_checkout_preserves_untracked_files(self) -> None:
  3942. """Test that checkout preserves untracked files."""
  3943. # Create an untracked file
  3944. untracked_path = os.path.join(self.repo.path, "untracked.txt")
  3945. with open(untracked_path, "w") as f:
  3946. f.write("untracked content\n")
  3947. # Checkout another branch
  3948. porcelain.checkout(self.repo, "feature")
  3949. # Untracked file should still exist
  3950. self.assertTrue(os.path.exists(untracked_path))
  3951. with open(untracked_path) as f:
  3952. content = f.read()
  3953. self.assertEqual("untracked content\n", content)
  3954. def test_checkout_full_ref_paths(self) -> None:
  3955. """Test checkout with full ref paths."""
  3956. # Test checkout with full branch ref path
  3957. porcelain.checkout(self.repo, "refs/heads/feature")
  3958. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3959. # Test checkout with full tag ref path
  3960. porcelain.checkout(self.repo, "refs/tags/v1.0")
  3961. # Should be in detached HEAD state
  3962. with self.assertRaises((ValueError, IndexError)):
  3963. porcelain.active_branch(self.repo)
  3964. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3965. def test_checkout_bytes_vs_string_target(self) -> None:
  3966. """Test that checkout works with both bytes and string targets."""
  3967. # Test with string target
  3968. porcelain.checkout(self.repo, "feature")
  3969. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3970. # Test with bytes target
  3971. porcelain.checkout(self.repo, b"master")
  3972. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3973. def test_checkout_new_branch_from_commit(self) -> None:
  3974. """Test creating a new branch from a specific commit."""
  3975. # Create new branch from first commit
  3976. porcelain.checkout(self.repo, self._sha1.decode(), new_branch="from-commit")
  3977. self.assertEqual(b"from-commit", porcelain.active_branch(self.repo))
  3978. # Should be at the first commit (no bar file)
  3979. self.assertFalse(os.path.exists(self._bar_path))
  3980. def test_checkout_with_staged_addition(self) -> None:
  3981. """Test checkout behavior with staged file additions."""
  3982. # Create and stage a new file that doesn't exist in target branch
  3983. new_file_path = os.path.join(self.repo.path, "new.txt")
  3984. with open(new_file_path, "w") as f:
  3985. f.write("new file content\n")
  3986. porcelain.add(self.repo, [new_file_path])
  3987. # This should succeed because the file doesn't exist in target branch
  3988. porcelain.checkout(self.repo, "feature")
  3989. # Should be on feature branch
  3990. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3991. # The new file should still exist and be staged
  3992. self.assertTrue(os.path.exists(new_file_path))
  3993. status = porcelain.status(self.repo)
  3994. self.assertIn(b"new.txt", status.staged["add"])
  3995. def test_checkout_with_staged_modification_conflict(self) -> None:
  3996. """Test checkout behavior with staged modifications that would conflict."""
  3997. # Stage changes to a file that exists in both branches
  3998. with open(self._foo_path, "w") as f:
  3999. f.write("modified content\n")
  4000. porcelain.add(self.repo, [self._foo_path])
  4001. # Should prevent checkout due to staged changes to existing file
  4002. with self.assertRaises(porcelain.CheckoutError) as cm:
  4003. porcelain.checkout(self.repo, "feature")
  4004. self.assertIn("local changes", str(cm.exception))
  4005. self.assertIn("foo", str(cm.exception))
  4006. def test_checkout_head_reference(self) -> None:
  4007. """Test checkout of HEAD reference."""
  4008. # Move to feature branch first
  4009. porcelain.checkout(self.repo, "feature")
  4010. # Checkout HEAD creates detached HEAD state
  4011. porcelain.checkout(self.repo, "HEAD")
  4012. # Should be in detached HEAD state
  4013. with self.assertRaises((ValueError, IndexError)):
  4014. porcelain.active_branch(self.repo)
  4015. def test_checkout_error_messages(self) -> None:
  4016. """Test that checkout error messages are helpful."""
  4017. # Create uncommitted changes
  4018. with open(self._foo_path, "w") as f:
  4019. f.write("uncommitted changes\n")
  4020. # Try to checkout
  4021. with self.assertRaises(porcelain.CheckoutError) as cm:
  4022. porcelain.checkout(self.repo, "feature")
  4023. error_msg = str(cm.exception)
  4024. self.assertIn("local changes", error_msg)
  4025. self.assertIn("foo", error_msg)
  4026. self.assertIn("overwritten", error_msg)
  4027. self.assertIn("commit or stash", error_msg)
  4028. class SubmoduleTests(PorcelainTestCase):
  4029. def test_empty(self) -> None:
  4030. porcelain.commit(
  4031. repo=self.repo.path,
  4032. message=b"init",
  4033. author=b"author <email>",
  4034. committer=b"committer <email>",
  4035. )
  4036. self.assertEqual([], list(porcelain.submodule_list(self.repo)))
  4037. def test_add(self) -> None:
  4038. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  4039. with open(f"{self.repo.path}/.gitmodules") as f:
  4040. self.assertEqual(
  4041. """\
  4042. [submodule "bar"]
  4043. \turl = ../bar.git
  4044. \tpath = bar
  4045. """,
  4046. f.read(),
  4047. )
  4048. def test_init(self) -> None:
  4049. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  4050. porcelain.submodule_init(self.repo)
  4051. def test_update(self) -> None:
  4052. # Create a submodule repository
  4053. sub_repo_path = tempfile.mkdtemp()
  4054. self.addCleanup(shutil.rmtree, sub_repo_path)
  4055. sub_repo = Repo.init(sub_repo_path)
  4056. self.addCleanup(sub_repo.close)
  4057. # Add a file to the submodule repo
  4058. sub_file = os.path.join(sub_repo_path, "test.txt")
  4059. with open(sub_file, "w") as f:
  4060. f.write("submodule content")
  4061. porcelain.add(sub_repo, paths=[sub_file])
  4062. sub_commit = porcelain.commit(
  4063. sub_repo,
  4064. message=b"Initial submodule commit",
  4065. author=b"Test Author <test@example.com>",
  4066. committer=b"Test Committer <test@example.com>",
  4067. )
  4068. # Add the submodule to the main repository
  4069. porcelain.submodule_add(self.repo, sub_repo_path, "test_submodule")
  4070. # Manually add the submodule to the index
  4071. from dulwich.index import IndexEntry
  4072. from dulwich.objects import S_IFGITLINK
  4073. index = self.repo.open_index()
  4074. index[b"test_submodule"] = IndexEntry(
  4075. ctime=0,
  4076. mtime=0,
  4077. dev=0,
  4078. ino=0,
  4079. mode=S_IFGITLINK,
  4080. uid=0,
  4081. gid=0,
  4082. size=0,
  4083. sha=sub_commit,
  4084. flags=0,
  4085. )
  4086. index.write()
  4087. porcelain.add(self.repo, paths=[".gitmodules"])
  4088. porcelain.commit(
  4089. self.repo,
  4090. message=b"Add submodule",
  4091. author=b"Test Author <test@example.com>",
  4092. committer=b"Test Committer <test@example.com>",
  4093. )
  4094. # Initialize and update the submodule
  4095. porcelain.submodule_init(self.repo)
  4096. porcelain.submodule_update(self.repo)
  4097. # Check that the submodule directory exists
  4098. submodule_path = os.path.join(self.repo.path, "test_submodule")
  4099. self.assertTrue(os.path.exists(submodule_path))
  4100. # Check that the submodule file exists
  4101. submodule_file = os.path.join(submodule_path, "test.txt")
  4102. self.assertTrue(os.path.exists(submodule_file))
  4103. with open(submodule_file) as f:
  4104. self.assertEqual(f.read(), "submodule content")
  4105. def test_update_recursive(self) -> None:
  4106. # Create a nested (innermost) submodule repository
  4107. nested_repo_path = tempfile.mkdtemp()
  4108. self.addCleanup(shutil.rmtree, nested_repo_path)
  4109. nested_repo = Repo.init(nested_repo_path)
  4110. self.addCleanup(nested_repo.close)
  4111. # Add a file to the nested repo
  4112. nested_file = os.path.join(nested_repo_path, "nested.txt")
  4113. with open(nested_file, "w") as f:
  4114. f.write("nested submodule content")
  4115. porcelain.add(nested_repo, paths=[nested_file])
  4116. nested_commit = porcelain.commit(
  4117. nested_repo,
  4118. message=b"Initial nested commit",
  4119. author=b"Test Author <test@example.com>",
  4120. committer=b"Test Committer <test@example.com>",
  4121. )
  4122. # Create a middle submodule repository
  4123. middle_repo_path = tempfile.mkdtemp()
  4124. self.addCleanup(shutil.rmtree, middle_repo_path)
  4125. middle_repo = Repo.init(middle_repo_path)
  4126. self.addCleanup(middle_repo.close)
  4127. # Add a file to the middle repo
  4128. middle_file = os.path.join(middle_repo_path, "middle.txt")
  4129. with open(middle_file, "w") as f:
  4130. f.write("middle submodule content")
  4131. porcelain.add(middle_repo, paths=[middle_file])
  4132. # Add the nested submodule to the middle repository
  4133. porcelain.submodule_add(middle_repo, nested_repo_path, "nested")
  4134. # Manually add the nested submodule to the index
  4135. from dulwich.index import IndexEntry
  4136. from dulwich.objects import S_IFGITLINK
  4137. middle_index = middle_repo.open_index()
  4138. middle_index[b"nested"] = IndexEntry(
  4139. ctime=0,
  4140. mtime=0,
  4141. dev=0,
  4142. ino=0,
  4143. mode=S_IFGITLINK,
  4144. uid=0,
  4145. gid=0,
  4146. size=0,
  4147. sha=nested_commit,
  4148. flags=0,
  4149. )
  4150. middle_index.write()
  4151. porcelain.add(middle_repo, paths=[".gitmodules"])
  4152. middle_commit = porcelain.commit(
  4153. middle_repo,
  4154. message=b"Add nested submodule",
  4155. author=b"Test Author <test@example.com>",
  4156. committer=b"Test Committer <test@example.com>",
  4157. )
  4158. # Add the middle submodule to the main repository
  4159. porcelain.submodule_add(self.repo, middle_repo_path, "middle")
  4160. # Manually add the middle submodule to the index
  4161. main_index = self.repo.open_index()
  4162. main_index[b"middle"] = IndexEntry(
  4163. ctime=0,
  4164. mtime=0,
  4165. dev=0,
  4166. ino=0,
  4167. mode=S_IFGITLINK,
  4168. uid=0,
  4169. gid=0,
  4170. size=0,
  4171. sha=middle_commit,
  4172. flags=0,
  4173. )
  4174. main_index.write()
  4175. porcelain.add(self.repo, paths=[".gitmodules"])
  4176. porcelain.commit(
  4177. self.repo,
  4178. message=b"Add middle submodule",
  4179. author=b"Test Author <test@example.com>",
  4180. committer=b"Test Committer <test@example.com>",
  4181. )
  4182. # Initialize and recursively update the submodules
  4183. porcelain.submodule_init(self.repo)
  4184. porcelain.submodule_update(self.repo, recursive=True)
  4185. # Check that the middle submodule directory and file exist
  4186. middle_submodule_path = os.path.join(self.repo.path, "middle")
  4187. self.assertTrue(os.path.exists(middle_submodule_path))
  4188. middle_submodule_file = os.path.join(middle_submodule_path, "middle.txt")
  4189. self.assertTrue(os.path.exists(middle_submodule_file))
  4190. with open(middle_submodule_file) as f:
  4191. self.assertEqual(f.read(), "middle submodule content")
  4192. # Check that the nested submodule directory and file exist
  4193. nested_submodule_path = os.path.join(self.repo.path, "middle", "nested")
  4194. self.assertTrue(os.path.exists(nested_submodule_path))
  4195. nested_submodule_file = os.path.join(nested_submodule_path, "nested.txt")
  4196. self.assertTrue(os.path.exists(nested_submodule_file))
  4197. with open(nested_submodule_file) as f:
  4198. self.assertEqual(f.read(), "nested submodule content")
  4199. class PushTests(PorcelainTestCase):
  4200. def test_simple(self) -> None:
  4201. """Basic test of porcelain push where self.repo is the remote. First
  4202. clone the remote, commit a file to the clone, then push the changes
  4203. back to the remote.
  4204. """
  4205. outstream = BytesIO()
  4206. errstream = BytesIO()
  4207. porcelain.commit(
  4208. repo=self.repo.path,
  4209. message=b"init",
  4210. author=b"author <email>",
  4211. committer=b"committer <email>",
  4212. )
  4213. # Setup target repo cloned from temp test repo
  4214. clone_path = tempfile.mkdtemp()
  4215. self.addCleanup(shutil.rmtree, clone_path)
  4216. target_repo = porcelain.clone(
  4217. self.repo.path, target=clone_path, errstream=errstream
  4218. )
  4219. self.addCleanup(target_repo.close)
  4220. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  4221. # create a second file to be pushed back to origin
  4222. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4223. os.close(handle)
  4224. porcelain.add(repo=clone_path, paths=[fullpath])
  4225. porcelain.commit(
  4226. repo=clone_path,
  4227. message=b"push",
  4228. author=b"author <email>",
  4229. committer=b"committer <email>",
  4230. )
  4231. # Setup a non-checked out branch in the remote
  4232. refs_path = b"refs/heads/foo"
  4233. new_id = self.repo[b"HEAD"].id
  4234. self.assertNotEqual(new_id, ZERO_SHA)
  4235. self.repo.refs[refs_path] = new_id
  4236. # Push to the remote
  4237. porcelain.push(
  4238. clone_path,
  4239. "origin",
  4240. b"HEAD:" + refs_path,
  4241. outstream=outstream,
  4242. errstream=errstream,
  4243. )
  4244. self.assertEqual(
  4245. target_repo.refs[b"refs/remotes/origin/foo"],
  4246. target_repo.refs[b"HEAD"],
  4247. )
  4248. # Check that the target and source
  4249. with Repo(clone_path) as r_clone:
  4250. self.assertEqual(
  4251. {
  4252. b"HEAD": new_id,
  4253. b"refs/heads/foo": r_clone[b"HEAD"].id,
  4254. b"refs/heads/master": new_id,
  4255. },
  4256. self.repo.get_refs(),
  4257. )
  4258. self.assertEqual(r_clone[b"HEAD"].id, self.repo[refs_path].id)
  4259. # Get the change in the target repo corresponding to the add
  4260. # this will be in the foo branch.
  4261. change = next(
  4262. iter(
  4263. tree_changes(
  4264. self.repo.object_store,
  4265. self.repo[b"HEAD"].tree,
  4266. self.repo[b"refs/heads/foo"].tree,
  4267. )
  4268. )
  4269. )
  4270. self.assertEqual(
  4271. os.path.basename(fullpath), change.new.path.decode("ascii")
  4272. )
  4273. def test_local_missing(self) -> None:
  4274. """Pushing a new branch."""
  4275. outstream = BytesIO()
  4276. errstream = BytesIO()
  4277. # Setup target repo cloned from temp test repo
  4278. clone_path = tempfile.mkdtemp()
  4279. self.addCleanup(shutil.rmtree, clone_path)
  4280. target_repo = porcelain.init(clone_path)
  4281. target_repo.close()
  4282. self.assertRaises(
  4283. porcelain.Error,
  4284. porcelain.push,
  4285. self.repo,
  4286. clone_path,
  4287. b"HEAD:refs/heads/master",
  4288. outstream=outstream,
  4289. errstream=errstream,
  4290. )
  4291. def test_new(self) -> None:
  4292. """Pushing a new branch."""
  4293. outstream = BytesIO()
  4294. errstream = BytesIO()
  4295. # Setup target repo cloned from temp test repo
  4296. clone_path = tempfile.mkdtemp()
  4297. self.addCleanup(shutil.rmtree, clone_path)
  4298. target_repo = porcelain.init(clone_path)
  4299. target_repo.close()
  4300. # create a second file to be pushed back to origin
  4301. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4302. os.close(handle)
  4303. porcelain.add(repo=clone_path, paths=[fullpath])
  4304. new_id = porcelain.commit(
  4305. repo=self.repo,
  4306. message=b"push",
  4307. author=b"author <email>",
  4308. committer=b"committer <email>",
  4309. )
  4310. # Push to the remote
  4311. porcelain.push(
  4312. self.repo,
  4313. clone_path,
  4314. b"HEAD:refs/heads/master",
  4315. outstream=outstream,
  4316. errstream=errstream,
  4317. )
  4318. with Repo(clone_path) as r_clone:
  4319. self.assertEqual(
  4320. {
  4321. b"HEAD": new_id,
  4322. b"refs/heads/master": new_id,
  4323. },
  4324. r_clone.get_refs(),
  4325. )
  4326. def test_delete(self) -> None:
  4327. """Basic test of porcelain push, removing a branch."""
  4328. outstream = BytesIO()
  4329. errstream = BytesIO()
  4330. porcelain.commit(
  4331. repo=self.repo.path,
  4332. message=b"init",
  4333. author=b"author <email>",
  4334. committer=b"committer <email>",
  4335. )
  4336. # Setup target repo cloned from temp test repo
  4337. clone_path = tempfile.mkdtemp()
  4338. self.addCleanup(shutil.rmtree, clone_path)
  4339. target_repo = porcelain.clone(
  4340. self.repo.path, target=clone_path, errstream=errstream
  4341. )
  4342. target_repo.close()
  4343. # Setup a non-checked out branch in the remote
  4344. refs_path = b"refs/heads/foo"
  4345. new_id = self.repo[b"HEAD"].id
  4346. self.assertNotEqual(new_id, ZERO_SHA)
  4347. self.repo.refs[refs_path] = new_id
  4348. # Push to the remote
  4349. porcelain.push(
  4350. clone_path,
  4351. self.repo.path,
  4352. b":" + refs_path,
  4353. outstream=outstream,
  4354. errstream=errstream,
  4355. )
  4356. self.assertEqual(
  4357. {
  4358. b"HEAD": new_id,
  4359. b"refs/heads/master": new_id,
  4360. },
  4361. self.repo.get_refs(),
  4362. )
  4363. def test_diverged(self) -> None:
  4364. outstream = BytesIO()
  4365. errstream = BytesIO()
  4366. porcelain.commit(
  4367. repo=self.repo.path,
  4368. message=b"init",
  4369. author=b"author <email>",
  4370. committer=b"committer <email>",
  4371. )
  4372. # Setup target repo cloned from temp test repo
  4373. clone_path = tempfile.mkdtemp()
  4374. self.addCleanup(shutil.rmtree, clone_path)
  4375. target_repo = porcelain.clone(
  4376. self.repo.path, target=clone_path, errstream=errstream
  4377. )
  4378. target_repo.close()
  4379. remote_id = porcelain.commit(
  4380. repo=self.repo.path,
  4381. message=b"remote change",
  4382. author=b"author <email>",
  4383. committer=b"committer <email>",
  4384. )
  4385. local_id = porcelain.commit(
  4386. repo=clone_path,
  4387. message=b"local change",
  4388. author=b"author <email>",
  4389. committer=b"committer <email>",
  4390. )
  4391. outstream = BytesIO()
  4392. errstream = BytesIO()
  4393. # Push to the remote
  4394. self.assertRaises(
  4395. porcelain.DivergedBranches,
  4396. porcelain.push,
  4397. clone_path,
  4398. self.repo.path,
  4399. b"refs/heads/master",
  4400. outstream=outstream,
  4401. errstream=errstream,
  4402. )
  4403. self.assertEqual(
  4404. {
  4405. b"HEAD": remote_id,
  4406. b"refs/heads/master": remote_id,
  4407. },
  4408. self.repo.get_refs(),
  4409. )
  4410. self.assertEqual(b"", outstream.getvalue())
  4411. self.assertEqual(b"", errstream.getvalue())
  4412. outstream = BytesIO()
  4413. errstream = BytesIO()
  4414. # Push to the remote with --force
  4415. porcelain.push(
  4416. clone_path,
  4417. self.repo.path,
  4418. b"refs/heads/master",
  4419. outstream=outstream,
  4420. errstream=errstream,
  4421. force=True,
  4422. )
  4423. self.assertEqual(
  4424. {
  4425. b"HEAD": local_id,
  4426. b"refs/heads/master": local_id,
  4427. },
  4428. self.repo.get_refs(),
  4429. )
  4430. self.assertEqual(b"", outstream.getvalue())
  4431. self.assertTrue(re.search(b"Push to .* successful.\n", errstream.getvalue()))
  4432. def test_push_returns_sendpackresult(self) -> None:
  4433. """Test that push returns a SendPackResult with per-ref information."""
  4434. outstream = BytesIO()
  4435. errstream = BytesIO()
  4436. # Create initial commit
  4437. porcelain.commit(
  4438. repo=self.repo.path,
  4439. message=b"init",
  4440. author=b"author <email>",
  4441. committer=b"committer <email>",
  4442. )
  4443. # Setup target repo cloned from temp test repo
  4444. clone_path = tempfile.mkdtemp()
  4445. self.addCleanup(shutil.rmtree, clone_path)
  4446. target_repo = porcelain.clone(
  4447. self.repo.path, target=clone_path, errstream=errstream
  4448. )
  4449. target_repo.close()
  4450. # Create a commit in the clone
  4451. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4452. os.close(handle)
  4453. porcelain.add(repo=clone_path, paths=[fullpath])
  4454. porcelain.commit(
  4455. repo=clone_path,
  4456. message=b"push",
  4457. author=b"author <email>",
  4458. committer=b"committer <email>",
  4459. )
  4460. # Push and check the return value
  4461. result = porcelain.push(
  4462. clone_path,
  4463. "origin",
  4464. b"HEAD:refs/heads/new-branch",
  4465. outstream=outstream,
  4466. errstream=errstream,
  4467. )
  4468. # Verify that we get a SendPackResult
  4469. self.assertIsInstance(result, SendPackResult)
  4470. # Verify that it contains refs
  4471. self.assertIsNotNone(result.refs)
  4472. self.assertIn(b"refs/heads/new-branch", result.refs)
  4473. # Verify ref_status - should be None for successful updates
  4474. if result.ref_status:
  4475. self.assertIsNone(result.ref_status.get(b"refs/heads/new-branch"))
  4476. def test_mirror_mode(self) -> None:
  4477. """Test push with remote.<name>.mirror configuration."""
  4478. outstream = BytesIO()
  4479. errstream = BytesIO()
  4480. # Create initial commit
  4481. porcelain.commit(
  4482. repo=self.repo.path,
  4483. message=b"init",
  4484. author=b"author <email>",
  4485. committer=b"committer <email>",
  4486. )
  4487. # Setup target repo cloned from temp test repo
  4488. clone_path = tempfile.mkdtemp()
  4489. self.addCleanup(shutil.rmtree, clone_path)
  4490. target_repo = porcelain.clone(
  4491. self.repo.path, target=clone_path, errstream=errstream
  4492. )
  4493. target_repo.close()
  4494. # Create multiple refs in the clone
  4495. with Repo(clone_path) as r_clone:
  4496. # Create a new branch
  4497. r_clone.refs[b"refs/heads/feature"] = r_clone[b"HEAD"].id
  4498. # Create a tag
  4499. r_clone.refs[b"refs/tags/v1.0"] = r_clone[b"HEAD"].id
  4500. # Create a remote tracking branch
  4501. r_clone.refs[b"refs/remotes/upstream/main"] = r_clone[b"HEAD"].id
  4502. # Create a branch in the remote that doesn't exist in clone
  4503. self.repo.refs[b"refs/heads/to-be-deleted"] = self.repo[b"HEAD"].id
  4504. # Configure mirror mode
  4505. with Repo(clone_path) as r_clone:
  4506. config = r_clone.get_config()
  4507. config.set((b"remote", b"origin"), b"mirror", True)
  4508. config.write_to_path()
  4509. # Push with mirror mode
  4510. porcelain.push(
  4511. clone_path,
  4512. "origin",
  4513. outstream=outstream,
  4514. errstream=errstream,
  4515. )
  4516. # Verify refs were properly mirrored
  4517. with Repo(clone_path) as r_clone:
  4518. # All local branches should be pushed
  4519. self.assertEqual(
  4520. r_clone.refs[b"refs/heads/feature"],
  4521. self.repo.refs[b"refs/heads/feature"],
  4522. )
  4523. # All tags should be pushed
  4524. self.assertEqual(
  4525. r_clone.refs[b"refs/tags/v1.0"], self.repo.refs[b"refs/tags/v1.0"]
  4526. )
  4527. # Remote tracking branches should be pushed
  4528. self.assertEqual(
  4529. r_clone.refs[b"refs/remotes/upstream/main"],
  4530. self.repo.refs[b"refs/remotes/upstream/main"],
  4531. )
  4532. # Verify the extra branch was deleted
  4533. self.assertNotIn(b"refs/heads/to-be-deleted", self.repo.refs)
  4534. def test_mirror_mode_disabled(self) -> None:
  4535. """Test that mirror mode is properly disabled when set to false."""
  4536. outstream = BytesIO()
  4537. errstream = BytesIO()
  4538. # Create initial commit
  4539. porcelain.commit(
  4540. repo=self.repo.path,
  4541. message=b"init",
  4542. author=b"author <email>",
  4543. committer=b"committer <email>",
  4544. )
  4545. # Setup target repo cloned from temp test repo
  4546. clone_path = tempfile.mkdtemp()
  4547. self.addCleanup(shutil.rmtree, clone_path)
  4548. target_repo = porcelain.clone(
  4549. self.repo.path, target=clone_path, errstream=errstream
  4550. )
  4551. target_repo.close()
  4552. # Create a branch in the remote that doesn't exist in clone
  4553. self.repo.refs[b"refs/heads/should-not-be-deleted"] = self.repo[b"HEAD"].id
  4554. # Explicitly set mirror mode to false
  4555. with Repo(clone_path) as r_clone:
  4556. config = r_clone.get_config()
  4557. config.set((b"remote", b"origin"), b"mirror", False)
  4558. config.write_to_path()
  4559. # Push normally (not mirror mode)
  4560. porcelain.push(
  4561. clone_path,
  4562. "origin",
  4563. outstream=outstream,
  4564. errstream=errstream,
  4565. )
  4566. # Verify the extra branch was NOT deleted
  4567. self.assertIn(b"refs/heads/should-not-be-deleted", self.repo.refs)
  4568. class PullTests(PorcelainTestCase):
  4569. def setUp(self) -> None:
  4570. super().setUp()
  4571. # create a file for initial commit
  4572. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4573. os.close(handle)
  4574. porcelain.add(repo=self.repo.path, paths=fullpath)
  4575. porcelain.commit(
  4576. repo=self.repo.path,
  4577. message=b"test",
  4578. author=b"test <email>",
  4579. committer=b"test <email>",
  4580. )
  4581. # Setup target repo
  4582. self.target_path = tempfile.mkdtemp()
  4583. self.addCleanup(shutil.rmtree, self.target_path)
  4584. target_repo = porcelain.clone(
  4585. self.repo.path, target=self.target_path, errstream=BytesIO()
  4586. )
  4587. target_repo.close()
  4588. # create a second file to be pushed
  4589. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4590. os.close(handle)
  4591. porcelain.add(repo=self.repo.path, paths=fullpath)
  4592. porcelain.commit(
  4593. repo=self.repo.path,
  4594. message=b"test2",
  4595. author=b"test2 <email>",
  4596. committer=b"test2 <email>",
  4597. )
  4598. self.assertIn(b"refs/heads/master", self.repo.refs)
  4599. self.assertIn(b"refs/heads/master", target_repo.refs)
  4600. def test_simple(self) -> None:
  4601. outstream = BytesIO()
  4602. errstream = BytesIO()
  4603. # Pull changes into the cloned repo
  4604. porcelain.pull(
  4605. self.target_path,
  4606. self.repo.path,
  4607. b"refs/heads/master",
  4608. outstream=outstream,
  4609. errstream=errstream,
  4610. )
  4611. # Check the target repo for pushed changes
  4612. with Repo(self.target_path) as r:
  4613. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4614. def test_diverged(self) -> None:
  4615. outstream = BytesIO()
  4616. errstream = BytesIO()
  4617. c3a = porcelain.commit(
  4618. repo=self.target_path,
  4619. message=b"test3a",
  4620. author=b"test2 <email>",
  4621. committer=b"test2 <email>",
  4622. )
  4623. porcelain.commit(
  4624. repo=self.repo.path,
  4625. message=b"test3b",
  4626. author=b"test2 <email>",
  4627. committer=b"test2 <email>",
  4628. )
  4629. # Pull changes into the cloned repo
  4630. self.assertRaises(
  4631. porcelain.DivergedBranches,
  4632. porcelain.pull,
  4633. self.target_path,
  4634. self.repo.path,
  4635. b"refs/heads/master",
  4636. outstream=outstream,
  4637. errstream=errstream,
  4638. )
  4639. # Check the target repo for pushed changes
  4640. with Repo(self.target_path) as r:
  4641. self.assertEqual(r[b"refs/heads/master"].id, c3a)
  4642. # Pull with merge should now work
  4643. porcelain.pull(
  4644. self.target_path,
  4645. self.repo.path,
  4646. b"refs/heads/master",
  4647. outstream=outstream,
  4648. errstream=errstream,
  4649. fast_forward=False,
  4650. )
  4651. # Check the target repo for merged changes
  4652. with Repo(self.target_path) as r:
  4653. # HEAD should now be a merge commit
  4654. head = r[b"HEAD"]
  4655. # It should have two parents
  4656. self.assertEqual(len(head.parents), 2)
  4657. # One parent should be the previous HEAD (c3a)
  4658. self.assertIn(c3a, head.parents)
  4659. # The other parent should be from the source repo
  4660. self.assertIn(self.repo[b"HEAD"].id, head.parents)
  4661. def test_no_refspec(self) -> None:
  4662. outstream = BytesIO()
  4663. errstream = BytesIO()
  4664. # Pull changes into the cloned repo
  4665. porcelain.pull(
  4666. self.target_path,
  4667. self.repo.path,
  4668. outstream=outstream,
  4669. errstream=errstream,
  4670. )
  4671. # Check the target repo for pushed changes
  4672. with Repo(self.target_path) as r:
  4673. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4674. def test_no_remote_location(self) -> None:
  4675. outstream = BytesIO()
  4676. errstream = BytesIO()
  4677. # Pull changes into the cloned repo
  4678. porcelain.pull(
  4679. self.target_path,
  4680. refspecs=b"refs/heads/master",
  4681. outstream=outstream,
  4682. errstream=errstream,
  4683. )
  4684. # Check the target repo for pushed changes
  4685. with Repo(self.target_path) as r:
  4686. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4687. def test_pull_updates_working_tree(self) -> None:
  4688. """Test that pull updates the working tree with new files."""
  4689. outstream = BytesIO()
  4690. errstream = BytesIO()
  4691. # Create a new file with content in the source repo
  4692. new_file = os.path.join(self.repo.path, "newfile.txt")
  4693. with open(new_file, "w") as f:
  4694. f.write("This is new content")
  4695. porcelain.add(repo=self.repo.path, paths=[new_file])
  4696. porcelain.commit(
  4697. repo=self.repo.path,
  4698. message=b"Add new file",
  4699. author=b"test <email>",
  4700. committer=b"test <email>",
  4701. )
  4702. # Before pull, the file should not exist in target
  4703. target_file = os.path.join(self.target_path, "newfile.txt")
  4704. self.assertFalse(os.path.exists(target_file))
  4705. # Pull changes into the cloned repo
  4706. porcelain.pull(
  4707. self.target_path,
  4708. self.repo.path,
  4709. b"refs/heads/master",
  4710. outstream=outstream,
  4711. errstream=errstream,
  4712. )
  4713. # After pull, the file should exist with correct content
  4714. self.assertTrue(os.path.exists(target_file))
  4715. with open(target_file) as f:
  4716. self.assertEqual(f.read(), "This is new content")
  4717. # Check the HEAD is updated too
  4718. with Repo(self.target_path) as r:
  4719. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4720. def test_pull_protects_modified_files(self) -> None:
  4721. """Test that pull refuses to overwrite uncommitted changes by default."""
  4722. from dulwich.errors import WorkingTreeModifiedError
  4723. outstream = BytesIO()
  4724. errstream = BytesIO()
  4725. # Create a file with content in the source repo
  4726. test_file = os.path.join(self.repo.path, "testfile.txt")
  4727. with open(test_file, "w") as f:
  4728. f.write("original content")
  4729. porcelain.add(repo=self.repo.path, paths=[test_file])
  4730. porcelain.commit(
  4731. repo=self.repo.path,
  4732. message=b"Add test file",
  4733. author=b"test <email>",
  4734. committer=b"test <email>",
  4735. )
  4736. # Pull this change to target first
  4737. porcelain.pull(
  4738. self.target_path,
  4739. self.repo.path,
  4740. b"refs/heads/master",
  4741. outstream=outstream,
  4742. errstream=errstream,
  4743. )
  4744. # Now modify the file in source repo
  4745. with open(test_file, "w") as f:
  4746. f.write("updated content")
  4747. porcelain.add(repo=self.repo.path, paths=[test_file])
  4748. porcelain.commit(
  4749. repo=self.repo.path,
  4750. message=b"Update test file",
  4751. author=b"test <email>",
  4752. committer=b"test <email>",
  4753. )
  4754. # Modify the same file in target working directory (uncommitted)
  4755. target_file = os.path.join(self.target_path, "testfile.txt")
  4756. with open(target_file, "w") as f:
  4757. f.write("local modifications")
  4758. # Pull should fail because of uncommitted changes
  4759. with self.assertRaises(WorkingTreeModifiedError) as cm:
  4760. porcelain.pull(
  4761. self.target_path,
  4762. self.repo.path,
  4763. b"refs/heads/master",
  4764. outstream=outstream,
  4765. errstream=errstream,
  4766. )
  4767. self.assertIn("Your local changes", str(cm.exception))
  4768. self.assertIn("testfile.txt", str(cm.exception))
  4769. # Verify the file still has local modifications
  4770. with open(target_file) as f:
  4771. self.assertEqual(f.read(), "local modifications")
  4772. def test_pull_force_overwrites_modified_files(self) -> None:
  4773. """Test that pull with force=True overwrites uncommitted changes."""
  4774. outstream = BytesIO()
  4775. errstream = BytesIO()
  4776. # Create a file with content in the source repo
  4777. test_file = os.path.join(self.repo.path, "testfile.txt")
  4778. with open(test_file, "w") as f:
  4779. f.write("original content")
  4780. porcelain.add(repo=self.repo.path, paths=[test_file])
  4781. porcelain.commit(
  4782. repo=self.repo.path,
  4783. message=b"Add test file",
  4784. author=b"test <email>",
  4785. committer=b"test <email>",
  4786. )
  4787. # Pull this change to target first
  4788. porcelain.pull(
  4789. self.target_path,
  4790. self.repo.path,
  4791. b"refs/heads/master",
  4792. outstream=outstream,
  4793. errstream=errstream,
  4794. )
  4795. # Now modify the file in source repo
  4796. with open(test_file, "w") as f:
  4797. f.write("updated content")
  4798. porcelain.add(repo=self.repo.path, paths=[test_file])
  4799. porcelain.commit(
  4800. repo=self.repo.path,
  4801. message=b"Update test file",
  4802. author=b"test <email>",
  4803. committer=b"test <email>",
  4804. )
  4805. # Modify the same file in target working directory (uncommitted)
  4806. target_file = os.path.join(self.target_path, "testfile.txt")
  4807. with open(target_file, "w") as f:
  4808. f.write("local modifications")
  4809. # Pull with force=True should succeed and overwrite local changes
  4810. porcelain.pull(
  4811. self.target_path,
  4812. self.repo.path,
  4813. b"refs/heads/master",
  4814. outstream=outstream,
  4815. errstream=errstream,
  4816. force=True,
  4817. )
  4818. # Verify the file now has the remote content
  4819. with open(target_file) as f:
  4820. self.assertEqual(f.read(), "updated content")
  4821. # Check the HEAD is updated too
  4822. with Repo(self.target_path) as r:
  4823. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4824. def test_pull_allows_unmodified_files(self) -> None:
  4825. """Test that pull allows updating files that haven't been modified locally."""
  4826. outstream = BytesIO()
  4827. errstream = BytesIO()
  4828. # Create a file with content in the source repo
  4829. test_file = os.path.join(self.repo.path, "testfile.txt")
  4830. with open(test_file, "w") as f:
  4831. f.write("original content")
  4832. porcelain.add(repo=self.repo.path, paths=[test_file])
  4833. porcelain.commit(
  4834. repo=self.repo.path,
  4835. message=b"Add test file",
  4836. author=b"test <email>",
  4837. committer=b"test <email>",
  4838. )
  4839. # Pull this change to target first
  4840. porcelain.pull(
  4841. self.target_path,
  4842. self.repo.path,
  4843. b"refs/heads/master",
  4844. outstream=outstream,
  4845. errstream=errstream,
  4846. )
  4847. # Now modify the file in source repo
  4848. with open(test_file, "w") as f:
  4849. f.write("updated content")
  4850. porcelain.add(repo=self.repo.path, paths=[test_file])
  4851. porcelain.commit(
  4852. repo=self.repo.path,
  4853. message=b"Update test file",
  4854. author=b"test <email>",
  4855. committer=b"test <email>",
  4856. )
  4857. # Don't modify the file in target - it should be safe to update
  4858. target_file = os.path.join(self.target_path, "testfile.txt")
  4859. # Pull should succeed since the file wasn't modified locally
  4860. porcelain.pull(
  4861. self.target_path,
  4862. self.repo.path,
  4863. b"refs/heads/master",
  4864. outstream=outstream,
  4865. errstream=errstream,
  4866. )
  4867. # Verify the file now has the remote content
  4868. with open(target_file) as f:
  4869. self.assertEqual(f.read(), "updated content")
  4870. # Check the HEAD is updated too
  4871. with Repo(self.target_path) as r:
  4872. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4873. class StatusTests(PorcelainTestCase):
  4874. def test_empty(self) -> None:
  4875. results = porcelain.status(self.repo)
  4876. self.assertEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4877. self.assertEqual([], results.unstaged)
  4878. def test_status_base(self) -> None:
  4879. """Integration test for `status` functionality."""
  4880. # Commit a dummy file then modify it
  4881. fullpath = os.path.join(self.repo.path, "foo")
  4882. with open(fullpath, "w") as f:
  4883. f.write("origstuff")
  4884. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4885. porcelain.commit(
  4886. repo=self.repo.path,
  4887. message=b"test status",
  4888. author=b"author <email>",
  4889. committer=b"committer <email>",
  4890. )
  4891. # modify access and modify time of path
  4892. os.utime(fullpath, (0, 0))
  4893. with open(fullpath, "wb") as f:
  4894. f.write(b"stuff")
  4895. # Make a dummy file and stage it
  4896. filename_add = "bar"
  4897. fullpath = os.path.join(self.repo.path, filename_add)
  4898. with open(fullpath, "w") as f:
  4899. f.write("stuff")
  4900. porcelain.add(repo=self.repo.path, paths=fullpath)
  4901. results = porcelain.status(self.repo)
  4902. self.assertEqual(results.staged["add"][0], filename_add.encode("ascii"))
  4903. self.assertEqual(results.unstaged, [b"foo"])
  4904. def test_status_with_core_preloadindex(self) -> None:
  4905. """Test status with core.preloadIndex enabled."""
  4906. # Set core.preloadIndex to true
  4907. config = self.repo.get_config()
  4908. config.set(b"core", b"preloadIndex", b"true")
  4909. config.write_to_path()
  4910. # Create multiple files
  4911. files = []
  4912. for i in range(10):
  4913. filename = f"file{i}"
  4914. fullpath = os.path.join(self.repo.path, filename)
  4915. with open(fullpath, "w") as f:
  4916. f.write(f"content{i}")
  4917. files.append(fullpath)
  4918. porcelain.add(repo=self.repo.path, paths=files)
  4919. porcelain.commit(
  4920. repo=self.repo.path,
  4921. message=b"test preload status",
  4922. author=b"author <email>",
  4923. committer=b"committer <email>",
  4924. )
  4925. # Modify some files
  4926. modified_files = ["file1", "file3", "file5", "file7"]
  4927. for filename in modified_files:
  4928. fullpath = os.path.join(self.repo.path, filename)
  4929. with open(fullpath, "w") as f:
  4930. f.write("modified content")
  4931. os.utime(fullpath, (0, 0))
  4932. # Status should work correctly with preloadIndex enabled
  4933. results = porcelain.status(self.repo)
  4934. # Check that we detected the correct unstaged changes
  4935. unstaged_sorted = sorted(results.unstaged)
  4936. expected_sorted = sorted([f.encode("ascii") for f in modified_files])
  4937. self.assertEqual(unstaged_sorted, expected_sorted)
  4938. def test_status_all(self) -> None:
  4939. del_path = os.path.join(self.repo.path, "foo")
  4940. mod_path = os.path.join(self.repo.path, "bar")
  4941. add_path = os.path.join(self.repo.path, "baz")
  4942. us_path = os.path.join(self.repo.path, "blye")
  4943. ut_path = os.path.join(self.repo.path, "blyat")
  4944. with open(del_path, "w") as f:
  4945. f.write("origstuff")
  4946. with open(mod_path, "w") as f:
  4947. f.write("origstuff")
  4948. with open(us_path, "w") as f:
  4949. f.write("origstuff")
  4950. porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path])
  4951. porcelain.commit(
  4952. repo=self.repo.path,
  4953. message=b"test status",
  4954. author=b"author <email>",
  4955. committer=b"committer <email>",
  4956. )
  4957. porcelain.remove(self.repo.path, [del_path])
  4958. with open(add_path, "w") as f:
  4959. f.write("origstuff")
  4960. with open(mod_path, "w") as f:
  4961. f.write("more_origstuff")
  4962. with open(us_path, "w") as f:
  4963. f.write("more_origstuff")
  4964. porcelain.add(repo=self.repo.path, paths=[add_path, mod_path])
  4965. with open(us_path, "w") as f:
  4966. f.write("\norigstuff")
  4967. with open(ut_path, "w") as f:
  4968. f.write("origstuff")
  4969. results = porcelain.status(self.repo.path)
  4970. self.assertDictEqual(
  4971. {"add": [b"baz"], "delete": [b"foo"], "modify": [b"bar"]},
  4972. results.staged,
  4973. )
  4974. self.assertListEqual(results.unstaged, [b"blye"])
  4975. results_no_untracked = porcelain.status(self.repo.path, untracked_files="no")
  4976. self.assertListEqual(results_no_untracked.untracked, [])
  4977. def test_status_wrong_untracked_files_value(self) -> None:
  4978. with self.assertRaises(ValueError):
  4979. porcelain.status(self.repo.path, untracked_files="antani")
  4980. def test_status_untracked_path(self) -> None:
  4981. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  4982. os.mkdir(untracked_dir)
  4983. untracked_file = os.path.join(untracked_dir, "untracked_file")
  4984. with open(untracked_file, "w") as fh:
  4985. fh.write("untracked")
  4986. _, _, untracked = porcelain.status(self.repo.path, untracked_files="all")
  4987. self.assertEqual(untracked, ["untracked_dir/untracked_file"])
  4988. def test_status_untracked_path_normal(self) -> None:
  4989. # Create an untracked directory with multiple files
  4990. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  4991. os.mkdir(untracked_dir)
  4992. untracked_file1 = os.path.join(untracked_dir, "file1")
  4993. untracked_file2 = os.path.join(untracked_dir, "file2")
  4994. with open(untracked_file1, "w") as fh:
  4995. fh.write("untracked1")
  4996. with open(untracked_file2, "w") as fh:
  4997. fh.write("untracked2")
  4998. # Create a nested untracked directory
  4999. nested_dir = os.path.join(untracked_dir, "nested")
  5000. os.mkdir(nested_dir)
  5001. nested_file = os.path.join(nested_dir, "file3")
  5002. with open(nested_file, "w") as fh:
  5003. fh.write("untracked3")
  5004. # Test "normal" mode - should only show the directory, not individual files
  5005. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  5006. self.assertEqual(untracked, ["untracked_dir/"])
  5007. # Test "all" mode - should show all files
  5008. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  5009. self.assertEqual(
  5010. sorted(untracked_all),
  5011. [
  5012. "untracked_dir/file1",
  5013. "untracked_dir/file2",
  5014. "untracked_dir/nested/file3",
  5015. ],
  5016. )
  5017. def test_status_mixed_tracked_untracked(self) -> None:
  5018. # Create a directory with both tracked and untracked files
  5019. mixed_dir = os.path.join(self.repo_path, "mixed_dir")
  5020. os.mkdir(mixed_dir)
  5021. # Add a tracked file
  5022. tracked_file = os.path.join(mixed_dir, "tracked.txt")
  5023. with open(tracked_file, "w") as fh:
  5024. fh.write("tracked content")
  5025. porcelain.add(self.repo.path, paths=[tracked_file])
  5026. porcelain.commit(
  5027. repo=self.repo.path,
  5028. message=b"add tracked file",
  5029. author=b"author <email>",
  5030. committer=b"committer <email>",
  5031. )
  5032. # Add untracked files to the same directory
  5033. untracked_file = os.path.join(mixed_dir, "untracked.txt")
  5034. with open(untracked_file, "w") as fh:
  5035. fh.write("untracked content")
  5036. # In "normal" mode, should show individual untracked files in mixed dirs
  5037. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  5038. self.assertEqual(untracked, ["mixed_dir/untracked.txt"])
  5039. # In "all" mode, should be the same for mixed directories
  5040. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  5041. self.assertEqual(untracked_all, ["mixed_dir/untracked.txt"])
  5042. def test_status_crlf_mismatch(self) -> None:
  5043. # First make a commit as if the file has been added on a Linux system
  5044. # or with core.autocrlf=True
  5045. file_path = os.path.join(self.repo.path, "crlf")
  5046. with open(file_path, "wb") as f:
  5047. f.write(b"line1\nline2")
  5048. porcelain.add(repo=self.repo.path, paths=[file_path])
  5049. porcelain.commit(
  5050. repo=self.repo.path,
  5051. message=b"test status",
  5052. author=b"author <email>",
  5053. committer=b"committer <email>",
  5054. )
  5055. # Then update the file as if it was created by CGit on a Windows
  5056. # system with core.autocrlf=true
  5057. with open(file_path, "wb") as f:
  5058. f.write(b"line1\r\nline2")
  5059. results = porcelain.status(self.repo)
  5060. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  5061. self.assertListEqual(results.unstaged, [b"crlf"])
  5062. self.assertListEqual(results.untracked, [])
  5063. def test_status_autocrlf_true(self) -> None:
  5064. # First make a commit as if the file has been added on a Linux system
  5065. # or with core.autocrlf=True
  5066. file_path = os.path.join(self.repo.path, "crlf")
  5067. with open(file_path, "wb") as f:
  5068. f.write(b"line1\nline2")
  5069. porcelain.add(repo=self.repo.path, paths=[file_path])
  5070. porcelain.commit(
  5071. repo=self.repo.path,
  5072. message=b"test status",
  5073. author=b"author <email>",
  5074. committer=b"committer <email>",
  5075. )
  5076. # Then update the file as if it was created by CGit on a Windows
  5077. # system with core.autocrlf=true
  5078. with open(file_path, "wb") as f:
  5079. f.write(b"line1\r\nline2")
  5080. # TODO: It should be set automatically by looking at the configuration
  5081. c = self.repo.get_config()
  5082. c.set("core", "autocrlf", True)
  5083. c.write_to_path()
  5084. results = porcelain.status(self.repo)
  5085. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  5086. self.assertListEqual(results.unstaged, [])
  5087. self.assertListEqual(results.untracked, [])
  5088. def test_status_autocrlf_input(self) -> None:
  5089. # Commit existing file with CRLF
  5090. file_path = os.path.join(self.repo.path, "crlf-exists")
  5091. with open(file_path, "wb") as f:
  5092. f.write(b"line1\r\nline2")
  5093. porcelain.add(repo=self.repo.path, paths=[file_path])
  5094. porcelain.commit(
  5095. repo=self.repo.path,
  5096. message=b"test status",
  5097. author=b"author <email>",
  5098. committer=b"committer <email>",
  5099. )
  5100. c = self.repo.get_config()
  5101. c.set("core", "autocrlf", "input")
  5102. c.write_to_path()
  5103. # Add new (untracked) file
  5104. file_path = os.path.join(self.repo.path, "crlf-new")
  5105. with open(file_path, "wb") as f:
  5106. f.write(b"line1\r\nline2")
  5107. porcelain.add(repo=self.repo.path, paths=[file_path])
  5108. results = porcelain.status(self.repo)
  5109. self.assertDictEqual(
  5110. {"add": [b"crlf-new"], "delete": [], "modify": []}, results.staged
  5111. )
  5112. # File committed with CRLF before autocrlf=input was enabled
  5113. # will appear as unstaged because working tree is normalized to LF
  5114. # during comparison but index still has CRLF
  5115. self.assertListEqual(results.unstaged, [b"crlf-exists"])
  5116. self.assertListEqual(results.untracked, [])
  5117. def test_status_autocrlf_input_modified(self) -> None:
  5118. """Test that modified files with CRLF are correctly detected with autocrlf=input."""
  5119. # Commit existing file with CRLF
  5120. file_path = os.path.join(self.repo.path, "crlf-file.txt")
  5121. with open(file_path, "wb") as f:
  5122. f.write(b"line1\r\nline2\r\nline3\r\n")
  5123. porcelain.add(repo=self.repo.path, paths=[file_path])
  5124. porcelain.commit(
  5125. repo=self.repo.path,
  5126. message=b"initial commit",
  5127. author=b"author <email>",
  5128. committer=b"committer <email>",
  5129. )
  5130. c = self.repo.get_config()
  5131. c.set("core", "autocrlf", "input")
  5132. c.write_to_path()
  5133. # Modify the file content but keep CRLF
  5134. with open(file_path, "wb") as f:
  5135. f.write(b"line1\r\nline2 modified\r\nline3\r\n")
  5136. results = porcelain.status(self.repo)
  5137. # Modified file should be detected as unstaged
  5138. self.assertListEqual(results.unstaged, [b"crlf-file.txt"])
  5139. def test_status_autocrlf_input_binary(self) -> None:
  5140. """Test that binary files are not affected by autocrlf=input."""
  5141. # Set autocrlf=input first
  5142. c = self.repo.get_config()
  5143. c.set("core", "autocrlf", "input")
  5144. c.write_to_path()
  5145. # Commit binary file with CRLF-like sequences
  5146. file_path = os.path.join(self.repo.path, "binary.dat")
  5147. with open(file_path, "wb") as f:
  5148. f.write(b"binary\r\ndata\x00\xff\r\nmore")
  5149. porcelain.add(repo=self.repo.path, paths=[file_path])
  5150. porcelain.commit(
  5151. repo=self.repo.path,
  5152. message=b"add binary",
  5153. author=b"author <email>",
  5154. committer=b"committer <email>",
  5155. )
  5156. # Status should be clean - binary files not normalized
  5157. results = porcelain.status(self.repo)
  5158. self.assertListEqual(results.unstaged, [])
  5159. def test_status_autocrlf_input_mixed_endings(self) -> None:
  5160. """Test files with mixed line endings with autocrlf=input."""
  5161. # Set autocrlf=input
  5162. c = self.repo.get_config()
  5163. c.set("core", "autocrlf", "input")
  5164. c.write_to_path()
  5165. # Create file with mixed line endings
  5166. file_path = os.path.join(self.repo.path, "mixed.txt")
  5167. with open(file_path, "wb") as f:
  5168. f.write(b"line1\r\nline2\nline3\r\n")
  5169. porcelain.add(repo=self.repo.path, paths=[file_path])
  5170. porcelain.commit(
  5171. repo=self.repo.path,
  5172. message=b"add mixed",
  5173. author=b"author <email>",
  5174. committer=b"committer <email>",
  5175. )
  5176. # The file was normalized on commit, so working tree should match
  5177. results = porcelain.status(self.repo)
  5178. self.assertListEqual(results.unstaged, [])
  5179. def test_status_autocrlf_input_issue_1770(self) -> None:
  5180. """Test the specific scenario from issue #1770.
  5181. Files with CRLF committed with autocrlf=input should not show as unstaged
  5182. when their content hasn't changed.
  5183. """
  5184. # Set autocrlf=input BEFORE committing
  5185. c = self.repo.get_config()
  5186. c.set("core", "autocrlf", "input")
  5187. c.write_to_path()
  5188. # Create and commit file with CRLF endings
  5189. file_path = os.path.join(self.repo.path, "crlf-test.dsp")
  5190. with open(file_path, "wb") as f:
  5191. f.write(b"# Microsoft DSP file\r\n\r\nContent here\r\n")
  5192. porcelain.add(repo=self.repo.path, paths=[file_path])
  5193. porcelain.commit(
  5194. repo=self.repo.path,
  5195. message=b"add dsp file",
  5196. author=b"author <email>",
  5197. committer=b"committer <email>",
  5198. )
  5199. # File was normalized to LF in index, but working tree still has CRLF
  5200. # Status should be clean because comparison normalizes working tree too
  5201. results = porcelain.status(self.repo)
  5202. self.assertListEqual(results.unstaged, [])
  5203. def test_get_tree_changes_add(self) -> None:
  5204. """Unit test for get_tree_changes add."""
  5205. # Make a dummy file, stage
  5206. filename = "bar"
  5207. fullpath = os.path.join(self.repo.path, filename)
  5208. with open(fullpath, "w") as f:
  5209. f.write("stuff")
  5210. porcelain.add(repo=self.repo.path, paths=fullpath)
  5211. porcelain.commit(
  5212. repo=self.repo.path,
  5213. message=b"test status",
  5214. author=b"author <email>",
  5215. committer=b"committer <email>",
  5216. )
  5217. filename = "foo"
  5218. fullpath = os.path.join(self.repo.path, filename)
  5219. with open(fullpath, "w") as f:
  5220. f.write("stuff")
  5221. porcelain.add(repo=self.repo.path, paths=fullpath)
  5222. changes = porcelain.get_tree_changes(self.repo.path)
  5223. self.assertEqual(changes["add"][0], filename.encode("ascii"))
  5224. self.assertEqual(len(changes["add"]), 1)
  5225. self.assertEqual(len(changes["modify"]), 0)
  5226. self.assertEqual(len(changes["delete"]), 0)
  5227. def test_get_tree_changes_modify(self) -> None:
  5228. """Unit test for get_tree_changes modify."""
  5229. # Make a dummy file, stage, commit, modify
  5230. filename = "foo"
  5231. fullpath = os.path.join(self.repo.path, filename)
  5232. with open(fullpath, "w") as f:
  5233. f.write("stuff")
  5234. porcelain.add(repo=self.repo.path, paths=fullpath)
  5235. porcelain.commit(
  5236. repo=self.repo.path,
  5237. message=b"test status",
  5238. author=b"author <email>",
  5239. committer=b"committer <email>",
  5240. )
  5241. with open(fullpath, "w") as f:
  5242. f.write("otherstuff")
  5243. porcelain.add(repo=self.repo.path, paths=fullpath)
  5244. changes = porcelain.get_tree_changes(self.repo.path)
  5245. self.assertEqual(changes["modify"][0], filename.encode("ascii"))
  5246. self.assertEqual(len(changes["add"]), 0)
  5247. self.assertEqual(len(changes["modify"]), 1)
  5248. self.assertEqual(len(changes["delete"]), 0)
  5249. def test_get_tree_changes_delete(self) -> None:
  5250. """Unit test for get_tree_changes delete."""
  5251. # Make a dummy file, stage, commit, remove
  5252. filename = "foo"
  5253. fullpath = os.path.join(self.repo.path, filename)
  5254. with open(fullpath, "w") as f:
  5255. f.write("stuff")
  5256. porcelain.add(repo=self.repo.path, paths=fullpath)
  5257. porcelain.commit(
  5258. repo=self.repo.path,
  5259. message=b"test status",
  5260. author=b"author <email>",
  5261. committer=b"committer <email>",
  5262. )
  5263. cwd = os.getcwd()
  5264. self.addCleanup(os.chdir, cwd)
  5265. os.chdir(self.repo.path)
  5266. porcelain.remove(repo=self.repo.path, paths=[filename])
  5267. changes = porcelain.get_tree_changes(self.repo.path)
  5268. self.assertEqual(changes["delete"][0], filename.encode("ascii"))
  5269. self.assertEqual(len(changes["add"]), 0)
  5270. self.assertEqual(len(changes["modify"]), 0)
  5271. self.assertEqual(len(changes["delete"]), 1)
  5272. def test_get_untracked_paths(self) -> None:
  5273. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5274. f.write("ignored\n")
  5275. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  5276. f.write("blah\n")
  5277. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5278. f.write("blah\n")
  5279. os.symlink(
  5280. os.path.join(self.repo.path, os.pardir, "external_target"),
  5281. os.path.join(self.repo.path, "link"),
  5282. )
  5283. self.assertEqual(
  5284. {"ignored", "notignored", ".gitignore", "link"},
  5285. set(
  5286. porcelain.get_untracked_paths(
  5287. self.repo.path, self.repo.path, self.repo.open_index()
  5288. )
  5289. ),
  5290. )
  5291. self.assertEqual(
  5292. {".gitignore", "notignored", "link"},
  5293. set(porcelain.status(self.repo).untracked),
  5294. )
  5295. self.assertEqual(
  5296. {".gitignore", "notignored", "ignored", "link"},
  5297. set(porcelain.status(self.repo, ignored=True).untracked),
  5298. )
  5299. def test_get_untracked_paths_subrepo(self) -> None:
  5300. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5301. f.write("nested/\n")
  5302. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5303. f.write("blah\n")
  5304. subrepo = Repo.init(os.path.join(self.repo.path, "nested"), mkdir=True)
  5305. with open(os.path.join(subrepo.path, "ignored"), "w") as f:
  5306. f.write("bleep\n")
  5307. with open(os.path.join(subrepo.path, "with"), "w") as f:
  5308. f.write("bloop\n")
  5309. with open(os.path.join(subrepo.path, "manager"), "w") as f:
  5310. f.write("blop\n")
  5311. self.assertEqual(
  5312. {".gitignore", "notignored", os.path.join("nested", "")},
  5313. set(
  5314. porcelain.get_untracked_paths(
  5315. self.repo.path, self.repo.path, self.repo.open_index()
  5316. )
  5317. ),
  5318. )
  5319. self.assertEqual(
  5320. {".gitignore", "notignored"},
  5321. set(
  5322. porcelain.get_untracked_paths(
  5323. self.repo.path,
  5324. self.repo.path,
  5325. self.repo.open_index(),
  5326. exclude_ignored=True,
  5327. )
  5328. ),
  5329. )
  5330. self.assertEqual(
  5331. {"ignored", "with", "manager"},
  5332. set(
  5333. porcelain.get_untracked_paths(
  5334. subrepo.path, subrepo.path, subrepo.open_index()
  5335. )
  5336. ),
  5337. )
  5338. self.assertEqual(
  5339. set(),
  5340. set(
  5341. porcelain.get_untracked_paths(
  5342. subrepo.path,
  5343. self.repo.path,
  5344. self.repo.open_index(),
  5345. )
  5346. ),
  5347. )
  5348. self.assertEqual(
  5349. {
  5350. os.path.join("nested", "ignored"),
  5351. os.path.join("nested", "with"),
  5352. os.path.join("nested", "manager"),
  5353. },
  5354. set(
  5355. porcelain.get_untracked_paths(
  5356. self.repo.path,
  5357. subrepo.path,
  5358. self.repo.open_index(),
  5359. )
  5360. ),
  5361. )
  5362. def test_get_untracked_paths_nested_gitignore(self) -> None:
  5363. """Test directories with nested .gitignore files that ignore all contents."""
  5364. # Create cache directories with .gitignore files that contain "*"
  5365. cache_dirs = [".ruff_cache", ".pytest_cache", "__pycache__"]
  5366. for cache_dir in cache_dirs:
  5367. cache_path = os.path.join(self.repo.path, cache_dir)
  5368. os.mkdir(cache_path)
  5369. # Create .gitignore with * pattern (ignores everything)
  5370. with open(os.path.join(cache_path, ".gitignore"), "w") as f:
  5371. f.write("*\n")
  5372. # Create some files in the cache directory
  5373. with open(os.path.join(cache_path, "somefile.txt"), "w") as f:
  5374. f.write("cached data\n")
  5375. with open(os.path.join(cache_path, "data.json"), "w") as f:
  5376. f.write("{}\n")
  5377. # Create a normal untracked file
  5378. with open(os.path.join(self.repo.path, "untracked.txt"), "w") as f:
  5379. f.write("untracked content\n")
  5380. # Test with exclude_ignored=True (default for status)
  5381. untracked = set(
  5382. porcelain.get_untracked_paths(
  5383. self.repo.path,
  5384. self.repo.path,
  5385. self.repo.open_index(),
  5386. exclude_ignored=True,
  5387. untracked_files="normal",
  5388. )
  5389. )
  5390. # Cache directories should NOT be in untracked since all their contents are ignored
  5391. self.assertEqual({"untracked.txt"}, untracked)
  5392. # Test with exclude_ignored=False
  5393. untracked_with_ignored = set(
  5394. porcelain.get_untracked_paths(
  5395. self.repo.path,
  5396. self.repo.path,
  5397. self.repo.open_index(),
  5398. exclude_ignored=False,
  5399. untracked_files="normal",
  5400. )
  5401. )
  5402. # Cache directories should be included when not excluding ignored
  5403. expected = {"untracked.txt"}
  5404. for cache_dir in cache_dirs:
  5405. expected.add(cache_dir + os.sep)
  5406. self.assertEqual(expected, untracked_with_ignored)
  5407. # Test status() which uses exclude_ignored=True by default
  5408. status = porcelain.status(self.repo)
  5409. self.assertEqual(["untracked.txt"], status.untracked)
  5410. # Test status() with ignored=True which uses exclude_ignored=False
  5411. status_with_ignored = porcelain.status(self.repo, ignored=True)
  5412. # Should include cache directories
  5413. self.assertIn("untracked.txt", status_with_ignored.untracked)
  5414. for cache_dir in cache_dirs:
  5415. self.assertIn(cache_dir + "/", status_with_ignored.untracked)
  5416. def test_get_untracked_paths_mixed_directory(self) -> None:
  5417. """Test directory with both ignored and non-ignored files."""
  5418. # Create a directory with mixed content
  5419. mixed_dir = os.path.join(self.repo.path, "mixed")
  5420. os.mkdir(mixed_dir)
  5421. # Create .gitignore that ignores .log files
  5422. with open(os.path.join(mixed_dir, ".gitignore"), "w") as f:
  5423. f.write("*.log\n")
  5424. # Create ignored and non-ignored files
  5425. with open(os.path.join(mixed_dir, "debug.log"), "w") as f:
  5426. f.write("debug info\n")
  5427. with open(os.path.join(mixed_dir, "readme.txt"), "w") as f:
  5428. f.write("important\n")
  5429. # Test with exclude_ignored=True and normal mode
  5430. untracked = set(
  5431. porcelain.get_untracked_paths(
  5432. self.repo.path,
  5433. self.repo.path,
  5434. self.repo.open_index(),
  5435. exclude_ignored=True,
  5436. untracked_files="normal",
  5437. )
  5438. )
  5439. # In normal mode, should show the directory (matching git behavior)
  5440. self.assertEqual({os.path.join("mixed", "")}, untracked)
  5441. # Test with untracked_files="all"
  5442. untracked_all = set(
  5443. porcelain.get_untracked_paths(
  5444. self.repo.path,
  5445. self.repo.path,
  5446. self.repo.open_index(),
  5447. exclude_ignored=True,
  5448. untracked_files="all",
  5449. )
  5450. )
  5451. # Should list the non-ignored files
  5452. expected = {
  5453. os.path.join("mixed", ".gitignore"),
  5454. os.path.join("mixed", "readme.txt"),
  5455. }
  5456. self.assertEqual(expected, untracked_all)
  5457. def test_get_untracked_paths_specific_ignore_pattern(self) -> None:
  5458. """Test directory with .gitignore that ignores specific files, not all."""
  5459. # Create a directory
  5460. test_dir = os.path.join(self.repo.path, "testdir")
  5461. os.mkdir(test_dir)
  5462. # Create .gitignore that ignores only files named "test"
  5463. with open(os.path.join(test_dir, ".gitignore"), "w") as f:
  5464. f.write("test\n")
  5465. # Create files
  5466. with open(os.path.join(test_dir, "test"), "w") as f:
  5467. f.write("ignored\n")
  5468. with open(os.path.join(test_dir, "other.txt"), "w") as f:
  5469. f.write("not ignored\n")
  5470. # Test with exclude_ignored=True and normal mode
  5471. untracked = set(
  5472. porcelain.get_untracked_paths(
  5473. self.repo.path,
  5474. self.repo.path,
  5475. self.repo.open_index(),
  5476. exclude_ignored=True,
  5477. untracked_files="normal",
  5478. )
  5479. )
  5480. # Directory should be shown because it has non-ignored files
  5481. self.assertEqual({os.path.join("testdir", "")}, untracked)
  5482. def test_get_untracked_paths_nested_subdirs_all_ignored(self) -> None:
  5483. """Test directory containing only subdirectories where all files are ignored."""
  5484. # Create parent directory with .gitignore that ignores everything
  5485. parent_dir = os.path.join(self.repo.path, "parent")
  5486. os.mkdir(parent_dir)
  5487. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5488. f.write("*\n")
  5489. # Create subdirectories with files (all should be ignored by parent's .gitignore)
  5490. sub1 = os.path.join(parent_dir, "sub1")
  5491. sub2 = os.path.join(parent_dir, "sub2")
  5492. os.mkdir(sub1)
  5493. os.mkdir(sub2)
  5494. # Create files in subdirectories
  5495. with open(os.path.join(sub1, "file1.txt"), "w") as f:
  5496. f.write("content1\n")
  5497. with open(os.path.join(sub2, "file2.txt"), "w") as f:
  5498. f.write("content2\n")
  5499. # Create another normal untracked file
  5500. with open(os.path.join(self.repo.path, "normal.txt"), "w") as f:
  5501. f.write("normal\n")
  5502. # Test with exclude_ignored=True
  5503. untracked = set(
  5504. porcelain.get_untracked_paths(
  5505. self.repo.path,
  5506. self.repo.path,
  5507. self.repo.open_index(),
  5508. exclude_ignored=True,
  5509. untracked_files="normal",
  5510. )
  5511. )
  5512. # Parent directory should NOT be shown since all nested files are ignored
  5513. self.assertEqual({"normal.txt"}, untracked)
  5514. def test_get_untracked_paths_nested_subdirs_mixed(self) -> None:
  5515. """Test directory containing only subdirectories where some files are ignored, some aren't."""
  5516. # Create parent directory with .gitignore that ignores .log files
  5517. parent_dir = os.path.join(self.repo.path, "parent")
  5518. os.mkdir(parent_dir)
  5519. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5520. f.write("*.log\n")
  5521. # Create subdirectories
  5522. sub1 = os.path.join(parent_dir, "sub1")
  5523. sub2 = os.path.join(parent_dir, "sub2")
  5524. os.mkdir(sub1)
  5525. os.mkdir(sub2)
  5526. # sub1: only ignored files
  5527. with open(os.path.join(sub1, "debug.log"), "w") as f:
  5528. f.write("log content\n")
  5529. with open(os.path.join(sub1, "error.log"), "w") as f:
  5530. f.write("error log\n")
  5531. # sub2: mix of ignored and non-ignored files
  5532. with open(os.path.join(sub2, "access.log"), "w") as f:
  5533. f.write("access log\n")
  5534. with open(os.path.join(sub2, "readme.txt"), "w") as f:
  5535. f.write("important info\n")
  5536. # Test with exclude_ignored=True
  5537. untracked = set(
  5538. porcelain.get_untracked_paths(
  5539. self.repo.path,
  5540. self.repo.path,
  5541. self.repo.open_index(),
  5542. exclude_ignored=True,
  5543. untracked_files="normal",
  5544. )
  5545. )
  5546. # Parent directory SHOULD be shown since sub2 has non-ignored files
  5547. self.assertEqual({os.path.join("parent", "")}, untracked)
  5548. def test_get_untracked_paths_deeply_nested_all_ignored(self) -> None:
  5549. """Test deeply nested directories where all files are eventually ignored."""
  5550. # Create nested structure: parent/sub/subsub/
  5551. parent_dir = os.path.join(self.repo.path, "parent")
  5552. sub_dir = os.path.join(parent_dir, "sub")
  5553. subsub_dir = os.path.join(sub_dir, "subsub")
  5554. os.makedirs(subsub_dir)
  5555. # Parent has .gitignore that ignores everything
  5556. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5557. f.write("*\n")
  5558. # Create files at different levels
  5559. with open(os.path.join(subsub_dir, "deep_file.txt"), "w") as f:
  5560. f.write("deep content\n")
  5561. with open(os.path.join(sub_dir, "mid_file.txt"), "w") as f:
  5562. f.write("mid content\n")
  5563. # Test with exclude_ignored=True
  5564. untracked = set(
  5565. porcelain.get_untracked_paths(
  5566. self.repo.path,
  5567. self.repo.path,
  5568. self.repo.open_index(),
  5569. exclude_ignored=True,
  5570. untracked_files="normal",
  5571. )
  5572. )
  5573. # Parent directory should NOT be shown since all nested files are ignored
  5574. self.assertEqual(set(), untracked)
  5575. def test_get_untracked_paths_subdir(self) -> None:
  5576. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5577. f.write("subdir/\nignored")
  5578. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5579. f.write("blah\n")
  5580. os.mkdir(os.path.join(self.repo.path, "subdir"))
  5581. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  5582. f.write("foo")
  5583. with open(os.path.join(self.repo.path, "subdir", "ignored"), "w") as f:
  5584. f.write("foo")
  5585. self.assertEqual(
  5586. {
  5587. ".gitignore",
  5588. "notignored",
  5589. "ignored",
  5590. os.path.join("subdir", ""),
  5591. },
  5592. set(
  5593. porcelain.get_untracked_paths(
  5594. self.repo.path,
  5595. self.repo.path,
  5596. self.repo.open_index(),
  5597. )
  5598. ),
  5599. )
  5600. self.assertEqual(
  5601. {".gitignore", "notignored"},
  5602. set(
  5603. porcelain.get_untracked_paths(
  5604. self.repo.path,
  5605. self.repo.path,
  5606. self.repo.open_index(),
  5607. exclude_ignored=True,
  5608. )
  5609. ),
  5610. )
  5611. def test_get_untracked_paths_invalid_untracked_files(self) -> None:
  5612. with self.assertRaises(ValueError):
  5613. list(
  5614. porcelain.get_untracked_paths(
  5615. self.repo.path,
  5616. self.repo.path,
  5617. self.repo.open_index(),
  5618. untracked_files="invalid_value",
  5619. )
  5620. )
  5621. def test_get_untracked_paths_normal(self) -> None:
  5622. # Create an untracked directory with files
  5623. untracked_dir = os.path.join(self.repo.path, "untracked_dir")
  5624. os.mkdir(untracked_dir)
  5625. with open(os.path.join(untracked_dir, "file1.txt"), "w") as f:
  5626. f.write("untracked content")
  5627. with open(os.path.join(untracked_dir, "file2.txt"), "w") as f:
  5628. f.write("more untracked content")
  5629. # Test that "normal" mode works and returns only the directory
  5630. _, _, untracked = porcelain.status(
  5631. repo=self.repo.path, untracked_files="normal"
  5632. )
  5633. self.assertEqual(untracked, ["untracked_dir/"])
  5634. def test_get_untracked_paths_top_level_issue_1247(self) -> None:
  5635. """Test for issue #1247: ensure top-level untracked files are detected."""
  5636. # Create a single top-level untracked file
  5637. with open(os.path.join(self.repo.path, "sample.txt"), "w") as f:
  5638. f.write("test content")
  5639. # Test get_untracked_paths directly
  5640. untracked = list(
  5641. porcelain.get_untracked_paths(
  5642. self.repo.path, self.repo.path, self.repo.open_index()
  5643. )
  5644. )
  5645. self.assertIn(
  5646. "sample.txt",
  5647. untracked,
  5648. "Top-level file 'sample.txt' should be in untracked list",
  5649. )
  5650. # Test via status
  5651. status = porcelain.status(self.repo)
  5652. self.assertIn(
  5653. "sample.txt",
  5654. status.untracked,
  5655. "Top-level file 'sample.txt' should be in status.untracked",
  5656. )
  5657. # TODO(jelmer): Add test for dulwich.porcelain.daemon
  5658. class ShortlogTests(PorcelainTestCase):
  5659. def test_shortlog(self) -> None:
  5660. """Test porcelain.shortlog function with multiple authors and commits."""
  5661. # Create first file and commit
  5662. file_a = os.path.join(self.repo.path, "a.txt")
  5663. with open(file_a, "w") as f:
  5664. f.write("hello")
  5665. porcelain.add(self.repo.path, paths=[file_a])
  5666. porcelain.commit(
  5667. repo=self.repo.path,
  5668. message=b"Initial commit",
  5669. author=b"John <john@example.com>",
  5670. )
  5671. # Create second file and commit
  5672. file_b = os.path.join(self.repo.path, "b.txt")
  5673. with open(file_b, "w") as f:
  5674. f.write("update")
  5675. porcelain.add(self.repo.path, paths=[file_b])
  5676. porcelain.commit(
  5677. repo=self.repo.path,
  5678. message=b"Update file",
  5679. author=b"Doe <doe@example.com>",
  5680. )
  5681. # Call shortlog
  5682. output = porcelain.shortlog(self.repo.path)
  5683. expected = [
  5684. {"author": "John <john@example.com>", "messages": "Initial commit"},
  5685. {"author": "Doe <doe@example.com>", "messages": "Update file"},
  5686. ]
  5687. self.assertCountEqual(output, expected)
  5688. # Test summary output (count of messages)
  5689. output_summary = [
  5690. {"author": entry["author"], "count": len(entry["messages"].splitlines())}
  5691. for entry in output
  5692. ]
  5693. expected_summary = [
  5694. {"author": "John <john@example.com>", "count": 1},
  5695. {"author": "Doe <doe@example.com>", "count": 1},
  5696. ]
  5697. self.assertCountEqual(output_summary, expected_summary)
  5698. class UploadPackTests(PorcelainTestCase):
  5699. """Tests for upload_pack."""
  5700. def test_upload_pack(self) -> None:
  5701. outf = BytesIO()
  5702. exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf)
  5703. outlines = outf.getvalue().splitlines()
  5704. self.assertEqual([b"0000"], outlines)
  5705. self.assertEqual(0, exitcode)
  5706. class ReceivePackTests(PorcelainTestCase):
  5707. """Tests for receive_pack."""
  5708. def test_receive_pack(self) -> None:
  5709. filename = "foo"
  5710. fullpath = os.path.join(self.repo.path, filename)
  5711. with open(fullpath, "w") as f:
  5712. f.write("stuff")
  5713. porcelain.add(repo=self.repo.path, paths=fullpath)
  5714. self.repo.get_worktree().commit(
  5715. message=b"test status",
  5716. committer=b"committer <email>",
  5717. author=b"author <email>",
  5718. commit_timestamp=1402354300,
  5719. commit_timezone=0,
  5720. author_timestamp=1402354300,
  5721. author_timezone=0,
  5722. )
  5723. outf = BytesIO()
  5724. exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf)
  5725. outlines = outf.getvalue().splitlines()
  5726. self.assertEqual(
  5727. [
  5728. b"0091319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status "
  5729. b"delete-refs quiet ofs-delta side-band-64k "
  5730. b"no-done symref=HEAD:refs/heads/master",
  5731. b"003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master",
  5732. b"0000",
  5733. ],
  5734. outlines,
  5735. )
  5736. self.assertEqual(0, exitcode)
  5737. class BranchListTests(PorcelainTestCase):
  5738. def test_standard(self) -> None:
  5739. self.assertEqual(set(), set(porcelain.branch_list(self.repo)))
  5740. def test_new_branch(self) -> None:
  5741. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5742. self.repo[b"HEAD"] = c1.id
  5743. porcelain.branch_create(self.repo, b"foo")
  5744. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  5745. def test_sort_by_refname(self) -> None:
  5746. """Test branch.sort=refname (default alphabetical)."""
  5747. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5748. self.repo[b"HEAD"] = c1.id
  5749. # Create branches in non-alphabetical order
  5750. porcelain.branch_create(self.repo, b"zebra")
  5751. porcelain.branch_create(self.repo, b"alpha")
  5752. porcelain.branch_create(self.repo, b"beta")
  5753. # Set branch.sort to refname (though it's the default)
  5754. config = self.repo.get_config()
  5755. config.set((b"branch",), b"sort", b"refname")
  5756. config.write_to_path()
  5757. # Should be sorted alphabetically
  5758. branches = porcelain.branch_list(self.repo)
  5759. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5760. def test_sort_by_refname_reverse(self) -> None:
  5761. """Test branch.sort=-refname (reverse alphabetical)."""
  5762. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5763. self.repo[b"HEAD"] = c1.id
  5764. # Create branches
  5765. porcelain.branch_create(self.repo, b"zebra")
  5766. porcelain.branch_create(self.repo, b"alpha")
  5767. porcelain.branch_create(self.repo, b"beta")
  5768. # Set branch.sort to -refname
  5769. config = self.repo.get_config()
  5770. config.set((b"branch",), b"sort", b"-refname")
  5771. config.write_to_path()
  5772. # Should be sorted reverse alphabetically
  5773. branches = porcelain.branch_list(self.repo)
  5774. self.assertEqual([b"zebra", b"master", b"beta", b"alpha"], branches)
  5775. def test_sort_by_committerdate(self) -> None:
  5776. """Test branch.sort=committerdate."""
  5777. # Use build_commit_graph to create proper commits with specific times
  5778. c1, c2, c3 = build_commit_graph(
  5779. self.repo.object_store,
  5780. [[1], [2], [3]],
  5781. attrs={
  5782. 1: {"commit_time": 1000}, # oldest
  5783. 2: {"commit_time": 2000}, # newest
  5784. 3: {"commit_time": 1500}, # middle
  5785. },
  5786. )
  5787. self.repo[b"HEAD"] = c1.id
  5788. # Create branches pointing to different commits
  5789. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  5790. self.repo.refs[b"refs/heads/oldest"] = c1.id
  5791. self.repo.refs[b"refs/heads/newest"] = c2.id
  5792. self.repo.refs[b"refs/heads/middle"] = c3.id
  5793. # Set branch.sort to committerdate
  5794. config = self.repo.get_config()
  5795. config.set((b"branch",), b"sort", b"committerdate")
  5796. config.write_to_path()
  5797. # Should be sorted by commit time (oldest first)
  5798. branches = porcelain.branch_list(self.repo)
  5799. self.assertEqual([b"master", b"oldest", b"middle", b"newest"], branches)
  5800. def test_sort_by_committerdate_reverse(self) -> None:
  5801. """Test branch.sort=-committerdate."""
  5802. # Use build_commit_graph to create proper commits with specific times
  5803. c1, c2, c3 = build_commit_graph(
  5804. self.repo.object_store,
  5805. [[1], [2], [3]],
  5806. attrs={
  5807. 1: {"commit_time": 1000}, # oldest
  5808. 2: {"commit_time": 2000}, # newest
  5809. 3: {"commit_time": 1500}, # middle
  5810. },
  5811. )
  5812. self.repo[b"HEAD"] = c1.id
  5813. # Create branches pointing to different commits
  5814. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  5815. self.repo.refs[b"refs/heads/oldest"] = c1.id
  5816. self.repo.refs[b"refs/heads/newest"] = c2.id
  5817. self.repo.refs[b"refs/heads/middle"] = c3.id
  5818. # Set branch.sort to -committerdate
  5819. config = self.repo.get_config()
  5820. config.set((b"branch",), b"sort", b"-committerdate")
  5821. config.write_to_path()
  5822. # Should be sorted by commit time (newest first)
  5823. branches = porcelain.branch_list(self.repo)
  5824. self.assertEqual([b"newest", b"middle", b"master", b"oldest"], branches)
  5825. def test_sort_default(self) -> None:
  5826. """Test default sorting (no config)."""
  5827. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5828. self.repo[b"HEAD"] = c1.id
  5829. # Create branches in non-alphabetical order
  5830. porcelain.branch_create(self.repo, b"zebra")
  5831. porcelain.branch_create(self.repo, b"alpha")
  5832. porcelain.branch_create(self.repo, b"beta")
  5833. # No config set - should default to alphabetical
  5834. branches = porcelain.branch_list(self.repo)
  5835. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5836. class BranchRemoteListTests(PorcelainTestCase):
  5837. def test_no_remote_branches(self) -> None:
  5838. """Test with no remote branches."""
  5839. result = porcelain.branch_remotes_list(self.repo)
  5840. self.assertEqual([], result)
  5841. def test_remote_branches_refname_sort(self) -> None:
  5842. """Test remote branches sorting with refname (alphabetical)."""
  5843. # Create some remote branches
  5844. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5845. # Create remote branches is non-alphabetical order
  5846. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  5847. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  5848. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  5849. self.repo.refs[b"refs/remotes/origin/feature-4"] = c1.id
  5850. # Set branch.sort to refname
  5851. config = self.repo.get_config()
  5852. config.set((b"branch",), b"sort", b"refname")
  5853. config.write_to_path()
  5854. # Should return only branch names, sorted alphabetically
  5855. branches = porcelain.branch_remotes_list(self.repo)
  5856. expected = [
  5857. b"origin/feature-1",
  5858. b"origin/feature-2",
  5859. b"origin/feature-3",
  5860. b"origin/feature-4",
  5861. ]
  5862. self.assertEqual(expected, branches)
  5863. def test_remote_branches_refname_reverse_sort(self) -> None:
  5864. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5865. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  5866. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  5867. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  5868. self.repo.refs[b"refs/remotes/origin/feature-4"] = c1.id
  5869. # Set branch.sort to -refname
  5870. config = self.repo.get_config()
  5871. config.set((b"branch",), b"sort", b"-refname")
  5872. config.write_to_path()
  5873. branches = porcelain.branch_remotes_list(self.repo)
  5874. expected = [
  5875. b"origin/feature-4",
  5876. b"origin/feature-3",
  5877. b"origin/feature-2",
  5878. b"origin/feature-1",
  5879. ]
  5880. self.assertEqual(expected, branches)
  5881. def test_remote_branches_committerdate_sort(self) -> None:
  5882. """Test remote branches sorting with committerdate"""
  5883. # Create commits with different timestamps
  5884. c1, c2, c3 = build_commit_graph(
  5885. self.repo.object_store,
  5886. [[1], [2], [3]],
  5887. attrs={
  5888. 1: {"commit_time": 1000},
  5889. 2: {"commit_time": 2000},
  5890. 3: {"commit_time": 3000},
  5891. },
  5892. )
  5893. self.repo.refs[b"refs/remotes/origin/oldest"] = c1.id
  5894. self.repo.refs[b"refs/remotes/origin/middle"] = c2.id
  5895. self.repo.refs[b"refs/remotes/origin/newest"] = c3.id
  5896. # Set branch.sort to committerdate
  5897. config = self.repo.get_config()
  5898. config.set((b"branch",), b"sort", b"committerdate")
  5899. config.write_to_path()
  5900. branches = porcelain.branch_remotes_list(self.repo)
  5901. # Should be sorted by commit time (oldest first), then alphabetically for same time
  5902. expected = [b"origin/oldest", b"origin/middle", b"origin/newest"]
  5903. self.assertEqual(expected, branches)
  5904. def test_remote_branches_committerdate_reverse_sort(self) -> None:
  5905. """Test remote branches sorting with -committerdate."""
  5906. c1, c2, c3 = build_commit_graph(
  5907. self.repo.object_store,
  5908. [[1], [2], [3]],
  5909. attrs={
  5910. 1: {"commit_time": 1000},
  5911. 2: {"commit_time": 2000},
  5912. 3: {"commit_time": 1500},
  5913. },
  5914. )
  5915. self.repo.refs[b"refs/remotes/origin/oldest"] = c1.id
  5916. self.repo.refs[b"refs/remotes/origin/newest"] = c2.id
  5917. self.repo.refs[b"refs/remotes/origin/middle"] = c3.id
  5918. # Set branch.sort to -committerdate
  5919. config = self.repo.get_config()
  5920. config.set((b"branch",), b"sort", b"-committerdate")
  5921. config.write_to_path()
  5922. branches = porcelain.branch_remotes_list(self.repo)
  5923. # Should be sorted by commit time (newest first), then alphabetically for same time
  5924. expected = [b"origin/newest", b"origin/middle", b"origin/oldest"]
  5925. self.assertEqual(expected, branches)
  5926. def test_remote_branches_authordate_sort(self) -> None:
  5927. """Test remote branches sorting with authordate."""
  5928. c1, c2, c3 = build_commit_graph(
  5929. self.repo.object_store,
  5930. [[1], [2], [3]],
  5931. attrs={
  5932. 1: {"author_time": 1500},
  5933. 2: {"author_time": 2000},
  5934. 3: {"author_time": 1000},
  5935. },
  5936. )
  5937. self.repo.refs[b"refs/remotes/origin/middle"] = c1.id
  5938. self.repo.refs[b"refs/remotes/origin/newest"] = c2.id
  5939. self.repo.refs[b"refs/remotes/origin/oldest"] = c3.id
  5940. # Set branch.sort to authordate
  5941. config = self.repo.get_config()
  5942. config.set((b"branch",), b"sort", b"authordate")
  5943. config.write_to_path()
  5944. branches = porcelain.branch_remotes_list(self.repo)
  5945. expected = [b"origin/oldest", b"origin/middle", b"origin/newest"]
  5946. self.assertEqual(expected, branches)
  5947. def test_unknown_sort_key(self) -> None:
  5948. """Test that unknown sort key raises ValueError."""
  5949. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5950. self.repo.refs[b"refs/remotes/origin/master"] = c1.id
  5951. # Set branch.sort to unknown key
  5952. config = self.repo.get_config()
  5953. config.set((b"branch",), b"sort", b"unknown")
  5954. config.write_to_path()
  5955. with self.assertRaises(ValueError) as cm:
  5956. porcelain.branch_remotes_list(self.repo)
  5957. self.assertIn("Unknown sort key: unknown", str(cm.exception))
  5958. def test_default_sort_no_config(self) -> None:
  5959. """Test default sorting when no config is set."""
  5960. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5961. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  5962. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  5963. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  5964. # No config set - should default to alphabetical
  5965. branches = porcelain.branch_remotes_list(self.repo)
  5966. expected = [b"origin/feature-1", b"origin/feature-2", b"origin/feature-3"]
  5967. self.assertEqual(expected, branches)
  5968. class BranchMergedTests(PorcelainTestCase):
  5969. def test_no_merged_branches(self) -> None:
  5970. """Test with no merged branches."""
  5971. # Create complete graph: c1 → c2 (master), c1 → c3 (feature)
  5972. [_c1, c2, c3] = build_commit_graph(
  5973. self.repo.object_store,
  5974. [
  5975. [1], # c1
  5976. [2, 1], # c2 → c1 (master line)
  5977. [3, 1], # c3 → c1 (diverged feature branch)
  5978. ],
  5979. )
  5980. self.repo.refs[b"HEAD"] = c2.id
  5981. self.repo.refs[b"refs/heads/master"] = c2.id
  5982. self.repo.refs[b"refs/heads/feature"] = c3.id
  5983. result = list(porcelain.merged_branches(self.repo))
  5984. self.assertEqual([b"master"], result)
  5985. def test_all_branches_merged(self) -> None:
  5986. """Test when all branches are merged into current."""
  5987. # Create linear history: c1 → c2 → c3 (HEAD)
  5988. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  5989. self.repo.refs[b"HEAD"] = c3.id
  5990. self.repo.refs[b"refs/heads/master"] = c3.id
  5991. self.repo.refs[b"refs/heads/feature-1"] = c2.id # Merged (ancestor)
  5992. self.repo.refs[b"refs/heads/feature-2"] = c1.id # Merged (ancestor)
  5993. branches = list(porcelain.merged_branches(self.repo))
  5994. expected = [b"feature-1", b"master", b"feature-2"]
  5995. expected.sort()
  5996. branches.sort()
  5997. self.assertEqual(expected, branches)
  5998. def test_some_branches_merged(self) -> None:
  5999. """Test when some branches are merged, some are not."""
  6000. # c1 → c2 → c3 (HEAD/master)
  6001. # c1 → c4 → c5 (feature-1 - diverged)
  6002. [_c1, c2, c3, _c4, c5] = build_commit_graph(
  6003. self.repo.object_store,
  6004. [
  6005. [1], # c1
  6006. [2, 1], # c2 → c1 (master line)
  6007. [3, 2], # c3 → c2 (HEAD)
  6008. [4, 1], # c4 → c1 (feature branch)
  6009. [5, 4], # c5 → c4 (feature branch)
  6010. ],
  6011. )
  6012. self.repo.refs[b"HEAD"] = c3.id
  6013. self.repo.refs[b"refs/heads/master"] = c3.id
  6014. self.repo.refs[b"refs/heads/feature-1"] = c5.id # Not merged (diverged)
  6015. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Merged (ancestor)
  6016. branches = list(porcelain.merged_branches(self.repo))
  6017. expected = [b"feature-2", b"master"]
  6018. expected.sort()
  6019. branches.sort()
  6020. self.assertEqual(expected, branches)
  6021. def test_only_current_branch_merged(self) -> None:
  6022. """Test when only current branch exists."""
  6023. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6024. self.repo.refs[b"HEAD"] = c1.id
  6025. self.repo.refs[b"refs/heads/master"] = c1.id
  6026. result = list(porcelain.merged_branches(self.repo))
  6027. self.assertEqual([b"master"], result)
  6028. class BranchNoMergedTests(PorcelainTestCase):
  6029. def test_all_branches_merged(self) -> None:
  6030. """Test when all branches are merged - should return empty list."""
  6031. # Create linear history: c1 → c2 → c3 (HEAD)
  6032. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  6033. self.repo.refs[b"HEAD"] = c3.id
  6034. self.repo.refs[b"refs/heads/master"] = c3.id
  6035. self.repo.refs[b"refs/heads/feature-1"] = c2.id # Merged (ancestor)
  6036. self.repo.refs[b"refs/heads/feature-2"] = c1.id # Merged (ancestor)
  6037. result = list(porcelain.no_merged_branches(self.repo))
  6038. self.assertEqual([], result)
  6039. def test_no_merged_branches(self) -> None:
  6040. """Test with some non-merged branches."""
  6041. # Create complete graph: c1 → c2 (master), c1 → c3 (feature)
  6042. [_c1, c2, c3] = build_commit_graph(
  6043. self.repo.object_store,
  6044. [
  6045. [1], # c1
  6046. [2, 1], # c2 → c1 (master line)
  6047. [3, 1], # c3 → c1 (diverged feature branch)
  6048. ],
  6049. )
  6050. self.repo.refs[b"HEAD"] = c2.id
  6051. self.repo.refs[b"refs/heads/master"] = c2.id
  6052. self.repo.refs[b"refs/heads/feature"] = c3.id
  6053. result = list(porcelain.no_merged_branches(self.repo))
  6054. self.assertEqual([b"feature"], result)
  6055. def test_some_branches_not_merged(self) -> None:
  6056. """Test when some branches are merged, some are not."""
  6057. # c1 → c2 → c3 (HEAD/master)
  6058. # c1 → c4 → c5 (feature-1 - diverged)
  6059. [_c1, c2, c3, _c4, c5] = build_commit_graph(
  6060. self.repo.object_store,
  6061. [
  6062. [1], # c1
  6063. [2, 1], # c2 → c1 (master line)
  6064. [3, 2], # c3 → c2 (HEAD)
  6065. [4, 1], # c4 → c1 (feature branch)
  6066. [5, 4], # c5 → c4 (feature branch)
  6067. ],
  6068. )
  6069. self.repo.refs[b"HEAD"] = c3.id
  6070. self.repo.refs[b"refs/heads/master"] = c3.id
  6071. self.repo.refs[b"refs/heads/feature-1"] = c5.id # Not merged (diverged)
  6072. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Merged (ancestor)
  6073. result = list(porcelain.no_merged_branches(self.repo))
  6074. self.assertEqual([b"feature-1"], result)
  6075. def test_multiple_branches_not_merged(self) -> None:
  6076. """Test with multiple non-merged branches."""
  6077. # c1 → c2 (HEAD/master)
  6078. # c1 → c3 (feature-1 - diverged)
  6079. # c1 → c4 (feature-2 - diverged)
  6080. [_c1, c2, c3, c4] = build_commit_graph(
  6081. self.repo.object_store,
  6082. [
  6083. [1], # c1
  6084. [2, 1], # c2 → c1 (master line)
  6085. [3, 1], # c3 → c1 (feature-1 branch)
  6086. [4, 1], # c4 → c1 (feature-2 branch)
  6087. ],
  6088. )
  6089. self.repo.refs[b"HEAD"] = c2.id
  6090. self.repo.refs[b"refs/heads/master"] = c2.id
  6091. self.repo.refs[b"refs/heads/feature-1"] = c3.id # Not merged (diverged)
  6092. self.repo.refs[b"refs/heads/feature-2"] = c4.id # Not merged (diverged)
  6093. branches = list(porcelain.no_merged_branches(self.repo))
  6094. expected = [b"feature-1", b"feature-2"]
  6095. expected.sort()
  6096. branches.sort()
  6097. self.assertEqual(expected, branches)
  6098. def test_only_current_branch_exists(self) -> None:
  6099. """Test when only current branch exists - should return empty list."""
  6100. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6101. self.repo.refs[b"HEAD"] = c1.id
  6102. self.repo.refs[b"refs/heads/master"] = c1.id
  6103. result = list(porcelain.no_merged_branches(self.repo))
  6104. self.assertEqual([], result)
  6105. class BranchContainsTests(PorcelainTestCase):
  6106. def test_commit_in_single_branch(self) -> None:
  6107. """Test commit contained in only one branch."""
  6108. # Create: c1 → c2 (master), c1 → c3 (feature)
  6109. [_c1, c2, c3] = build_commit_graph(
  6110. self.repo.object_store,
  6111. [
  6112. [1], # c1
  6113. [2, 1], # c2 → c1 (master line)
  6114. [3, 1], # c3 → c1 (feature branch)
  6115. ],
  6116. )
  6117. self.repo.refs[b"HEAD"] = c2.id
  6118. self.repo.refs[b"refs/heads/master"] = c2.id
  6119. self.repo.refs[b"refs/heads/feature"] = c3.id
  6120. # c2 is only in master branch
  6121. result = list(porcelain.branches_containing(self.repo, c2.id.decode()))
  6122. self.assertEqual([b"master"], result)
  6123. # c3 is only in feature branch
  6124. result = list(porcelain.branches_containing(self.repo, c3.id.decode()))
  6125. self.assertEqual([b"feature"], result)
  6126. def test_commit_in_multiple_branches(self) -> None:
  6127. """Test commit contained in multiple branches."""
  6128. # Create: c1 → c2 → c3 (master), c2 → c4 (feature)
  6129. [c1, c2, c3, c4] = build_commit_graph(
  6130. self.repo.object_store,
  6131. [
  6132. [1], # c1
  6133. [2, 1], # c2 → c1
  6134. [3, 2], # c3 → c2 (master)
  6135. [4, 2], # c4 → c2 (feature)
  6136. ],
  6137. )
  6138. self.repo.refs[b"HEAD"] = c3.id
  6139. self.repo.refs[b"refs/heads/master"] = c3.id
  6140. self.repo.refs[b"refs/heads/feature"] = c4.id
  6141. # c2 is in both branches (common ancestor)
  6142. branches = list(porcelain.branches_containing(self.repo, c2.id.decode()))
  6143. expected = [b"master", b"feature"]
  6144. expected.sort()
  6145. branches.sort()
  6146. self.assertEqual(expected, branches)
  6147. # c1 is in both branches (older common ancestor)
  6148. branches = list(porcelain.branches_containing(self.repo, c1.id.decode()))
  6149. expected = [b"master", b"feature"]
  6150. expected.sort()
  6151. branches.sort()
  6152. self.assertEqual(expected, branches)
  6153. def test_commit_in_all_branches(self) -> None:
  6154. """Test commit contained in all branches."""
  6155. # Create linear history: c1 → c2 → c3 (HEAD/master)
  6156. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  6157. self.repo.refs[b"HEAD"] = c3.id
  6158. self.repo.refs[b"refs/heads/master"] = c3.id
  6159. self.repo.refs[b"refs/heads/feature-1"] = c3.id # Same as master
  6160. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Ancestor
  6161. # c1 is in all branches
  6162. branches = list(porcelain.branches_containing(self.repo, c1.id.decode()))
  6163. expected = [b"master", b"feature-1", b"feature-2"]
  6164. expected.sort()
  6165. branches.sort()
  6166. self.assertEqual(expected, branches)
  6167. def test_commit_in_no_branches(self) -> None:
  6168. """Test commit not contained in any branch."""
  6169. # Create: c1 → c2 (master), c1 → c3 (feature), orphan c4
  6170. [_c1, c2, c3, c4] = build_commit_graph(
  6171. self.repo.object_store,
  6172. [
  6173. [1], # c1
  6174. [2, 1], # c2 → c1 (master)
  6175. [3, 1], # c3 → c1 (feature)
  6176. [4], # c4 (orphan commit)
  6177. ],
  6178. )
  6179. self.repo.refs[b"HEAD"] = c2.id
  6180. self.repo.refs[b"refs/heads/master"] = c2.id
  6181. self.repo.refs[b"refs/heads/feature"] = c3.id
  6182. # c4 is not in any branch
  6183. result = list(porcelain.branches_containing(self.repo, c4.id.decode()))
  6184. self.assertEqual([], result)
  6185. def test_commit_ref_by_branch_name(self) -> None:
  6186. """Test using branch name as commit reference."""
  6187. # Create: c1 → c2 (master), c1 → c3 (feature)
  6188. [_c1, c2, c3] = build_commit_graph(
  6189. self.repo.object_store,
  6190. [
  6191. [1], # c1
  6192. [2, 1], # c2 → c1 (master)
  6193. [3, 1], # c3 → c1 (feature)
  6194. ],
  6195. )
  6196. self.repo.refs[b"HEAD"] = c2.id
  6197. self.repo.refs[b"refs/heads/master"] = c2.id
  6198. self.repo.refs[b"refs/heads/feature"] = c3.id
  6199. # Use "master" as commit reference - should find master branch
  6200. result = list(porcelain.branches_containing(self.repo, "master"))
  6201. self.assertEqual([b"master"], result)
  6202. # Use "feature" as commit reference - should find feature branch
  6203. result = list(porcelain.branches_containing(self.repo, "feature"))
  6204. self.assertEqual([b"feature"], result)
  6205. def test_commit_ref_by_head(self) -> None:
  6206. """Test using HEAD as commit reference."""
  6207. # Create: c1 → c2 → c3 (HEAD/master)
  6208. [_c1, c2, c3] = build_commit_graph(
  6209. self.repo.object_store, [[1], [2, 1], [3, 2]]
  6210. )
  6211. self.repo.refs[b"HEAD"] = c3.id
  6212. self.repo.refs[b"refs/heads/master"] = c3.id
  6213. self.repo.refs[b"refs/heads/feature"] = c2.id # Ancestor
  6214. # Use "HEAD" as commit reference
  6215. result = list(porcelain.branches_containing(self.repo, "HEAD"))
  6216. self.assertEqual([b"master"], result)
  6217. def test_invalid_commit_ref(self) -> None:
  6218. """Test with invalid commit reference."""
  6219. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6220. self.repo.refs[b"HEAD"] = c1.id
  6221. self.repo.refs[b"refs/heads/master"] = c1.id
  6222. # Test with non-existent commit
  6223. with self.assertRaises(KeyError) as cm:
  6224. list(porcelain.branches_containing(self.repo, "nonexistent"))
  6225. self.assertEqual(b"nonexistent", cm.exception.args[0])
  6226. # Test with invalid SHA
  6227. with self.assertRaises(KeyError) as cm:
  6228. list(porcelain.branches_containing(self.repo, "invalid-sha"))
  6229. self.assertEqual(b"invalid-sha", cm.exception.args[0])
  6230. def test_short_sha_reference(self) -> None:
  6231. """Test using short SHA as commit reference."""
  6232. # Create: c1 → c2 (master)
  6233. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2, 1]])
  6234. self.repo.refs[b"HEAD"] = c2.id
  6235. self.repo.refs[b"refs/heads/master"] = c2.id
  6236. # Use short SHA (first 7 characters)
  6237. short_sha = c1.id.decode()[:7]
  6238. result = list(porcelain.branches_containing(self.repo, short_sha))
  6239. self.assertEqual([b"master"], result)
  6240. class FilterBranchesByPatternTests(PorcelainTestCase):
  6241. """Tests for filter_branches_by_pattern function."""
  6242. def test_empty_branches(self) -> None:
  6243. """Test with empty branches list."""
  6244. result = porcelain.filter_branches_by_pattern([], "feature-*")
  6245. self.assertEqual([], result)
  6246. def test_star_pattern(self) -> None:
  6247. """Test wildcard pattern matching."""
  6248. branches = [b"main", b"feature-1", b"feature-2", b"develop", b"hotfix-bug"]
  6249. result = porcelain.filter_branches_by_pattern(branches, "feature-*")
  6250. expected = [b"feature-1", b"feature-2"]
  6251. self.assertEqual(expected, result)
  6252. def test_question_mark_pattern(self) -> None:
  6253. """Test single character wildcard pattern."""
  6254. branches = [b"main", b"feature-1", b"feature-2", b"feature-a", b"develop"]
  6255. result = porcelain.filter_branches_by_pattern(branches, "feature-?")
  6256. expected = [b"feature-1", b"feature-2", b"feature-a"]
  6257. self.assertEqual(expected, result)
  6258. def test_specific_pattern(self) -> None:
  6259. """Test exact match pattern."""
  6260. branches = [b"main", b"feature-1", b"feature-2", b"develop"]
  6261. result = porcelain.filter_branches_by_pattern(branches, "feature-1")
  6262. expected = [b"feature-1"]
  6263. self.assertEqual(expected, result)
  6264. def test_no_matches(self) -> None:
  6265. """Test pattern that matches no branches."""
  6266. branches = [b"main", b"feature-1", b"develop"]
  6267. result = porcelain.filter_branches_by_pattern(branches, "release-*")
  6268. self.assertEqual([], result)
  6269. def test_case_sensitive_pattern(self) -> None:
  6270. """Test case-sensitive pattern matching."""
  6271. branches = [b"Main", b"main", b"MAIN", b"develop"]
  6272. result = porcelain.filter_branches_by_pattern(branches, "main")
  6273. expected = [b"main"]
  6274. self.assertEqual(expected, result)
  6275. def test_multiple_patterns_behavior(self) -> None:
  6276. """Test that pattern works with multiple wildcards."""
  6277. branches = [
  6278. b"feature-login",
  6279. b"feature-signup",
  6280. b"bugfix-login",
  6281. b"hotfix-signup",
  6282. ]
  6283. result = porcelain.filter_branches_by_pattern(branches, "feature-*")
  6284. expected = [b"feature-login", b"feature-signup"]
  6285. self.assertEqual(expected, result)
  6286. def test_mixed_encoding_branches(self) -> None:
  6287. """Test with branches that have special characters."""
  6288. branches = [b"feature-1", b"feature/test", b"feature@prod", b"develop"]
  6289. result = porcelain.filter_branches_by_pattern(branches, "feature/*")
  6290. expected = [b"feature/test"]
  6291. self.assertEqual(expected, result)
  6292. def test_pattern_with_square_brackets(self) -> None:
  6293. """Test pattern with character classes."""
  6294. branches = [b"feature-1", b"feature-2", b"feature-a", b"feature-b", b"develop"]
  6295. result = porcelain.filter_branches_by_pattern(branches, "feature-[12]")
  6296. expected = [b"feature-1", b"feature-2"]
  6297. self.assertEqual(expected, result)
  6298. class BranchCreateTests(PorcelainTestCase):
  6299. def test_branch_exists(self) -> None:
  6300. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6301. self.repo[b"HEAD"] = c1.id
  6302. porcelain.branch_create(self.repo, b"foo")
  6303. self.assertRaises(porcelain.Error, porcelain.branch_create, self.repo, b"foo")
  6304. porcelain.branch_create(self.repo, b"foo", force=True)
  6305. def test_new_branch(self) -> None:
  6306. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6307. self.repo[b"HEAD"] = c1.id
  6308. porcelain.branch_create(self.repo, b"foo")
  6309. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  6310. def test_auto_setup_merge_true_from_remote_tracking(self) -> None:
  6311. """Test branch.autoSetupMerge=true sets up tracking from remote-tracking branch."""
  6312. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6313. self.repo[b"HEAD"] = c1.id
  6314. # Create a remote-tracking branch
  6315. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6316. # Set branch.autoSetupMerge to true (default)
  6317. config = self.repo.get_config()
  6318. config.set((b"branch",), b"autoSetupMerge", b"true")
  6319. config.write_to_path()
  6320. # Create branch from remote-tracking branch
  6321. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6322. # Verify tracking was set up
  6323. config = self.repo.get_config()
  6324. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6325. self.assertEqual(
  6326. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6327. )
  6328. def test_auto_setup_merge_false(self) -> None:
  6329. """Test branch.autoSetupMerge=false disables tracking setup."""
  6330. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6331. self.repo[b"HEAD"] = c1.id
  6332. # Create a remote-tracking branch
  6333. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6334. # Set branch.autoSetupMerge to false
  6335. config = self.repo.get_config()
  6336. config.set((b"branch",), b"autoSetupMerge", b"false")
  6337. config.write_to_path()
  6338. # Create branch from remote-tracking branch
  6339. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6340. # Verify tracking was NOT set up
  6341. config = self.repo.get_config()
  6342. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"remote")
  6343. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"merge")
  6344. def test_auto_setup_merge_always(self) -> None:
  6345. """Test branch.autoSetupMerge=always sets up tracking even from local branches."""
  6346. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6347. self.repo[b"HEAD"] = c1.id
  6348. self.repo.refs[b"refs/heads/main"] = c1.id
  6349. # Set branch.autoSetupMerge to always
  6350. config = self.repo.get_config()
  6351. config.set((b"branch",), b"autoSetupMerge", b"always")
  6352. config.write_to_path()
  6353. # Create branch from local branch - normally wouldn't set up tracking
  6354. porcelain.branch_create(self.repo, "feature", "main")
  6355. # With always, tracking should NOT be set up from local branches
  6356. # (Git only sets up tracking from remote-tracking branches even with always)
  6357. config = self.repo.get_config()
  6358. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"remote")
  6359. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"merge")
  6360. def test_auto_setup_merge_always_from_remote(self) -> None:
  6361. """Test branch.autoSetupMerge=always still sets up tracking from remote branches."""
  6362. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6363. self.repo[b"HEAD"] = c1.id
  6364. # Create a remote-tracking branch
  6365. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6366. # Set branch.autoSetupMerge to always
  6367. config = self.repo.get_config()
  6368. config.set((b"branch",), b"autoSetupMerge", b"always")
  6369. config.write_to_path()
  6370. # Create branch from remote-tracking branch
  6371. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6372. # Verify tracking was set up
  6373. config = self.repo.get_config()
  6374. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6375. self.assertEqual(
  6376. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6377. )
  6378. def test_auto_setup_merge_default(self) -> None:
  6379. """Test default behavior (no config) is same as true."""
  6380. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6381. self.repo[b"HEAD"] = c1.id
  6382. # Create a remote-tracking branch
  6383. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6384. # Don't set any config - should default to true
  6385. # Create branch from remote-tracking branch
  6386. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6387. # Verify tracking was set up
  6388. config = self.repo.get_config()
  6389. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6390. self.assertEqual(
  6391. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6392. )
  6393. class BranchDeleteTests(PorcelainTestCase):
  6394. def test_simple(self) -> None:
  6395. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6396. self.repo[b"HEAD"] = c1.id
  6397. porcelain.branch_create(self.repo, b"foo")
  6398. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  6399. porcelain.branch_delete(self.repo, b"foo")
  6400. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  6401. def test_simple_unicode(self) -> None:
  6402. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6403. self.repo[b"HEAD"] = c1.id
  6404. porcelain.branch_create(self.repo, "foo")
  6405. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  6406. porcelain.branch_delete(self.repo, "foo")
  6407. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  6408. class FetchTests(PorcelainTestCase):
  6409. def test_simple(self) -> None:
  6410. outstream = BytesIO()
  6411. errstream = BytesIO()
  6412. # create a file for initial commit
  6413. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6414. os.close(handle)
  6415. porcelain.add(repo=self.repo.path, paths=fullpath)
  6416. porcelain.commit(
  6417. repo=self.repo.path,
  6418. message=b"test",
  6419. author=b"test <email>",
  6420. committer=b"test <email>",
  6421. )
  6422. # Setup target repo
  6423. target_path = tempfile.mkdtemp()
  6424. self.addCleanup(shutil.rmtree, target_path)
  6425. target_repo = porcelain.clone(
  6426. self.repo.path, target=target_path, errstream=errstream
  6427. )
  6428. # create a second file to be pushed
  6429. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6430. os.close(handle)
  6431. porcelain.add(repo=self.repo.path, paths=fullpath)
  6432. porcelain.commit(
  6433. repo=self.repo.path,
  6434. message=b"test2",
  6435. author=b"test2 <email>",
  6436. committer=b"test2 <email>",
  6437. )
  6438. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  6439. target_repo.close()
  6440. # Fetch changes into the cloned repo
  6441. porcelain.fetch(target_path, "origin", outstream=outstream, errstream=errstream)
  6442. # Assert that fetch updated the local image of the remote
  6443. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  6444. # Check the target repo for pushed changes
  6445. with Repo(target_path) as r:
  6446. self.assertIn(self.repo[b"HEAD"].id, r)
  6447. def test_with_remote_name(self) -> None:
  6448. remote_name = "origin"
  6449. outstream = BytesIO()
  6450. errstream = BytesIO()
  6451. # create a file for initial commit
  6452. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6453. os.close(handle)
  6454. porcelain.add(repo=self.repo.path, paths=fullpath)
  6455. porcelain.commit(
  6456. repo=self.repo.path,
  6457. message=b"test",
  6458. author=b"test <email>",
  6459. committer=b"test <email>",
  6460. )
  6461. # Setup target repo
  6462. target_path = tempfile.mkdtemp()
  6463. self.addCleanup(shutil.rmtree, target_path)
  6464. target_repo = porcelain.clone(
  6465. self.repo.path, target=target_path, errstream=errstream
  6466. )
  6467. # Capture current refs
  6468. target_refs = target_repo.get_refs()
  6469. # create a second file to be pushed
  6470. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6471. os.close(handle)
  6472. porcelain.add(repo=self.repo.path, paths=fullpath)
  6473. porcelain.commit(
  6474. repo=self.repo.path,
  6475. message=b"test2",
  6476. author=b"test2 <email>",
  6477. committer=b"test2 <email>",
  6478. )
  6479. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  6480. target_config = target_repo.get_config()
  6481. target_config.set(
  6482. (b"remote", remote_name.encode()), b"url", self.repo.path.encode()
  6483. )
  6484. target_repo.close()
  6485. # Fetch changes into the cloned repo
  6486. porcelain.fetch(
  6487. target_path, remote_name, outstream=outstream, errstream=errstream
  6488. )
  6489. # Assert that fetch updated the local image of the remote
  6490. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  6491. # Check the target repo for pushed changes, as well as updates
  6492. # for the refs
  6493. with Repo(target_path) as r:
  6494. self.assertIn(self.repo[b"HEAD"].id, r)
  6495. self.assertNotEqual(self.repo.get_refs(), target_refs)
  6496. def assert_correct_remote_refs(
  6497. self, local_refs, remote_refs, remote_name=b"origin"
  6498. ) -> None:
  6499. """Assert that known remote refs corresponds to actual remote refs."""
  6500. local_ref_prefix = b"refs/heads"
  6501. remote_ref_prefix = b"refs/remotes/" + remote_name
  6502. locally_known_remote_refs = {
  6503. k[len(remote_ref_prefix) + 1 :]: v
  6504. for k, v in local_refs.items()
  6505. if k.startswith(remote_ref_prefix)
  6506. }
  6507. normalized_remote_refs = {
  6508. k[len(local_ref_prefix) + 1 :]: v
  6509. for k, v in remote_refs.items()
  6510. if k.startswith(local_ref_prefix)
  6511. }
  6512. if b"HEAD" in locally_known_remote_refs and b"HEAD" in remote_refs:
  6513. normalized_remote_refs[b"HEAD"] = remote_refs[b"HEAD"]
  6514. self.assertEqual(locally_known_remote_refs, normalized_remote_refs)
  6515. class RepackTests(PorcelainTestCase):
  6516. def test_empty(self) -> None:
  6517. porcelain.repack(self.repo)
  6518. def test_simple(self) -> None:
  6519. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6520. os.close(handle)
  6521. porcelain.add(repo=self.repo.path, paths=fullpath)
  6522. porcelain.repack(self.repo)
  6523. class LsTreeTests(PorcelainTestCase):
  6524. def test_empty(self) -> None:
  6525. porcelain.commit(
  6526. repo=self.repo.path,
  6527. message=b"test status",
  6528. author=b"author <email>",
  6529. committer=b"committer <email>",
  6530. )
  6531. f = StringIO()
  6532. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  6533. self.assertEqual(f.getvalue(), "")
  6534. def test_simple(self) -> None:
  6535. # Commit a dummy file then modify it
  6536. fullpath = os.path.join(self.repo.path, "foo")
  6537. with open(fullpath, "w") as f:
  6538. f.write("origstuff")
  6539. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6540. porcelain.commit(
  6541. repo=self.repo.path,
  6542. message=b"test status",
  6543. author=b"author <email>",
  6544. committer=b"committer <email>",
  6545. )
  6546. output = StringIO()
  6547. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  6548. self.assertEqual(
  6549. output.getvalue(),
  6550. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n",
  6551. )
  6552. def test_recursive(self) -> None:
  6553. # Create a directory then write a dummy file in it
  6554. dirpath = os.path.join(self.repo.path, "adir")
  6555. filepath = os.path.join(dirpath, "afile")
  6556. os.mkdir(dirpath)
  6557. with open(filepath, "w") as f:
  6558. f.write("origstuff")
  6559. porcelain.add(repo=self.repo.path, paths=[filepath])
  6560. porcelain.commit(
  6561. repo=self.repo.path,
  6562. message=b"test status",
  6563. author=b"author <email>",
  6564. committer=b"committer <email>",
  6565. )
  6566. output = StringIO()
  6567. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  6568. self.assertEqual(
  6569. output.getvalue(),
  6570. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n",
  6571. )
  6572. output2 = StringIO()
  6573. porcelain.ls_tree(self.repo, b"HEAD", outstream=output2, recursive=True)
  6574. self.assertEqual(
  6575. output2.getvalue(),
  6576. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n"
  6577. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir"
  6578. "/afile\n",
  6579. )
  6580. class LsRemoteTests(PorcelainTestCase):
  6581. def test_empty(self) -> None:
  6582. result = porcelain.ls_remote(self.repo.path)
  6583. self.assertEqual({}, result.refs)
  6584. self.assertEqual({}, result.symrefs)
  6585. def test_some(self) -> None:
  6586. cid = porcelain.commit(
  6587. repo=self.repo.path,
  6588. message=b"test status",
  6589. author=b"author <email>",
  6590. committer=b"committer <email>",
  6591. )
  6592. result = porcelain.ls_remote(self.repo.path)
  6593. self.assertEqual(
  6594. {b"refs/heads/master": cid, b"HEAD": cid},
  6595. result.refs,
  6596. )
  6597. # HEAD should be a symref to refs/heads/master
  6598. self.assertEqual({b"HEAD": b"refs/heads/master"}, result.symrefs)
  6599. class LsFilesTests(PorcelainTestCase):
  6600. def test_empty(self) -> None:
  6601. self.assertEqual([], list(porcelain.ls_files(self.repo)))
  6602. def test_simple(self) -> None:
  6603. # Commit a dummy file then modify it
  6604. fullpath = os.path.join(self.repo.path, "foo")
  6605. with open(fullpath, "w") as f:
  6606. f.write("origstuff")
  6607. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6608. self.assertEqual([b"foo"], list(porcelain.ls_files(self.repo)))
  6609. class RemoteAddTests(PorcelainTestCase):
  6610. def test_new(self) -> None:
  6611. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6612. c = self.repo.get_config()
  6613. self.assertEqual(
  6614. c.get((b"remote", b"jelmer"), b"url"),
  6615. b"git://jelmer.uk/code/dulwich",
  6616. )
  6617. def test_exists(self) -> None:
  6618. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6619. self.assertRaises(
  6620. porcelain.RemoteExists,
  6621. porcelain.remote_add,
  6622. self.repo,
  6623. "jelmer",
  6624. "git://jelmer.uk/code/dulwich",
  6625. )
  6626. class RemoteRemoveTests(PorcelainTestCase):
  6627. def test_remove(self) -> None:
  6628. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6629. c = self.repo.get_config()
  6630. self.assertEqual(
  6631. c.get((b"remote", b"jelmer"), b"url"),
  6632. b"git://jelmer.uk/code/dulwich",
  6633. )
  6634. porcelain.remote_remove(self.repo, "jelmer")
  6635. self.assertRaises(KeyError, porcelain.remote_remove, self.repo, "jelmer")
  6636. c = self.repo.get_config()
  6637. self.assertRaises(KeyError, c.get, (b"remote", b"jelmer"), b"url")
  6638. class CheckIgnoreTests(PorcelainTestCase):
  6639. def test_check_ignored(self) -> None:
  6640. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6641. f.write("foo")
  6642. foo_path = os.path.join(self.repo.path, "foo")
  6643. with open(foo_path, "w") as f:
  6644. f.write("BAR")
  6645. bar_path = os.path.join(self.repo.path, "bar")
  6646. with open(bar_path, "w") as f:
  6647. f.write("BAR")
  6648. self.assertEqual(["foo"], list(porcelain.check_ignore(self.repo, [foo_path])))
  6649. self.assertEqual([], list(porcelain.check_ignore(self.repo, [bar_path])))
  6650. def test_check_added_abs(self) -> None:
  6651. path = os.path.join(self.repo.path, "foo")
  6652. with open(path, "w") as f:
  6653. f.write("BAR")
  6654. self.repo.get_worktree().stage(["foo"])
  6655. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6656. f.write("foo\n")
  6657. self.assertEqual([], list(porcelain.check_ignore(self.repo, [path])))
  6658. self.assertEqual(
  6659. ["foo"],
  6660. list(porcelain.check_ignore(self.repo, [path], no_index=True)),
  6661. )
  6662. def test_check_added_rel(self) -> None:
  6663. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  6664. f.write("BAR")
  6665. self.repo.get_worktree().stage(["foo"])
  6666. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6667. f.write("foo\n")
  6668. cwd = os.getcwd()
  6669. self.addCleanup(os.chdir, cwd)
  6670. os.mkdir(os.path.join(self.repo.path, "bar"))
  6671. os.chdir(os.path.join(self.repo.path, "bar"))
  6672. self.assertEqual(list(porcelain.check_ignore(self.repo, ["../foo"])), [])
  6673. self.assertEqual(
  6674. ["../foo"],
  6675. list(porcelain.check_ignore(self.repo, ["../foo"], no_index=True)),
  6676. )
  6677. class UpdateHeadTests(PorcelainTestCase):
  6678. def test_set_to_branch(self) -> None:
  6679. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6680. self.repo.refs[b"refs/heads/blah"] = c1.id
  6681. porcelain.update_head(self.repo, "blah")
  6682. self.assertEqual(c1.id, self.repo.head())
  6683. self.assertEqual(b"ref: refs/heads/blah", self.repo.refs.read_ref(b"HEAD"))
  6684. def test_set_to_branch_detached(self) -> None:
  6685. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6686. self.repo.refs[b"refs/heads/blah"] = c1.id
  6687. porcelain.update_head(self.repo, "blah", detached=True)
  6688. self.assertEqual(c1.id, self.repo.head())
  6689. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  6690. def test_set_to_commit_detached(self) -> None:
  6691. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6692. self.repo.refs[b"refs/heads/blah"] = c1.id
  6693. porcelain.update_head(self.repo, c1.id, detached=True)
  6694. self.assertEqual(c1.id, self.repo.head())
  6695. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  6696. def test_set_new_branch(self) -> None:
  6697. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6698. self.repo.refs[b"refs/heads/blah"] = c1.id
  6699. porcelain.update_head(self.repo, "blah", new_branch="bar")
  6700. self.assertEqual(c1.id, self.repo.head())
  6701. self.assertEqual(b"ref: refs/heads/bar", self.repo.refs.read_ref(b"HEAD"))
  6702. class MailmapTests(PorcelainTestCase):
  6703. def test_no_mailmap(self) -> None:
  6704. self.assertEqual(
  6705. b"Jelmer Vernooij <jelmer@samba.org>",
  6706. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  6707. )
  6708. def test_mailmap_lookup(self) -> None:
  6709. with open(os.path.join(self.repo.path, ".mailmap"), "wb") as f:
  6710. f.write(
  6711. b"""\
  6712. Jelmer Vernooij <jelmer@debian.org>
  6713. """
  6714. )
  6715. self.assertEqual(
  6716. b"Jelmer Vernooij <jelmer@debian.org>",
  6717. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  6718. )
  6719. class FsckTests(PorcelainTestCase):
  6720. def test_none(self) -> None:
  6721. self.assertEqual([], list(porcelain.fsck(self.repo)))
  6722. def test_git_dir(self) -> None:
  6723. obj = Tree()
  6724. a = Blob()
  6725. a.data = b"foo"
  6726. obj.add(b".git", 0o100644, a.id)
  6727. self.repo.object_store.add_objects([(a, None), (obj, None)])
  6728. self.assertEqual(
  6729. [(obj.id, "invalid name .git")],
  6730. [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)],
  6731. )
  6732. class DescribeTests(PorcelainTestCase):
  6733. def test_no_commits(self) -> None:
  6734. self.assertRaises(KeyError, porcelain.describe, self.repo.path)
  6735. def test_single_commit(self) -> None:
  6736. fullpath = os.path.join(self.repo.path, "foo")
  6737. with open(fullpath, "w") as f:
  6738. f.write("BAR")
  6739. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6740. sha = porcelain.commit(
  6741. self.repo.path,
  6742. message=b"Some message",
  6743. author=b"Joe <joe@example.com>",
  6744. committer=b"Bob <bob@example.com>",
  6745. )
  6746. self.assertEqual(
  6747. "g{}".format(sha[:7].decode("ascii")),
  6748. porcelain.describe(self.repo.path),
  6749. )
  6750. def test_tag(self) -> None:
  6751. fullpath = os.path.join(self.repo.path, "foo")
  6752. with open(fullpath, "w") as f:
  6753. f.write("BAR")
  6754. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6755. porcelain.commit(
  6756. self.repo.path,
  6757. message=b"Some message",
  6758. author=b"Joe <joe@example.com>",
  6759. committer=b"Bob <bob@example.com>",
  6760. )
  6761. porcelain.tag_create(
  6762. self.repo.path,
  6763. b"tryme",
  6764. b"foo <foo@bar.com>",
  6765. b"bar",
  6766. annotated=True,
  6767. )
  6768. self.assertEqual("tryme", porcelain.describe(self.repo.path))
  6769. def test_tag_and_commit(self) -> None:
  6770. fullpath = os.path.join(self.repo.path, "foo")
  6771. with open(fullpath, "w") as f:
  6772. f.write("BAR")
  6773. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6774. porcelain.commit(
  6775. self.repo.path,
  6776. message=b"Some message",
  6777. author=b"Joe <joe@example.com>",
  6778. committer=b"Bob <bob@example.com>",
  6779. )
  6780. porcelain.tag_create(
  6781. self.repo.path,
  6782. b"tryme",
  6783. b"foo <foo@bar.com>",
  6784. b"bar",
  6785. annotated=True,
  6786. )
  6787. with open(fullpath, "w") as f:
  6788. f.write("BAR2")
  6789. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6790. sha = porcelain.commit(
  6791. self.repo.path,
  6792. message=b"Some message",
  6793. author=b"Joe <joe@example.com>",
  6794. committer=b"Bob <bob@example.com>",
  6795. )
  6796. self.assertEqual(
  6797. "tryme-1-g{}".format(sha[:7].decode("ascii")),
  6798. porcelain.describe(self.repo.path),
  6799. )
  6800. def test_tag_and_commit_full(self) -> None:
  6801. fullpath = os.path.join(self.repo.path, "foo")
  6802. with open(fullpath, "w") as f:
  6803. f.write("BAR")
  6804. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6805. porcelain.commit(
  6806. self.repo.path,
  6807. message=b"Some message",
  6808. author=b"Joe <joe@example.com>",
  6809. committer=b"Bob <bob@example.com>",
  6810. )
  6811. porcelain.tag_create(
  6812. self.repo.path,
  6813. b"tryme",
  6814. b"foo <foo@bar.com>",
  6815. b"bar",
  6816. annotated=True,
  6817. )
  6818. with open(fullpath, "w") as f:
  6819. f.write("BAR2")
  6820. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6821. sha = porcelain.commit(
  6822. self.repo.path,
  6823. message=b"Some message",
  6824. author=b"Joe <joe@example.com>",
  6825. committer=b"Bob <bob@example.com>",
  6826. )
  6827. self.assertEqual(
  6828. "tryme-1-g{}".format(sha.decode("ascii")),
  6829. porcelain.describe(self.repo.path, abbrev=40),
  6830. )
  6831. def test_untagged_commit_abbreviation(self) -> None:
  6832. _, _, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]])
  6833. self.repo.refs[b"HEAD"] = c3.id
  6834. brief_description, complete_description = (
  6835. porcelain.describe(self.repo),
  6836. porcelain.describe(self.repo, abbrev=40),
  6837. )
  6838. self.assertTrue(complete_description.startswith(brief_description))
  6839. self.assertEqual(
  6840. "g{}".format(c3.id.decode("ascii")),
  6841. complete_description,
  6842. )
  6843. def test_hash_length_dynamic(self) -> None:
  6844. """Test that hash length adjusts based on uniqueness."""
  6845. fullpath = os.path.join(self.repo.path, "foo")
  6846. with open(fullpath, "w") as f:
  6847. f.write("content")
  6848. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6849. sha = porcelain.commit(
  6850. self.repo.path,
  6851. message=b"commit",
  6852. author=b"Joe <joe@example.com>",
  6853. committer=b"Bob <bob@example.com>",
  6854. )
  6855. # When abbrev is None, it should use find_unique_abbrev
  6856. result = porcelain.describe(self.repo.path)
  6857. # Should start with 'g' and have at least 7 characters
  6858. self.assertTrue(result.startswith("g"))
  6859. self.assertGreaterEqual(len(result[1:]), 7)
  6860. # Should be a prefix of the full SHA
  6861. self.assertTrue(sha.decode("ascii").startswith(result[1:]))
  6862. class PathToTreeTests(PorcelainTestCase):
  6863. def setUp(self) -> None:
  6864. super().setUp()
  6865. self.fp = os.path.join(self.test_dir, "bar")
  6866. with open(self.fp, "w") as f:
  6867. f.write("something")
  6868. oldcwd = os.getcwd()
  6869. self.addCleanup(os.chdir, oldcwd)
  6870. os.chdir(self.test_dir)
  6871. def test_path_to_tree_path_base(self) -> None:
  6872. self.assertEqual(b"bar", porcelain.path_to_tree_path(self.test_dir, self.fp))
  6873. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  6874. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "bar"))
  6875. cwd = os.getcwd()
  6876. self.assertEqual(
  6877. b"bar", porcelain.path_to_tree_path(".", os.path.join(cwd, "bar"))
  6878. )
  6879. self.assertEqual(b"bar", porcelain.path_to_tree_path(cwd, "bar"))
  6880. def test_path_to_tree_path_syntax(self) -> None:
  6881. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  6882. def test_path_to_tree_path_error(self) -> None:
  6883. with self.assertRaises(ValueError):
  6884. with tempfile.TemporaryDirectory() as od:
  6885. porcelain.path_to_tree_path(od, self.fp)
  6886. def test_path_to_tree_path_rel(self) -> None:
  6887. cwd = os.getcwd()
  6888. self.addCleanup(os.chdir, cwd)
  6889. os.mkdir(os.path.join(self.repo.path, "foo"))
  6890. os.mkdir(os.path.join(self.repo.path, "foo/bar"))
  6891. os.chdir(os.path.join(self.repo.path, "foo/bar"))
  6892. with open("baz", "w") as f:
  6893. f.write("contents")
  6894. self.assertEqual(b"bar/baz", porcelain.path_to_tree_path("..", "baz"))
  6895. self.assertEqual(
  6896. b"bar/baz",
  6897. porcelain.path_to_tree_path(
  6898. os.path.join(os.getcwd(), ".."),
  6899. os.path.join(os.getcwd(), "baz"),
  6900. ),
  6901. )
  6902. self.assertEqual(
  6903. b"bar/baz",
  6904. porcelain.path_to_tree_path("..", os.path.join(os.getcwd(), "baz")),
  6905. )
  6906. self.assertEqual(
  6907. b"bar/baz",
  6908. porcelain.path_to_tree_path(os.path.join(os.getcwd(), ".."), "baz"),
  6909. )
  6910. class GetObjectByPathTests(PorcelainTestCase):
  6911. def test_simple(self) -> None:
  6912. fullpath = os.path.join(self.repo.path, "foo")
  6913. with open(fullpath, "w") as f:
  6914. f.write("BAR")
  6915. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6916. porcelain.commit(
  6917. self.repo.path,
  6918. message=b"Some message",
  6919. author=b"Joe <joe@example.com>",
  6920. committer=b"Bob <bob@example.com>",
  6921. )
  6922. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  6923. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  6924. def test_encoding(self) -> None:
  6925. fullpath = os.path.join(self.repo.path, "foo")
  6926. with open(fullpath, "w") as f:
  6927. f.write("BAR")
  6928. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6929. porcelain.commit(
  6930. self.repo.path,
  6931. message=b"Some message",
  6932. author=b"Joe <joe@example.com>",
  6933. committer=b"Bob <bob@example.com>",
  6934. encoding=b"utf-8",
  6935. )
  6936. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  6937. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  6938. def test_missing(self) -> None:
  6939. self.assertRaises(KeyError, porcelain.get_object_by_path, self.repo, "foo")
  6940. class WriteTreeTests(PorcelainTestCase):
  6941. def test_simple(self) -> None:
  6942. fullpath = os.path.join(self.repo.path, "foo")
  6943. with open(fullpath, "w") as f:
  6944. f.write("BAR")
  6945. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6946. self.assertEqual(
  6947. b"d2092c8a9f311f0311083bf8d177f2ca0ab5b241",
  6948. porcelain.write_tree(self.repo),
  6949. )
  6950. class ActiveBranchTests(PorcelainTestCase):
  6951. def test_simple(self) -> None:
  6952. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  6953. class BranchTrackingTests(PorcelainTestCase):
  6954. def test_get_branch_merge(self) -> None:
  6955. # Set up branch tracking configuration
  6956. config = self.repo.get_config()
  6957. config.set((b"branch", b"master"), b"remote", b"origin")
  6958. config.set((b"branch", b"master"), b"merge", b"refs/heads/main")
  6959. config.write_to_path()
  6960. # Test getting merge ref for current branch
  6961. merge_ref = porcelain.get_branch_merge(self.repo)
  6962. self.assertEqual(b"refs/heads/main", merge_ref)
  6963. # Test getting merge ref for specific branch
  6964. merge_ref = porcelain.get_branch_merge(self.repo, b"master")
  6965. self.assertEqual(b"refs/heads/main", merge_ref)
  6966. # Test branch without merge config
  6967. with self.assertRaises(KeyError):
  6968. porcelain.get_branch_merge(self.repo, b"nonexistent")
  6969. def test_set_branch_tracking(self) -> None:
  6970. # Create a new branch
  6971. _sha, _ = _commit_file_with_content(self.repo, "foo", "content\n")
  6972. porcelain.branch_create(self.repo, "feature")
  6973. # Set up tracking
  6974. porcelain.set_branch_tracking(
  6975. self.repo, b"feature", b"upstream", b"refs/heads/main"
  6976. )
  6977. # Verify configuration was written
  6978. config = self.repo.get_config()
  6979. self.assertEqual(b"upstream", config.get((b"branch", b"feature"), b"remote"))
  6980. self.assertEqual(
  6981. b"refs/heads/main", config.get((b"branch", b"feature"), b"merge")
  6982. )
  6983. class FindUniqueAbbrevTests(PorcelainTestCase):
  6984. def test_simple(self) -> None:
  6985. c1, _c2, c3 = build_commit_graph(
  6986. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  6987. )
  6988. self.repo.refs[b"HEAD"] = c3.id
  6989. self.assertEqual(
  6990. c1.id.decode("ascii")[:7],
  6991. porcelain.find_unique_abbrev(self.repo.object_store, c1.id),
  6992. )
  6993. class PackRefsTests(PorcelainTestCase):
  6994. def test_all(self) -> None:
  6995. c1, c2, c3 = build_commit_graph(
  6996. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  6997. )
  6998. self.repo.refs[b"HEAD"] = c3.id
  6999. self.repo.refs[b"refs/heads/master"] = c2.id
  7000. self.repo.refs[b"refs/tags/foo"] = c1.id
  7001. porcelain.pack_refs(self.repo, all=True)
  7002. self.assertEqual(
  7003. self.repo.refs.get_packed_refs(),
  7004. {
  7005. b"refs/heads/master": c2.id,
  7006. b"refs/tags/foo": c1.id,
  7007. },
  7008. )
  7009. def test_not_all(self) -> None:
  7010. c1, c2, c3 = build_commit_graph(
  7011. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  7012. )
  7013. self.repo.refs[b"HEAD"] = c3.id
  7014. self.repo.refs[b"refs/heads/master"] = c2.id
  7015. self.repo.refs[b"refs/tags/foo"] = c1.id
  7016. porcelain.pack_refs(self.repo)
  7017. self.assertEqual(
  7018. self.repo.refs.get_packed_refs(),
  7019. {
  7020. b"refs/tags/foo": c1.id,
  7021. },
  7022. )
  7023. class ServerTests(PorcelainTestCase):
  7024. @contextlib.contextmanager
  7025. def _serving(self):
  7026. with make_server("localhost", 0, self.app) as server:
  7027. thread = threading.Thread(target=server.serve_forever, daemon=True)
  7028. thread.start()
  7029. try:
  7030. yield f"http://localhost:{server.server_port}"
  7031. finally:
  7032. server.shutdown()
  7033. thread.join(10)
  7034. def setUp(self) -> None:
  7035. super().setUp()
  7036. self.served_repo_path = os.path.join(self.test_dir, "served_repo.git")
  7037. self.served_repo = Repo.init_bare(self.served_repo_path, mkdir=True)
  7038. self.addCleanup(self.served_repo.close)
  7039. backend = DictBackend({"/": self.served_repo})
  7040. self.app = make_wsgi_chain(backend)
  7041. def test_pull(self) -> None:
  7042. (c1,) = build_commit_graph(self.served_repo.object_store, [[1]])
  7043. self.served_repo.refs[b"refs/heads/master"] = c1.id
  7044. with self._serving() as url:
  7045. porcelain.pull(self.repo, url, "master")
  7046. def test_push(self) -> None:
  7047. (c1,) = build_commit_graph(self.repo.object_store, [[1]])
  7048. self.repo.refs[b"refs/heads/master"] = c1.id
  7049. with self._serving() as url:
  7050. porcelain.push(self.repo, url, "master")
  7051. class ForEachTests(PorcelainTestCase):
  7052. def setUp(self) -> None:
  7053. super().setUp()
  7054. c1, c2, c3, c4 = build_commit_graph(
  7055. self.repo.object_store, [[1], [2, 1], [3, 1, 2], [4]]
  7056. )
  7057. porcelain.tag_create(
  7058. self.repo.path,
  7059. b"v0.1",
  7060. objectish=c1.id,
  7061. annotated=True,
  7062. message=b"0.1",
  7063. )
  7064. porcelain.tag_create(
  7065. self.repo.path,
  7066. b"v1.0",
  7067. objectish=c2.id,
  7068. annotated=True,
  7069. message=b"1.0",
  7070. )
  7071. porcelain.tag_create(self.repo.path, b"simple-tag", objectish=c3.id)
  7072. porcelain.tag_create(
  7073. self.repo.path,
  7074. b"v1.1",
  7075. objectish=c4.id,
  7076. annotated=True,
  7077. message=b"1.1",
  7078. )
  7079. porcelain.branch_create(
  7080. self.repo.path, b"feat", objectish=c2.id.decode("ascii")
  7081. )
  7082. self.repo.refs[b"HEAD"] = c4.id
  7083. def test_for_each_ref(self) -> None:
  7084. refs = porcelain.for_each_ref(self.repo)
  7085. self.assertEqual(
  7086. [(object_type, tag) for _, object_type, tag in refs],
  7087. [
  7088. (b"commit", b"refs/heads/feat"),
  7089. (b"commit", b"refs/heads/master"),
  7090. (b"commit", b"refs/tags/simple-tag"),
  7091. (b"tag", b"refs/tags/v0.1"),
  7092. (b"tag", b"refs/tags/v1.0"),
  7093. (b"tag", b"refs/tags/v1.1"),
  7094. ],
  7095. )
  7096. def test_for_each_ref_pattern(self) -> None:
  7097. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v*")
  7098. self.assertEqual(
  7099. [(object_type, tag) for _, object_type, tag in versions],
  7100. [
  7101. (b"tag", b"refs/tags/v0.1"),
  7102. (b"tag", b"refs/tags/v1.0"),
  7103. (b"tag", b"refs/tags/v1.1"),
  7104. ],
  7105. )
  7106. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v1.?")
  7107. self.assertEqual(
  7108. [(object_type, tag) for _, object_type, tag in versions],
  7109. [
  7110. (b"tag", b"refs/tags/v1.0"),
  7111. (b"tag", b"refs/tags/v1.1"),
  7112. ],
  7113. )
  7114. class SparseCheckoutTests(PorcelainTestCase):
  7115. """Integration tests for Dulwich's sparse checkout feature."""
  7116. # NOTE: We do NOT override `setUp()` here because the parent class
  7117. # (PorcelainTestCase) already:
  7118. # 1) Creates self.test_dir = a unique temp dir
  7119. # 2) Creates a subdir named "repo"
  7120. # 3) Calls Repo.init() on that path
  7121. # Re-initializing again caused FileExistsError.
  7122. #
  7123. # Utility/Placeholder
  7124. #
  7125. def sparse_checkout(self, repo, patterns, force=False):
  7126. """Wrapper around the actual porcelain.sparse_checkout function
  7127. to handle any test-specific setup or logging.
  7128. """
  7129. return porcelain.sparse_checkout(repo, patterns, force=force)
  7130. def _write_file(self, rel_path, content):
  7131. """Helper to write a file in the repository working tree."""
  7132. abs_path = os.path.join(self.repo_path, rel_path)
  7133. os.makedirs(os.path.dirname(abs_path), exist_ok=True)
  7134. with open(abs_path, "w") as f:
  7135. f.write(content)
  7136. return abs_path
  7137. def _commit_file(self, rel_path, content):
  7138. """Helper to write, add, and commit a file."""
  7139. abs_path = self._write_file(rel_path, content)
  7140. add(self.repo_path, paths=[abs_path])
  7141. commit(self.repo_path, message=b"Added " + rel_path.encode("utf-8"))
  7142. def _list_wtree_files(self):
  7143. """Return a set of all files (not dirs) present
  7144. in the working tree, ignoring .git/.
  7145. """
  7146. found_files = set()
  7147. for root, dirs, files in os.walk(self.repo_path):
  7148. # Skip .git in the walk
  7149. if ".git" in dirs:
  7150. dirs.remove(".git")
  7151. for filename in files:
  7152. file_rel = os.path.relpath(os.path.join(root, filename), self.repo_path)
  7153. found_files.add(file_rel)
  7154. return found_files
  7155. def test_only_included_paths_appear_in_wtree(self):
  7156. """Only included paths remain in the working tree, excluded paths are removed.
  7157. Commits two files, "keep_me.txt" and "exclude_me.txt". Then applies a
  7158. sparse-checkout pattern containing only "keep_me.txt". Ensures that
  7159. the latter remains in the working tree, while "exclude_me.txt" is
  7160. removed. This verifies correct application of sparse-checkout patterns
  7161. to remove files not listed.
  7162. """
  7163. self._commit_file("keep_me.txt", "I'll stay\n")
  7164. self._commit_file("exclude_me.txt", "I'll be excluded\n")
  7165. patterns = ["keep_me.txt"]
  7166. self.sparse_checkout(self.repo, patterns)
  7167. actual_files = self._list_wtree_files()
  7168. expected_files = {"keep_me.txt"}
  7169. self.assertEqual(
  7170. expected_files,
  7171. actual_files,
  7172. f"Expected only {expected_files}, but found {actual_files}",
  7173. )
  7174. def test_previously_included_paths_become_excluded(self):
  7175. """Previously included files become excluded after pattern changes.
  7176. Verifies that files initially brought into the working tree (e.g.,
  7177. by including `data/`) can later be excluded by narrowing the
  7178. sparse-checkout pattern to just `data/included_1.txt`. Confirms that
  7179. the file `data/included_2.txt` remains in the index with
  7180. skip-worktree set (rather than being removed entirely), ensuring
  7181. data is not lost and Dulwich correctly updates the index flags.
  7182. """
  7183. self._commit_file("data/included_1.txt", "some content\n")
  7184. self._commit_file("data/included_2.txt", "other content\n")
  7185. initial_patterns = ["data/"]
  7186. self.sparse_checkout(self.repo, initial_patterns)
  7187. updated_patterns = ["data/included_1.txt"]
  7188. self.sparse_checkout(self.repo, updated_patterns)
  7189. actual_files = self._list_wtree_files()
  7190. expected_files = {os.path.join("data", "included_1.txt")}
  7191. self.assertEqual(expected_files, actual_files)
  7192. idx = self.repo.open_index()
  7193. self.assertIn(b"data/included_2.txt", idx)
  7194. entry = idx[b"data/included_2.txt"]
  7195. self.assertTrue(entry.skip_worktree)
  7196. def test_force_removes_local_changes_for_excluded_paths(self):
  7197. """Forced sparse checkout removes local modifications for newly excluded paths.
  7198. Verifies that specifying force=True allows destructive operations
  7199. which discard uncommitted changes. First, we commit "file1.txt" and
  7200. then modify it. Next, we apply a pattern that excludes the file,
  7201. using force=True. The local modifications (and the file) should
  7202. be removed, leaving the working tree empty.
  7203. """
  7204. self._commit_file("file1.txt", "original content\n")
  7205. file1_path = os.path.join(self.repo_path, "file1.txt")
  7206. with open(file1_path, "a") as f:
  7207. f.write("local changes!\n")
  7208. new_patterns = ["some_other_file.txt"]
  7209. self.sparse_checkout(self.repo, new_patterns, force=True)
  7210. actual_files = self._list_wtree_files()
  7211. self.assertEqual(
  7212. set(),
  7213. actual_files,
  7214. "Force-sparse-checkout did not remove file with local changes.",
  7215. )
  7216. def test_destructive_refuse_uncommitted_changes_without_force(self):
  7217. """Fail on uncommitted changes for newly excluded paths without force.
  7218. Ensures that a sparse checkout is blocked if it would remove local
  7219. modifications from the working tree. We commit 'config.yaml', then
  7220. modify it, and finally attempt to exclude it via new patterns without
  7221. using force=True. This should raise a CheckoutError rather than
  7222. discarding the local changes.
  7223. """
  7224. self._commit_file("config.yaml", "initial\n")
  7225. cfg_path = os.path.join(self.repo_path, "config.yaml")
  7226. with open(cfg_path, "a") as f:
  7227. f.write("local modifications\n")
  7228. exclude_patterns = ["docs/"]
  7229. with self.assertRaises(CheckoutError):
  7230. self.sparse_checkout(self.repo, exclude_patterns, force=False)
  7231. def test_fnmatch_gitignore_pattern_expansion(self):
  7232. """Reading/writing patterns align with gitignore/fnmatch expansions.
  7233. Ensures that `sparse_checkout` interprets wildcard patterns (like `*.py`)
  7234. in the same way Git's sparse-checkout would. Multiple files are committed
  7235. to `src/` (e.g. `foo.py`, `foo_test.py`, `foo_helper.py`) and to `docs/`.
  7236. Then the pattern `src/foo*.py` is applied, confirming that only the
  7237. matching Python files remain in the working tree while the Markdown file
  7238. under `docs/` is excluded.
  7239. Finally, verifies that the `.git/info/sparse-checkout` file contains the
  7240. specified wildcard pattern (`src/foo*.py`), ensuring correct round-trip
  7241. of user-supplied patterns.
  7242. """
  7243. self._commit_file("src/foo.py", "print('hello')\n")
  7244. self._commit_file("src/foo_test.py", "print('test')\n")
  7245. self._commit_file("docs/readme.md", "# docs\n")
  7246. self._commit_file("src/foo_helper.py", "print('helper')\n")
  7247. patterns = ["src/foo*.py"]
  7248. self.sparse_checkout(self.repo, patterns)
  7249. actual_files = self._list_wtree_files()
  7250. expected_files = {
  7251. os.path.join("src", "foo.py"),
  7252. os.path.join("src", "foo_test.py"),
  7253. os.path.join("src", "foo_helper.py"),
  7254. }
  7255. self.assertEqual(
  7256. expected_files,
  7257. actual_files,
  7258. "Wildcard pattern not matched as expected. Either too strict or too broad.",
  7259. )
  7260. sc_file = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7261. self.assertTrue(os.path.isfile(sc_file))
  7262. with open(sc_file) as f:
  7263. lines = f.read().strip().split()
  7264. self.assertIn("src/foo*.py", lines)
  7265. class ConeModeTests(PorcelainTestCase):
  7266. """Provide integration tests for Dulwich's cone mode sparse checkout.
  7267. This test suite verifies the expected behavior for:
  7268. * cone_mode_init
  7269. * cone_mode_set
  7270. * cone_mode_add
  7271. Although Dulwich does not yet implement cone mode, these tests are
  7272. prepared in advance to guide future development.
  7273. """
  7274. def setUp(self):
  7275. """Set up a fresh repository for each test.
  7276. This method creates a new empty repo_path and Repo object
  7277. as provided by the PorcelainTestCase base class.
  7278. """
  7279. super().setUp()
  7280. def _commit_file(self, rel_path, content=b"contents"):
  7281. """Add a file at the given relative path and commit it.
  7282. Creates necessary directories, writes the file content,
  7283. stages, and commits. The commit message and author/committer
  7284. are also provided.
  7285. """
  7286. full_path = os.path.join(self.repo_path, rel_path)
  7287. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  7288. with open(full_path, "wb") as f:
  7289. f.write(content)
  7290. porcelain.add(self.repo_path, paths=[full_path])
  7291. porcelain.commit(
  7292. self.repo_path,
  7293. message=b"Adding " + rel_path.encode("utf-8"),
  7294. author=b"Test Author <author@example.com>",
  7295. committer=b"Test Committer <committer@example.com>",
  7296. )
  7297. def _list_wtree_files(self):
  7298. """Return a set of all file paths relative to the repository root.
  7299. Walks the working tree, skipping the .git directory.
  7300. """
  7301. found_files = set()
  7302. for root, dirs, files in os.walk(self.repo_path):
  7303. if ".git" in dirs:
  7304. dirs.remove(".git")
  7305. for fn in files:
  7306. relp = os.path.relpath(os.path.join(root, fn), self.repo_path)
  7307. found_files.add(relp)
  7308. return found_files
  7309. def test_init_excludes_everything(self):
  7310. """Verify that cone_mode_init writes minimal patterns and empties the working tree.
  7311. Make some dummy files, commit them, then call cone_mode_init. Confirm
  7312. that the working tree is empty, the sparse-checkout file has the
  7313. minimal patterns (/*, !/*/), and the relevant config values are set.
  7314. """
  7315. self._commit_file("docs/readme.md", b"# doc\n")
  7316. self._commit_file("src/main.py", b"print('hello')\n")
  7317. porcelain.cone_mode_init(self.repo)
  7318. actual_files = self._list_wtree_files()
  7319. self.assertEqual(
  7320. set(),
  7321. actual_files,
  7322. "cone_mode_init did not exclude all files from the working tree.",
  7323. )
  7324. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7325. with open(sp_path) as f:
  7326. lines = [ln.strip() for ln in f if ln.strip()]
  7327. self.assertIn("/*", lines)
  7328. self.assertIn("!/*/", lines)
  7329. config = self.repo.get_config()
  7330. self.assertEqual(config.get((b"core",), b"sparseCheckout"), b"true")
  7331. self.assertEqual(config.get((b"core",), b"sparseCheckoutCone"), b"true")
  7332. def test_set_specific_dirs(self):
  7333. """Verify that cone_mode_set overwrites the included directories to only the specified ones.
  7334. Initializes cone mode, commits some files, then calls cone_mode_set with
  7335. a list of directories. Expects that only those directories remain in the
  7336. working tree.
  7337. """
  7338. porcelain.cone_mode_init(self.repo)
  7339. self._commit_file("docs/readme.md", b"# doc\n")
  7340. self._commit_file("src/main.py", b"print('hello')\n")
  7341. self._commit_file("tests/test_foo.py", b"# tests\n")
  7342. # Everything is still excluded initially by init.
  7343. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  7344. actual_files = self._list_wtree_files()
  7345. expected_files = {
  7346. os.path.join("docs", "readme.md"),
  7347. os.path.join("src", "main.py"),
  7348. }
  7349. self.assertEqual(
  7350. expected_files,
  7351. actual_files,
  7352. "Did not see only the 'docs/' and 'src/' dirs in the working tree.",
  7353. )
  7354. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7355. with open(sp_path) as f:
  7356. lines = [ln.strip() for ln in f if ln.strip()]
  7357. # For standard cone mode, we'd expect lines like:
  7358. # /* (include top-level files)
  7359. # !/*/ (exclude subdirectories)
  7360. # !/docs/ (re-include docs)
  7361. # !/src/ (re-include src)
  7362. # Instead of the wildcard-based lines the old test used.
  7363. self.assertIn("/*", lines)
  7364. self.assertIn("!/*/", lines)
  7365. self.assertIn("/docs/", lines)
  7366. self.assertIn("/src/", lines)
  7367. self.assertNotIn("/tests/", lines)
  7368. def test_set_overwrites_old_dirs(self):
  7369. """Ensure that calling cone_mode_set again overwrites old includes.
  7370. Initializes cone mode, includes two directories, then calls
  7371. cone_mode_set again with a different directory to confirm the
  7372. new set of includes replaces the old.
  7373. """
  7374. porcelain.cone_mode_init(self.repo)
  7375. self._commit_file("docs/readme.md")
  7376. self._commit_file("src/main.py")
  7377. self._commit_file("tests/test_bar.py")
  7378. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  7379. self.assertEqual(
  7380. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  7381. self._list_wtree_files(),
  7382. )
  7383. # Overwrite includes, now only 'tests'
  7384. porcelain.cone_mode_set(self.repo, dirs=["tests"], force=True)
  7385. actual_files = self._list_wtree_files()
  7386. expected_files = {os.path.join("tests", "test_bar.py")}
  7387. self.assertEqual(expected_files, actual_files)
  7388. def test_force_removal_of_local_mods(self):
  7389. """Confirm that force=True removes local changes in excluded paths.
  7390. cone_mode_init and cone_mode_set are called, a file is locally modified,
  7391. and then cone_mode_set is called again with force=True to exclude that path.
  7392. The excluded file should be removed with no CheckoutError.
  7393. """
  7394. porcelain.cone_mode_init(self.repo)
  7395. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  7396. self._commit_file("docs/readme.md", b"Docs stuff\n")
  7397. self._commit_file("src/main.py", b"print('hello')\n")
  7398. # Modify src/main.py
  7399. with open(os.path.join(self.repo_path, "src/main.py"), "ab") as f:
  7400. f.write(b"extra line\n")
  7401. # Exclude src/ with force=True
  7402. porcelain.cone_mode_set(self.repo, dirs=["docs"], force=True)
  7403. actual_files = self._list_wtree_files()
  7404. expected_files = {os.path.join("docs", "readme.md")}
  7405. self.assertEqual(expected_files, actual_files)
  7406. def test_add_and_merge_dirs(self):
  7407. """Verify that cone_mode_add merges new directories instead of overwriting them.
  7408. After initializing cone mode and including a single directory, call
  7409. cone_mode_add with a new directory. Confirm that both directories
  7410. remain included. Repeat for an additional directory to ensure it
  7411. is merged, not overwritten.
  7412. """
  7413. porcelain.cone_mode_init(self.repo)
  7414. self._commit_file("docs/readme.md", b"# doc\n")
  7415. self._commit_file("src/main.py", b"print('hello')\n")
  7416. self._commit_file("tests/test_bar.py", b"# tests\n")
  7417. # Include "docs" only
  7418. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  7419. self.assertEqual({os.path.join("docs", "readme.md")}, self._list_wtree_files())
  7420. # Add "src"
  7421. porcelain.cone_mode_add(self.repo, dirs=["src"])
  7422. actual_files = self._list_wtree_files()
  7423. self.assertEqual(
  7424. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  7425. actual_files,
  7426. )
  7427. # Add "tests" as well
  7428. porcelain.cone_mode_add(self.repo, dirs=["tests"])
  7429. actual_files = self._list_wtree_files()
  7430. expected_files = {
  7431. os.path.join("docs", "readme.md"),
  7432. os.path.join("src", "main.py"),
  7433. os.path.join("tests", "test_bar.py"),
  7434. }
  7435. self.assertEqual(expected_files, actual_files)
  7436. # Check .git/info/sparse-checkout
  7437. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7438. with open(sp_path) as f:
  7439. lines = [ln.strip() for ln in f if ln.strip()]
  7440. # Standard cone mode lines:
  7441. # "/*" -> include top-level
  7442. # "!/*/" -> exclude subdirectories
  7443. # "!/docs/", "!/src/", "!/tests/" -> re-include the directories we added
  7444. self.assertIn("/*", lines)
  7445. self.assertIn("!/*/", lines)
  7446. self.assertIn("/docs/", lines)
  7447. self.assertIn("/src/", lines)
  7448. self.assertIn("/tests/", lines)
  7449. class UnpackObjectsTest(PorcelainTestCase):
  7450. def test_unpack_objects(self):
  7451. """Test unpacking objects from a pack file."""
  7452. # Create a test repository with some objects
  7453. b1 = Blob()
  7454. b1.data = b"test content 1"
  7455. b2 = Blob()
  7456. b2.data = b"test content 2"
  7457. # Add objects to the repo
  7458. self.repo.object_store.add_object(b1)
  7459. self.repo.object_store.add_object(b2)
  7460. # Create a pack file with these objects
  7461. pack_path = os.path.join(self.test_dir, "test_pack")
  7462. with (
  7463. open(pack_path + ".pack", "wb") as pack_f,
  7464. open(pack_path + ".idx", "wb") as idx_f,
  7465. ):
  7466. porcelain.pack_objects(
  7467. self.repo,
  7468. [b1.id, b2.id],
  7469. pack_f,
  7470. idx_f,
  7471. )
  7472. # Create a new repository to unpack into
  7473. target_repo_path = os.path.join(self.test_dir, "target_repo")
  7474. target_repo = Repo.init(target_repo_path, mkdir=True)
  7475. self.addCleanup(target_repo.close)
  7476. # Unpack the objects
  7477. count = porcelain.unpack_objects(pack_path + ".pack", target_repo_path)
  7478. # Verify the objects were unpacked
  7479. self.assertEqual(2, count)
  7480. self.assertIn(b1.id, target_repo.object_store)
  7481. self.assertIn(b2.id, target_repo.object_store)
  7482. # Verify the content is correct
  7483. unpacked_b1 = target_repo.object_store[b1.id]
  7484. unpacked_b2 = target_repo.object_store[b2.id]
  7485. self.assertEqual(b1.data, unpacked_b1.data)
  7486. self.assertEqual(b2.data, unpacked_b2.data)
  7487. class CountObjectsTests(PorcelainTestCase):
  7488. def test_count_objects_empty_repo(self):
  7489. """Test counting objects in an empty repository."""
  7490. stats = porcelain.count_objects(self.repo)
  7491. self.assertEqual(0, stats.count)
  7492. self.assertEqual(0, stats.size)
  7493. def test_count_objects_verbose_empty_repo(self):
  7494. """Test verbose counting in an empty repository."""
  7495. stats = porcelain.count_objects(self.repo, verbose=True)
  7496. self.assertEqual(0, stats.count)
  7497. self.assertEqual(0, stats.size)
  7498. self.assertEqual(0, stats.in_pack)
  7499. self.assertEqual(0, stats.packs)
  7500. self.assertEqual(0, stats.size_pack)
  7501. def test_count_objects_with_loose_objects(self):
  7502. """Test counting loose objects."""
  7503. # Create some loose objects
  7504. blob1 = make_object(Blob, data=b"data1")
  7505. blob2 = make_object(Blob, data=b"data2")
  7506. self.repo.object_store.add_object(blob1)
  7507. self.repo.object_store.add_object(blob2)
  7508. stats = porcelain.count_objects(self.repo)
  7509. self.assertEqual(2, stats.count)
  7510. self.assertGreater(stats.size, 0)
  7511. def test_count_objects_verbose_with_objects(self):
  7512. """Test verbose counting with both loose and packed objects."""
  7513. # Add some loose objects
  7514. for i in range(3):
  7515. blob = make_object(Blob, data=f"data{i}".encode())
  7516. self.repo.object_store.add_object(blob)
  7517. # Create a simple commit to have some objects in a pack
  7518. tree = Tree()
  7519. c1 = make_commit(tree=tree.id, message=b"Test commit")
  7520. self.repo.object_store.add_objects([(tree, None), (c1, None)])
  7521. self.repo.refs[b"HEAD"] = c1.id
  7522. # Repack to create a pack file
  7523. porcelain.repack(self.repo)
  7524. stats = porcelain.count_objects(self.repo, verbose=True)
  7525. # After repacking, loose objects might be cleaned up
  7526. self.assertIsInstance(stats.count, int)
  7527. self.assertIsInstance(stats.size, int)
  7528. self.assertGreater(stats.in_pack, 0) # Should have packed objects
  7529. self.assertGreater(stats.packs, 0) # Should have at least one pack
  7530. self.assertGreater(stats.size_pack, 0) # Pack should have size
  7531. # Verify it's the correct dataclass type
  7532. self.assertIsInstance(stats, CountObjectsResult)
  7533. class PruneTests(PorcelainTestCase):
  7534. def test_prune_removes_old_tempfiles(self):
  7535. """Test that prune removes old temporary files."""
  7536. # Create an old temporary file in the objects directory
  7537. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7538. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_test")
  7539. with open(tmp_pack_path, "wb") as f:
  7540. f.write(b"old temporary data")
  7541. # Make it old
  7542. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  7543. os.utime(tmp_pack_path, (old_time, old_time))
  7544. # Run prune
  7545. porcelain.prune(self.repo.path)
  7546. # Verify the file was removed
  7547. self.assertFalse(os.path.exists(tmp_pack_path))
  7548. def test_prune_keeps_recent_tempfiles(self):
  7549. """Test that prune keeps recent temporary files."""
  7550. # Create a recent temporary file
  7551. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7552. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_recent")
  7553. with open(tmp_pack_path, "wb") as f:
  7554. f.write(b"recent temporary data")
  7555. self.addCleanup(os.remove, tmp_pack_path)
  7556. # Run prune
  7557. porcelain.prune(self.repo.path)
  7558. # Verify the file was NOT removed
  7559. self.assertTrue(os.path.exists(tmp_pack_path))
  7560. def test_prune_with_custom_grace_period(self):
  7561. """Test prune with custom grace period."""
  7562. # Create a 1-hour-old temporary file
  7563. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7564. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_1hour")
  7565. with open(tmp_pack_path, "wb") as f:
  7566. f.write(b"1 hour old data")
  7567. # Make it 1 hour old
  7568. old_time = time.time() - 3600
  7569. os.utime(tmp_pack_path, (old_time, old_time))
  7570. # Prune with 30-minute grace period should remove it
  7571. porcelain.prune(self.repo.path, grace_period=1800)
  7572. # Verify the file was removed
  7573. self.assertFalse(os.path.exists(tmp_pack_path))
  7574. def test_prune_dry_run(self):
  7575. """Test prune in dry-run mode."""
  7576. # Create an old temporary file
  7577. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7578. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_dryrun")
  7579. with open(tmp_pack_path, "wb") as f:
  7580. f.write(b"old temporary data")
  7581. self.addCleanup(os.remove, tmp_pack_path)
  7582. # Make it old
  7583. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  7584. os.utime(tmp_pack_path, (old_time, old_time))
  7585. # Run prune in dry-run mode
  7586. porcelain.prune(self.repo.path, dry_run=True)
  7587. # Verify the file was NOT removed (dry run)
  7588. self.assertTrue(os.path.exists(tmp_pack_path))
  7589. class FilterBranchTests(PorcelainTestCase):
  7590. def setUp(self):
  7591. super().setUp()
  7592. # Create initial commits with different authors
  7593. from dulwich.objects import Commit, Tree
  7594. # Create actual tree and blob objects
  7595. tree = Tree()
  7596. self.repo.object_store.add_object(tree)
  7597. c1 = Commit()
  7598. c1.tree = tree.id
  7599. c1.parents = []
  7600. c1.author = b"Old Author <old@example.com>"
  7601. c1.author_time = 1000
  7602. c1.author_timezone = 0
  7603. c1.committer = b"Old Committer <old@example.com>"
  7604. c1.commit_time = 1000
  7605. c1.commit_timezone = 0
  7606. c1.message = b"Initial commit"
  7607. self.repo.object_store.add_object(c1)
  7608. c2 = Commit()
  7609. c2.tree = tree.id
  7610. c2.parents = [c1.id]
  7611. c2.author = b"Another Author <another@example.com>"
  7612. c2.author_time = 2000
  7613. c2.author_timezone = 0
  7614. c2.committer = b"Another Committer <another@example.com>"
  7615. c2.commit_time = 2000
  7616. c2.commit_timezone = 0
  7617. c2.message = b"Second commit\n\nWith body"
  7618. self.repo.object_store.add_object(c2)
  7619. c3 = Commit()
  7620. c3.tree = tree.id
  7621. c3.parents = [c2.id]
  7622. c3.author = b"Third Author <third@example.com>"
  7623. c3.author_time = 3000
  7624. c3.author_timezone = 0
  7625. c3.committer = b"Third Committer <third@example.com>"
  7626. c3.commit_time = 3000
  7627. c3.commit_timezone = 0
  7628. c3.message = b"Third commit"
  7629. self.repo.object_store.add_object(c3)
  7630. self.repo.refs[b"refs/heads/master"] = c3.id
  7631. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  7632. # Store IDs for test assertions
  7633. self.c1_id = c1.id
  7634. self.c2_id = c2.id
  7635. self.c3_id = c3.id
  7636. def test_filter_branch_author(self):
  7637. """Test filtering branch with author changes."""
  7638. def filter_author(author):
  7639. # Change all authors to "New Author"
  7640. return b"New Author <new@example.com>"
  7641. result = porcelain.filter_branch(
  7642. self.repo_path, "master", filter_author=filter_author
  7643. )
  7644. # Check that we have mappings for all commits
  7645. self.assertEqual(len(result), 3)
  7646. # Verify the branch ref was updated
  7647. new_head = self.repo.refs[b"refs/heads/master"]
  7648. self.assertNotEqual(new_head, self.c3_id)
  7649. # Verify the original ref was saved
  7650. original_ref = self.repo.refs[b"refs/original/refs/heads/master"]
  7651. self.assertEqual(original_ref, self.c3_id)
  7652. # Check that authors were updated
  7653. new_commit = self.repo[new_head]
  7654. self.assertEqual(new_commit.author, b"New Author <new@example.com>")
  7655. # Check parent chain
  7656. parent = self.repo[new_commit.parents[0]]
  7657. self.assertEqual(parent.author, b"New Author <new@example.com>")
  7658. def test_filter_branch_message(self):
  7659. """Test filtering branch with message changes."""
  7660. def filter_message(message):
  7661. # Add prefix to all messages
  7662. return b"[FILTERED] " + message
  7663. porcelain.filter_branch(self.repo_path, "master", filter_message=filter_message)
  7664. # Verify messages were updated
  7665. new_head = self.repo.refs[b"refs/heads/master"]
  7666. new_commit = self.repo[new_head]
  7667. self.assertTrue(new_commit.message.startswith(b"[FILTERED] "))
  7668. def test_filter_branch_custom_filter(self):
  7669. """Test filtering branch with custom filter function."""
  7670. def custom_filter(commit):
  7671. # Change both author and message
  7672. return {
  7673. "author": b"Custom Author <custom@example.com>",
  7674. "message": b"Custom: " + commit.message,
  7675. }
  7676. porcelain.filter_branch(self.repo_path, "master", filter_fn=custom_filter)
  7677. # Verify custom filter was applied
  7678. new_head = self.repo.refs[b"refs/heads/master"]
  7679. new_commit = self.repo[new_head]
  7680. self.assertEqual(new_commit.author, b"Custom Author <custom@example.com>")
  7681. self.assertTrue(new_commit.message.startswith(b"Custom: "))
  7682. def test_filter_branch_no_changes(self):
  7683. """Test filtering branch with no changes."""
  7684. result = porcelain.filter_branch(self.repo_path, "master")
  7685. # All commits should map to themselves
  7686. for old_sha, new_sha in result.items():
  7687. self.assertEqual(old_sha, new_sha)
  7688. # HEAD should be unchanged
  7689. self.assertEqual(self.repo.refs[b"refs/heads/master"], self.c3_id)
  7690. def test_filter_branch_force(self):
  7691. """Test force filtering a previously filtered branch."""
  7692. # First filter
  7693. porcelain.filter_branch(
  7694. self.repo_path, "master", filter_message=lambda m: b"First: " + m
  7695. )
  7696. # Try again without force - should fail
  7697. with self.assertRaises(porcelain.Error):
  7698. porcelain.filter_branch(
  7699. self.repo_path, "master", filter_message=lambda m: b"Second: " + m
  7700. )
  7701. # Try again with force - should succeed
  7702. porcelain.filter_branch(
  7703. self.repo_path,
  7704. "master",
  7705. filter_message=lambda m: b"Second: " + m,
  7706. force=True,
  7707. )
  7708. # Verify second filter was applied
  7709. new_head = self.repo.refs[b"refs/heads/master"]
  7710. new_commit = self.repo[new_head]
  7711. self.assertTrue(new_commit.message.startswith(b"Second: First: "))
  7712. class StashTests(PorcelainTestCase):
  7713. def setUp(self) -> None:
  7714. super().setUp()
  7715. # Create initial commit
  7716. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  7717. f.write(b"initial content")
  7718. porcelain.add(repo=self.repo.path, paths=["initial.txt"])
  7719. porcelain.commit(
  7720. repo=self.repo.path,
  7721. message=b"Initial commit",
  7722. author=b"Test Author <test@example.com>",
  7723. committer=b"Test Committer <test@example.com>",
  7724. )
  7725. def test_stash_push_and_pop(self) -> None:
  7726. # Create a new file and stage it
  7727. new_file = os.path.join(self.repo.path, "new.txt")
  7728. with open(new_file, "wb") as f:
  7729. f.write(b"new file content")
  7730. porcelain.add(repo=self.repo.path, paths=["new.txt"])
  7731. # Modify existing file
  7732. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  7733. f.write(b"modified content")
  7734. # Push to stash
  7735. porcelain.stash_push(self.repo.path)
  7736. # Verify files are reset
  7737. self.assertFalse(os.path.exists(new_file))
  7738. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  7739. self.assertEqual(b"initial content", f.read())
  7740. # Pop the stash
  7741. porcelain.stash_pop(self.repo.path)
  7742. # Verify files are restored
  7743. self.assertTrue(os.path.exists(new_file))
  7744. with open(new_file, "rb") as f:
  7745. self.assertEqual(b"new file content", f.read())
  7746. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  7747. self.assertEqual(b"modified content", f.read())
  7748. # Verify new file is in the index
  7749. from dulwich.index import Index
  7750. index = Index(os.path.join(self.repo.path, ".git", "index"))
  7751. self.assertIn(b"new.txt", index)
  7752. def test_stash_list(self) -> None:
  7753. # Initially no stashes
  7754. stashes = list(porcelain.stash_list(self.repo.path))
  7755. self.assertEqual(0, len(stashes))
  7756. # Create a file and stash it
  7757. test_file = os.path.join(self.repo.path, "test.txt")
  7758. with open(test_file, "wb") as f:
  7759. f.write(b"test content")
  7760. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  7761. # Push first stash
  7762. porcelain.stash_push(self.repo.path)
  7763. # Create another file and stash it
  7764. test_file2 = os.path.join(self.repo.path, "test2.txt")
  7765. with open(test_file2, "wb") as f:
  7766. f.write(b"test content 2")
  7767. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  7768. # Push second stash
  7769. porcelain.stash_push(self.repo.path)
  7770. # Check stash list
  7771. stashes = list(porcelain.stash_list(self.repo.path))
  7772. self.assertEqual(2, len(stashes))
  7773. # Stashes are returned in order (most recent first)
  7774. self.assertEqual(0, stashes[0][0])
  7775. self.assertEqual(1, stashes[1][0])
  7776. def test_stash_drop(self) -> None:
  7777. # Create and stash some changes
  7778. test_file = os.path.join(self.repo.path, "test.txt")
  7779. with open(test_file, "wb") as f:
  7780. f.write(b"test content")
  7781. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  7782. porcelain.stash_push(self.repo.path)
  7783. # Create another stash
  7784. test_file2 = os.path.join(self.repo.path, "test2.txt")
  7785. with open(test_file2, "wb") as f:
  7786. f.write(b"test content 2")
  7787. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  7788. porcelain.stash_push(self.repo.path)
  7789. # Verify we have 2 stashes
  7790. stashes = list(porcelain.stash_list(self.repo.path))
  7791. self.assertEqual(2, len(stashes))
  7792. # Drop the first stash (index 0)
  7793. porcelain.stash_drop(self.repo.path, 0)
  7794. # Verify we have 1 stash left
  7795. stashes = list(porcelain.stash_list(self.repo.path))
  7796. self.assertEqual(1, len(stashes))
  7797. # The remaining stash should be the one we created first
  7798. # Pop it and verify it's the first file
  7799. porcelain.stash_pop(self.repo.path)
  7800. self.assertTrue(os.path.exists(test_file))
  7801. self.assertFalse(os.path.exists(test_file2))
  7802. def test_stash_pop_empty(self) -> None:
  7803. # Attempting to pop from empty stash should raise an error
  7804. with self.assertRaises(IndexError):
  7805. porcelain.stash_pop(self.repo.path)
  7806. def test_stash_with_untracked_files(self) -> None:
  7807. # Create an untracked file
  7808. untracked_file = os.path.join(self.repo.path, "untracked.txt")
  7809. with open(untracked_file, "wb") as f:
  7810. f.write(b"untracked content")
  7811. # Create a tracked change
  7812. tracked_file = os.path.join(self.repo.path, "tracked.txt")
  7813. with open(tracked_file, "wb") as f:
  7814. f.write(b"tracked content")
  7815. porcelain.add(repo=self.repo.path, paths=["tracked.txt"])
  7816. # Stash (by default, untracked files are not included)
  7817. porcelain.stash_push(self.repo.path)
  7818. # Untracked file should still exist
  7819. self.assertTrue(os.path.exists(untracked_file))
  7820. # Tracked file should be gone
  7821. self.assertFalse(os.path.exists(tracked_file))
  7822. # Pop the stash
  7823. porcelain.stash_pop(self.repo.path)
  7824. # Tracked file should be restored
  7825. self.assertTrue(os.path.exists(tracked_file))
  7826. class BisectTests(PorcelainTestCase):
  7827. """Tests for bisect porcelain functions."""
  7828. def test_bisect_start(self):
  7829. """Test starting a bisect session."""
  7830. # Create some commits
  7831. _c1, _c2, c3 = build_commit_graph(
  7832. self.repo.object_store,
  7833. [[1], [2, 1], [3, 2]],
  7834. attrs={
  7835. 1: {"message": b"initial"},
  7836. 2: {"message": b"second"},
  7837. 3: {"message": b"third"},
  7838. },
  7839. )
  7840. self.repo.refs[b"refs/heads/master"] = c3.id
  7841. self.repo.refs[b"HEAD"] = c3.id
  7842. # Start bisect
  7843. porcelain.bisect_start(self.repo_path)
  7844. # Check that bisect state files exist
  7845. self.assertTrue(
  7846. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  7847. )
  7848. self.assertTrue(
  7849. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_TERMS"))
  7850. )
  7851. self.assertTrue(
  7852. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_NAMES"))
  7853. )
  7854. self.assertTrue(
  7855. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_LOG"))
  7856. )
  7857. def test_bisect_workflow(self):
  7858. """Test a complete bisect workflow."""
  7859. # Create some commits
  7860. c1, c2, c3, c4 = build_commit_graph(
  7861. self.repo.object_store,
  7862. [[1], [2, 1], [3, 2], [4, 3]],
  7863. attrs={
  7864. 1: {"message": b"good commit 1"},
  7865. 2: {"message": b"good commit 2"},
  7866. 3: {"message": b"bad commit"},
  7867. 4: {"message": b"bad commit 2"},
  7868. },
  7869. )
  7870. self.repo.refs[b"refs/heads/master"] = c4.id
  7871. self.repo.refs[b"HEAD"] = c4.id
  7872. # Start bisect with bad and good
  7873. next_sha = porcelain.bisect_start(self.repo_path, bad=c4.id, good=c1.id)
  7874. # Should return the middle commit
  7875. self.assertIsNotNone(next_sha)
  7876. self.assertIn(next_sha, [c2.id, c3.id])
  7877. # Mark the middle commit as good or bad
  7878. if next_sha == c2.id:
  7879. # c2 is good, next should be c3
  7880. next_sha = porcelain.bisect_good(self.repo_path)
  7881. self.assertEqual(next_sha, c3.id)
  7882. # Mark c3 as bad - bisect complete
  7883. next_sha = porcelain.bisect_bad(self.repo_path)
  7884. self.assertIsNone(next_sha)
  7885. else:
  7886. # c3 is bad, next should be c2
  7887. next_sha = porcelain.bisect_bad(self.repo_path)
  7888. self.assertEqual(next_sha, c2.id)
  7889. # Mark c2 as good - bisect complete
  7890. next_sha = porcelain.bisect_good(self.repo_path)
  7891. self.assertIsNone(next_sha)
  7892. def test_bisect_log(self):
  7893. """Test getting bisect log."""
  7894. # Create some commits
  7895. c1, _c2, c3 = build_commit_graph(
  7896. self.repo.object_store,
  7897. [[1], [2, 1], [3, 2]],
  7898. attrs={
  7899. 1: {"message": b"initial"},
  7900. 2: {"message": b"second"},
  7901. 3: {"message": b"third"},
  7902. },
  7903. )
  7904. self.repo.refs[b"refs/heads/master"] = c3.id
  7905. self.repo.refs[b"HEAD"] = c3.id
  7906. # Start bisect and mark commits
  7907. porcelain.bisect_start(self.repo_path)
  7908. porcelain.bisect_bad(self.repo_path, c3.id)
  7909. porcelain.bisect_good(self.repo_path, c1.id)
  7910. # Get log
  7911. log = porcelain.bisect_log(self.repo_path)
  7912. self.assertIn("git bisect start", log)
  7913. self.assertIn("git bisect bad", log)
  7914. self.assertIn("git bisect good", log)
  7915. def test_bisect_reset(self):
  7916. """Test resetting bisect state."""
  7917. # Create some commits
  7918. c1, _c2, c3 = build_commit_graph(
  7919. self.repo.object_store,
  7920. [[1], [2, 1], [3, 2]],
  7921. attrs={
  7922. 1: {"message": b"initial"},
  7923. 2: {"message": b"second"},
  7924. 3: {"message": b"third"},
  7925. },
  7926. )
  7927. self.repo.refs[b"refs/heads/master"] = c3.id
  7928. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  7929. # Start bisect
  7930. porcelain.bisect_start(self.repo_path)
  7931. porcelain.bisect_bad(self.repo_path)
  7932. porcelain.bisect_good(self.repo_path, c1.id)
  7933. # Reset
  7934. porcelain.bisect_reset(self.repo_path)
  7935. # Check that bisect state files are removed
  7936. self.assertFalse(
  7937. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  7938. )
  7939. self.assertFalse(
  7940. os.path.exists(os.path.join(self.repo.controldir(), "refs", "bisect"))
  7941. )
  7942. # HEAD should be back to being a symbolic ref to master
  7943. head_target, _ = self.repo.refs.follow(b"HEAD")
  7944. self.assertEqual(head_target[-1], b"refs/heads/master")
  7945. def test_bisect_skip(self):
  7946. """Test skipping commits during bisect."""
  7947. # Create some commits
  7948. c1, c2, _c3, _c4, c5 = build_commit_graph(
  7949. self.repo.object_store,
  7950. [[1], [2, 1], [3, 2], [4, 3], [5, 4]],
  7951. attrs={
  7952. 1: {"message": b"good"},
  7953. 2: {"message": b"skip this"},
  7954. 3: {"message": b"bad"},
  7955. 4: {"message": b"bad"},
  7956. 5: {"message": b"bad"},
  7957. },
  7958. )
  7959. self.repo.refs[b"refs/heads/master"] = c5.id
  7960. self.repo.refs[b"HEAD"] = c5.id
  7961. # Start bisect
  7962. porcelain.bisect_start(self.repo_path, bad=c5.id, good=c1.id)
  7963. # Skip c2 if it's selected
  7964. next_sha = porcelain.bisect_skip(self.repo_path, [c2.id])
  7965. self.assertIsNotNone(next_sha)
  7966. class ReflogTest(PorcelainTestCase):
  7967. def test_reflog_head(self):
  7968. """Test reading HEAD reflog."""
  7969. # Create a commit
  7970. blob = Blob.from_string(b"test content")
  7971. self.repo.object_store.add_object(blob)
  7972. tree = Tree()
  7973. tree.add(b"test", 0o100644, blob.id)
  7974. self.repo.object_store.add_object(tree)
  7975. commit = Commit()
  7976. commit.tree = tree.id
  7977. commit.author = b"Test Author <test@example.com>"
  7978. commit.committer = b"Test Author <test@example.com>"
  7979. commit.commit_time = 1234567890
  7980. commit.commit_timezone = 0
  7981. commit.author_time = 1234567890
  7982. commit.author_timezone = 0
  7983. commit.message = b"Initial commit"
  7984. self.repo.object_store.add_object(commit)
  7985. # Write a reflog entry
  7986. self.repo._write_reflog(
  7987. b"HEAD",
  7988. ZERO_SHA,
  7989. commit.id,
  7990. b"Test Author <test@example.com>",
  7991. 1234567890,
  7992. 0,
  7993. b"commit (initial): Initial commit",
  7994. )
  7995. # Read reflog using porcelain
  7996. entries = list(porcelain.reflog(self.repo_path))
  7997. self.assertEqual(1, len(entries))
  7998. self.assertEqual(ZERO_SHA, entries[0].old_sha)
  7999. self.assertEqual(commit.id, entries[0].new_sha)
  8000. self.assertEqual(b"Test Author <test@example.com>", entries[0].committer)
  8001. self.assertEqual(1234567890, entries[0].timestamp)
  8002. self.assertEqual(0, entries[0].timezone)
  8003. self.assertEqual(b"commit (initial): Initial commit", entries[0].message)
  8004. def test_reflog_with_string_ref(self):
  8005. """Test reading reflog with string reference."""
  8006. # Create a commit
  8007. blob = Blob.from_string(b"test content")
  8008. self.repo.object_store.add_object(blob)
  8009. tree = Tree()
  8010. tree.add(b"test", 0o100644, blob.id)
  8011. self.repo.object_store.add_object(tree)
  8012. commit = Commit()
  8013. commit.tree = tree.id
  8014. commit.author = b"Test Author <test@example.com>"
  8015. commit.committer = b"Test Author <test@example.com>"
  8016. commit.commit_time = 1234567890
  8017. commit.commit_timezone = 0
  8018. commit.author_time = 1234567890
  8019. commit.author_timezone = 0
  8020. commit.message = b"Initial commit"
  8021. self.repo.object_store.add_object(commit)
  8022. # Write a reflog entry
  8023. self.repo._write_reflog(
  8024. b"refs/heads/master",
  8025. ZERO_SHA,
  8026. commit.id,
  8027. b"Test Author <test@example.com>",
  8028. 1234567890,
  8029. 0,
  8030. b"commit (initial): Initial commit",
  8031. )
  8032. # Read reflog using porcelain with string ref
  8033. entries = list(porcelain.reflog(self.repo_path, "refs/heads/master"))
  8034. self.assertEqual(1, len(entries))
  8035. self.assertEqual(commit.id, entries[0].new_sha)
  8036. def test_reflog_all(self):
  8037. """Test reading all reflogs."""
  8038. # Create a commit
  8039. blob = Blob.from_string(b"test content")
  8040. self.repo.object_store.add_object(blob)
  8041. tree = Tree()
  8042. tree.add(b"test", 0o100644, blob.id)
  8043. self.repo.object_store.add_object(tree)
  8044. commit = Commit()
  8045. commit.tree = tree.id
  8046. commit.author = b"Test Author <test@example.com>"
  8047. commit.committer = b"Test Author <test@example.com>"
  8048. commit.commit_time = 1234567890
  8049. commit.commit_timezone = 0
  8050. commit.author_time = 1234567890
  8051. commit.author_timezone = 0
  8052. commit.message = b"Initial commit"
  8053. self.repo.object_store.add_object(commit)
  8054. # Write reflog entries for HEAD and master
  8055. self.repo._write_reflog(
  8056. b"HEAD",
  8057. ZERO_SHA,
  8058. commit.id,
  8059. b"Test Author <test@example.com>",
  8060. 1234567890,
  8061. 0,
  8062. b"commit (initial): Initial commit",
  8063. )
  8064. self.repo._write_reflog(
  8065. b"refs/heads/master",
  8066. ZERO_SHA,
  8067. commit.id,
  8068. b"Test Author <test@example.com>",
  8069. 1234567891,
  8070. 0,
  8071. b"branch: Created from HEAD",
  8072. )
  8073. # Read all reflogs using porcelain
  8074. entries = list(porcelain.reflog(self.repo_path, all=True))
  8075. # Should have at least 2 entries (HEAD and refs/heads/master)
  8076. self.assertGreaterEqual(len(entries), 2)
  8077. # Check that we got entries from different refs
  8078. refs_seen = set()
  8079. for ref, entry in entries:
  8080. refs_seen.add(ref)
  8081. self.assertEqual(commit.id, entry.new_sha)
  8082. # Should have seen at least HEAD and refs/heads/master
  8083. self.assertIn(b"HEAD", refs_seen)
  8084. self.assertIn(b"refs/heads/master", refs_seen)
  8085. def test_reflog_expire_by_time(self):
  8086. """Test expiring reflog entries by timestamp."""
  8087. # Create commits
  8088. blob = Blob.from_string(b"test content")
  8089. self.repo.object_store.add_object(blob)
  8090. tree = Tree()
  8091. tree.add(b"test", 0o100644, blob.id)
  8092. self.repo.object_store.add_object(tree)
  8093. commit1 = Commit()
  8094. commit1.tree = tree.id
  8095. commit1.author = b"Test Author <test@example.com>"
  8096. commit1.committer = b"Test Author <test@example.com>"
  8097. commit1.commit_time = 1000000000
  8098. commit1.commit_timezone = 0
  8099. commit1.author_time = 1000000000
  8100. commit1.author_timezone = 0
  8101. commit1.message = b"Old commit"
  8102. self.repo.object_store.add_object(commit1)
  8103. commit2 = Commit()
  8104. commit2.tree = tree.id
  8105. commit2.author = b"Test Author <test@example.com>"
  8106. commit2.committer = b"Test Author <test@example.com>"
  8107. commit2.commit_time = 2000000000
  8108. commit2.commit_timezone = 0
  8109. commit2.author_time = 2000000000
  8110. commit2.author_timezone = 0
  8111. commit2.message = b"Recent commit"
  8112. self.repo.object_store.add_object(commit2)
  8113. # Write reflog entries with different timestamps
  8114. self.repo._write_reflog(
  8115. b"HEAD",
  8116. ZERO_SHA,
  8117. commit1.id,
  8118. b"Test Author <test@example.com>",
  8119. 1000000000,
  8120. 0,
  8121. b"commit: Old commit",
  8122. )
  8123. self.repo._write_reflog(
  8124. b"HEAD",
  8125. commit1.id,
  8126. commit2.id,
  8127. b"Test Author <test@example.com>",
  8128. 2000000000,
  8129. 0,
  8130. b"commit: Recent commit",
  8131. )
  8132. # Expire entries older than timestamp 1500000000
  8133. result = porcelain.reflog_expire(
  8134. self.repo_path, ref=b"HEAD", expire_time=1500000000
  8135. )
  8136. self.assertEqual(1, result[b"HEAD"])
  8137. # Check that only the recent entry remains
  8138. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8139. self.assertEqual(1, len(entries))
  8140. self.assertEqual(commit2.id, entries[0].new_sha)
  8141. def test_reflog_expire_all(self):
  8142. """Test expiring reflog entries for all refs."""
  8143. # Create a commit
  8144. blob = Blob.from_string(b"test content")
  8145. self.repo.object_store.add_object(blob)
  8146. tree = Tree()
  8147. tree.add(b"test", 0o100644, blob.id)
  8148. self.repo.object_store.add_object(tree)
  8149. commit = Commit()
  8150. commit.tree = tree.id
  8151. commit.author = b"Test Author <test@example.com>"
  8152. commit.committer = b"Test Author <test@example.com>"
  8153. commit.commit_time = 1000000000
  8154. commit.commit_timezone = 0
  8155. commit.author_time = 1000000000
  8156. commit.author_timezone = 0
  8157. commit.message = b"Test commit"
  8158. self.repo.object_store.add_object(commit)
  8159. # Write old reflog entries for multiple refs
  8160. self.repo._write_reflog(
  8161. b"HEAD",
  8162. ZERO_SHA,
  8163. commit.id,
  8164. b"Test Author <test@example.com>",
  8165. 1000000000,
  8166. 0,
  8167. b"commit: Test commit",
  8168. )
  8169. self.repo._write_reflog(
  8170. b"refs/heads/master",
  8171. ZERO_SHA,
  8172. commit.id,
  8173. b"Test Author <test@example.com>",
  8174. 1000000000,
  8175. 0,
  8176. b"commit: Test commit",
  8177. )
  8178. # Expire all old entries
  8179. result = porcelain.reflog_expire(
  8180. self.repo_path, all=True, expire_time=2000000000
  8181. )
  8182. # Should have expired entries from both refs
  8183. self.assertIn(b"HEAD", result)
  8184. self.assertIn(b"refs/heads/master", result)
  8185. self.assertEqual(1, result[b"HEAD"])
  8186. self.assertEqual(1, result[b"refs/heads/master"])
  8187. def test_reflog_expire_dry_run(self):
  8188. """Test dry-run mode for reflog expire."""
  8189. # Create a commit
  8190. blob = Blob.from_string(b"test content")
  8191. self.repo.object_store.add_object(blob)
  8192. tree = Tree()
  8193. tree.add(b"test", 0o100644, blob.id)
  8194. self.repo.object_store.add_object(tree)
  8195. commit = Commit()
  8196. commit.tree = tree.id
  8197. commit.author = b"Test Author <test@example.com>"
  8198. commit.committer = b"Test Author <test@example.com>"
  8199. commit.commit_time = 1000000000
  8200. commit.commit_timezone = 0
  8201. commit.author_time = 1000000000
  8202. commit.author_timezone = 0
  8203. commit.message = b"Test commit"
  8204. self.repo.object_store.add_object(commit)
  8205. # Write old reflog entry
  8206. self.repo._write_reflog(
  8207. b"HEAD",
  8208. ZERO_SHA,
  8209. commit.id,
  8210. b"Test Author <test@example.com>",
  8211. 1000000000,
  8212. 0,
  8213. b"commit: Test commit",
  8214. )
  8215. # Dry run expire
  8216. result = porcelain.reflog_expire(
  8217. self.repo_path, ref=b"HEAD", expire_time=2000000000, dry_run=True
  8218. )
  8219. self.assertEqual(1, result[b"HEAD"])
  8220. # Entry should still exist
  8221. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8222. self.assertEqual(1, len(entries))
  8223. def test_reflog_delete(self):
  8224. """Test deleting specific reflog entry."""
  8225. # Create commits
  8226. blob = Blob.from_string(b"test content")
  8227. self.repo.object_store.add_object(blob)
  8228. tree = Tree()
  8229. tree.add(b"test", 0o100644, blob.id)
  8230. self.repo.object_store.add_object(tree)
  8231. commit1 = Commit()
  8232. commit1.tree = tree.id
  8233. commit1.author = b"Test Author <test@example.com>"
  8234. commit1.committer = b"Test Author <test@example.com>"
  8235. commit1.commit_time = 1000000000
  8236. commit1.commit_timezone = 0
  8237. commit1.author_time = 1000000000
  8238. commit1.author_timezone = 0
  8239. commit1.message = b"First commit"
  8240. self.repo.object_store.add_object(commit1)
  8241. commit2 = Commit()
  8242. commit2.tree = tree.id
  8243. commit2.author = b"Test Author <test@example.com>"
  8244. commit2.committer = b"Test Author <test@example.com>"
  8245. commit2.commit_time = 2000000000
  8246. commit2.commit_timezone = 0
  8247. commit2.author_time = 2000000000
  8248. commit2.author_timezone = 0
  8249. commit2.message = b"Second commit"
  8250. self.repo.object_store.add_object(commit2)
  8251. # Write two reflog entries
  8252. self.repo._write_reflog(
  8253. b"HEAD",
  8254. ZERO_SHA,
  8255. commit1.id,
  8256. b"Test Author <test@example.com>",
  8257. 1000000000,
  8258. 0,
  8259. b"commit: First commit",
  8260. )
  8261. self.repo._write_reflog(
  8262. b"HEAD",
  8263. commit1.id,
  8264. commit2.id,
  8265. b"Test Author <test@example.com>",
  8266. 2000000000,
  8267. 0,
  8268. b"commit: Second commit",
  8269. )
  8270. # Delete the most recent entry (index 0)
  8271. porcelain.reflog_delete(self.repo_path, ref=b"HEAD", index=0)
  8272. # Should only have one entry left
  8273. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8274. self.assertEqual(1, len(entries))
  8275. self.assertEqual(commit1.id, entries[0].new_sha)
  8276. def test_reflog_expire_unreachable(self):
  8277. """Test expiring unreachable reflog entries."""
  8278. # Create commits
  8279. blob = Blob.from_string(b"test content")
  8280. self.repo.object_store.add_object(blob)
  8281. tree = Tree()
  8282. tree.add(b"test", 0o100644, blob.id)
  8283. self.repo.object_store.add_object(tree)
  8284. # Create commit 1 - will be reachable (pointed to by HEAD)
  8285. commit1 = Commit()
  8286. commit1.tree = tree.id
  8287. commit1.author = b"Test Author <test@example.com>"
  8288. commit1.committer = b"Test Author <test@example.com>"
  8289. commit1.commit_time = 1000000000
  8290. commit1.commit_timezone = 0
  8291. commit1.author_time = 1000000000
  8292. commit1.author_timezone = 0
  8293. commit1.message = b"Reachable commit"
  8294. self.repo.object_store.add_object(commit1)
  8295. # Create commit 2 - will be unreachable
  8296. commit2 = Commit()
  8297. commit2.tree = tree.id
  8298. commit2.author = b"Test Author <test@example.com>"
  8299. commit2.committer = b"Test Author <test@example.com>"
  8300. commit2.commit_time = 1500000000
  8301. commit2.commit_timezone = 0
  8302. commit2.author_time = 1500000000
  8303. commit2.author_timezone = 0
  8304. commit2.message = b"Unreachable commit"
  8305. self.repo.object_store.add_object(commit2)
  8306. # Create commit 3 - will also be reachable (pointed to by master)
  8307. commit3 = Commit()
  8308. commit3.tree = tree.id
  8309. commit3.author = b"Test Author <test@example.com>"
  8310. commit3.committer = b"Test Author <test@example.com>"
  8311. commit3.commit_time = 2000000000
  8312. commit3.commit_timezone = 0
  8313. commit3.author_time = 2000000000
  8314. commit3.author_timezone = 0
  8315. commit3.message = b"Another reachable commit"
  8316. self.repo.object_store.add_object(commit3)
  8317. # Set up refs to make commit1 and commit3 reachable
  8318. # HEAD is a symbolic ref to refs/heads/master by default, so we set master first
  8319. self.repo.refs[b"refs/heads/master"] = commit1.id
  8320. # Create another branch pointing to commit3
  8321. self.repo.refs[b"refs/heads/feature"] = commit3.id
  8322. # Write reflog entries for all three commits
  8323. self.repo._write_reflog(
  8324. b"HEAD",
  8325. ZERO_SHA,
  8326. commit1.id,
  8327. b"Test Author <test@example.com>",
  8328. 1000000000,
  8329. 0,
  8330. b"commit: Reachable commit",
  8331. )
  8332. self.repo._write_reflog(
  8333. b"HEAD",
  8334. commit1.id,
  8335. commit2.id,
  8336. b"Test Author <test@example.com>",
  8337. 1500000000,
  8338. 0,
  8339. b"commit: Unreachable commit",
  8340. )
  8341. self.repo._write_reflog(
  8342. b"HEAD",
  8343. commit2.id,
  8344. commit3.id,
  8345. b"Test Author <test@example.com>",
  8346. 2000000000,
  8347. 0,
  8348. b"commit: Another reachable commit",
  8349. )
  8350. # Expire unreachable entries older than a time that includes commit2
  8351. # but not the reachable commits
  8352. result = porcelain.reflog_expire(
  8353. self.repo_path,
  8354. ref=b"HEAD",
  8355. expire_unreachable_time=1600000000, # After commit2, before commit3
  8356. )
  8357. # Should have expired only commit2
  8358. self.assertEqual(1, result[b"HEAD"])
  8359. # Verify the remaining entries
  8360. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8361. self.assertEqual(2, len(entries))
  8362. # commit1 and commit3 should remain (both reachable)
  8363. self.assertEqual(commit1.id, entries[0].new_sha)
  8364. self.assertEqual(commit3.id, entries[1].new_sha)
  8365. class WriteCommitGraphTests(PorcelainTestCase):
  8366. """Tests for the write_commit_graph porcelain function."""
  8367. def test_write_commit_graph_empty_repo(self):
  8368. """Test writing commit graph on empty repository."""
  8369. # Should not fail on empty repo
  8370. porcelain.write_commit_graph(self.repo_path)
  8371. # No commit graph should be created for empty repo
  8372. graph_path = os.path.join(
  8373. self.repo_path, ".git", "objects", "info", "commit-graph"
  8374. )
  8375. self.assertFalse(os.path.exists(graph_path))
  8376. def test_write_commit_graph_with_commits(self):
  8377. """Test writing commit graph with commits."""
  8378. # Create some commits
  8379. c1, c2, c3 = build_commit_graph(
  8380. self.repo.object_store,
  8381. [[1], [2, 1], [3, 1, 2]],
  8382. attrs={
  8383. 1: {"message": b"First commit"},
  8384. 2: {"message": b"Second commit"},
  8385. 3: {"message": b"Merge commit"},
  8386. },
  8387. )
  8388. self.repo.refs[b"refs/heads/master"] = c3.id
  8389. self.repo.refs[b"refs/heads/branch"] = c2.id
  8390. # Write commit graph
  8391. porcelain.write_commit_graph(self.repo_path)
  8392. # Verify commit graph was created
  8393. graph_path = os.path.join(
  8394. self.repo_path, ".git", "objects", "info", "commit-graph"
  8395. )
  8396. self.assertTrue(os.path.exists(graph_path))
  8397. # Load and verify the commit graph
  8398. from dulwich.commit_graph import read_commit_graph
  8399. commit_graph = read_commit_graph(graph_path)
  8400. self.assertIsNotNone(commit_graph)
  8401. self.assertEqual(3, len(commit_graph))
  8402. # Verify all commits are in the graph
  8403. for commit_obj in [c1, c2, c3]:
  8404. entry = commit_graph.get_entry_by_oid(commit_obj.id)
  8405. self.assertIsNotNone(entry)
  8406. def test_write_commit_graph_config_disabled(self):
  8407. """Test that commit graph is not written when disabled by config."""
  8408. # Create a commit
  8409. (c1,) = build_commit_graph(
  8410. self.repo.object_store, [[1]], attrs={1: {"message": b"First commit"}}
  8411. )
  8412. self.repo.refs[b"refs/heads/master"] = c1.id
  8413. # Disable commit graph in config
  8414. config = self.repo.get_config()
  8415. config.set((b"core",), b"commitGraph", b"false")
  8416. config.write_to_path()
  8417. # Write commit graph (should respect config)
  8418. porcelain.write_commit_graph(self.repo_path)
  8419. # Verify commit graph still gets written
  8420. # (porcelain.write_commit_graph explicitly writes regardless of config)
  8421. graph_path = os.path.join(
  8422. self.repo_path, ".git", "objects", "info", "commit-graph"
  8423. )
  8424. self.assertTrue(os.path.exists(graph_path))
  8425. def test_write_commit_graph_reachable_false(self):
  8426. """Test writing commit graph with reachable=False."""
  8427. # Create commits
  8428. _c1, _c2, c3 = build_commit_graph(
  8429. self.repo.object_store,
  8430. [[1], [2, 1], [3, 2]],
  8431. attrs={
  8432. 1: {"message": b"First commit"},
  8433. 2: {"message": b"Second commit"},
  8434. 3: {"message": b"Third commit"},
  8435. },
  8436. )
  8437. # Only reference the third commit
  8438. self.repo.refs[b"refs/heads/master"] = c3.id
  8439. # Write commit graph with reachable=False
  8440. porcelain.write_commit_graph(self.repo_path, reachable=False)
  8441. # Verify commit graph was created
  8442. graph_path = os.path.join(
  8443. self.repo_path, ".git", "objects", "info", "commit-graph"
  8444. )
  8445. self.assertTrue(os.path.exists(graph_path))
  8446. # Load and verify the commit graph
  8447. from dulwich.commit_graph import read_commit_graph
  8448. commit_graph = read_commit_graph(graph_path)
  8449. self.assertIsNotNone(commit_graph)
  8450. # With reachable=False, only directly referenced commits should be included
  8451. # In this case, only c3 (from refs/heads/master)
  8452. self.assertEqual(1, len(commit_graph))
  8453. entry = commit_graph.get_entry_by_oid(c3.id)
  8454. self.assertIsNotNone(entry)
  8455. class WorktreePorcelainTests(PorcelainTestCase):
  8456. """Tests for porcelain worktree functions."""
  8457. def test_worktree_list_single(self):
  8458. """Test listing worktrees when only main worktree exists."""
  8459. # Create initial commit
  8460. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8461. f.write("test content")
  8462. porcelain.add(self.repo_path, ["test.txt"])
  8463. porcelain.commit(self.repo_path, message=b"Initial commit")
  8464. # List worktrees
  8465. worktrees = porcelain.worktree_list(self.repo_path)
  8466. self.assertEqual(len(worktrees), 1)
  8467. self.assertEqual(worktrees[0].path, self.repo_path)
  8468. self.assertFalse(worktrees[0].bare)
  8469. self.assertIsNotNone(worktrees[0].head)
  8470. self.assertIsNotNone(worktrees[0].branch)
  8471. def test_worktree_add_branch(self):
  8472. """Test adding a worktree with a new branch."""
  8473. # Create initial commit
  8474. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8475. f.write("test content")
  8476. porcelain.add(self.repo_path, ["test.txt"])
  8477. porcelain.commit(self.repo_path, message=b"Initial commit")
  8478. # Add worktree
  8479. wt_path = os.path.join(self.test_dir, "worktree1")
  8480. result_path = porcelain.worktree_add(self.repo_path, wt_path, branch=b"feature")
  8481. self.assertEqual(result_path, wt_path)
  8482. self.assertTrue(os.path.exists(wt_path))
  8483. self.assertTrue(os.path.exists(os.path.join(wt_path, ".git")))
  8484. # Check it appears in the list
  8485. worktrees = porcelain.worktree_list(self.repo_path)
  8486. self.assertEqual(len(worktrees), 2)
  8487. # Find the new worktree
  8488. new_wt = None
  8489. for wt in worktrees:
  8490. if wt.path == wt_path:
  8491. new_wt = wt
  8492. break
  8493. self.assertIsNotNone(new_wt)
  8494. self.assertEqual(new_wt.branch, b"refs/heads/feature")
  8495. self.assertFalse(new_wt.detached)
  8496. def test_worktree_add_detached(self):
  8497. """Test adding a detached worktree."""
  8498. # Create initial commit
  8499. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8500. f.write("test content")
  8501. porcelain.add(self.repo_path, ["test.txt"])
  8502. sha = porcelain.commit(self.repo_path, message=b"Initial commit")
  8503. # Add detached worktree
  8504. wt_path = os.path.join(self.test_dir, "detached")
  8505. porcelain.worktree_add(self.repo_path, wt_path, commit=sha, detach=True)
  8506. # Check it's detached
  8507. worktrees = porcelain.worktree_list(self.repo_path)
  8508. for wt in worktrees:
  8509. if wt.path == wt_path:
  8510. self.assertTrue(wt.detached)
  8511. self.assertIsNone(wt.branch)
  8512. self.assertEqual(wt.head, sha)
  8513. def test_worktree_remove(self):
  8514. """Test removing a worktree."""
  8515. # Create initial commit
  8516. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8517. f.write("test content")
  8518. porcelain.add(self.repo_path, ["test.txt"])
  8519. porcelain.commit(self.repo_path, message=b"Initial commit")
  8520. # Add and remove worktree
  8521. wt_path = os.path.join(self.test_dir, "to-remove")
  8522. porcelain.worktree_add(self.repo_path, wt_path)
  8523. # Verify it exists
  8524. self.assertTrue(os.path.exists(wt_path))
  8525. self.assertEqual(len(porcelain.worktree_list(self.repo_path)), 2)
  8526. # Remove it
  8527. porcelain.worktree_remove(self.repo_path, wt_path)
  8528. # Verify it's gone
  8529. self.assertFalse(os.path.exists(wt_path))
  8530. self.assertEqual(len(porcelain.worktree_list(self.repo_path)), 1)
  8531. def test_worktree_prune(self):
  8532. """Test pruning worktrees."""
  8533. # Create initial commit
  8534. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8535. f.write("test content")
  8536. porcelain.add(self.repo_path, ["test.txt"])
  8537. porcelain.commit(self.repo_path, message=b"Initial commit")
  8538. # Add worktree
  8539. wt_path = os.path.join(self.test_dir, "to-prune")
  8540. porcelain.worktree_add(self.repo_path, wt_path)
  8541. # Manually remove directory
  8542. shutil.rmtree(wt_path)
  8543. # Prune should remove the administrative files
  8544. pruned = porcelain.worktree_prune(self.repo_path)
  8545. self.assertEqual(len(pruned), 1)
  8546. # Verify it's gone from the list
  8547. worktrees = porcelain.worktree_list(self.repo_path)
  8548. self.assertEqual(len(worktrees), 1)
  8549. def test_worktree_lock_unlock(self):
  8550. """Test locking and unlocking worktrees."""
  8551. # Create initial commit
  8552. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8553. f.write("test content")
  8554. porcelain.add(self.repo_path, ["test.txt"])
  8555. porcelain.commit(self.repo_path, message=b"Initial commit")
  8556. # Add worktree
  8557. wt_path = os.path.join(self.test_dir, "lockable")
  8558. porcelain.worktree_add(self.repo_path, wt_path)
  8559. # Lock it
  8560. porcelain.worktree_lock(self.repo_path, wt_path, reason="Testing")
  8561. # Verify it's locked
  8562. worktrees = porcelain.worktree_list(self.repo_path)
  8563. for wt in worktrees:
  8564. if wt.path == wt_path:
  8565. self.assertTrue(wt.locked)
  8566. # Unlock it
  8567. porcelain.worktree_unlock(self.repo_path, wt_path)
  8568. # Verify it's unlocked
  8569. worktrees = porcelain.worktree_list(self.repo_path)
  8570. for wt in worktrees:
  8571. if wt.path == wt_path:
  8572. self.assertFalse(wt.locked)
  8573. def test_worktree_move(self):
  8574. """Test moving a worktree."""
  8575. # Create initial commit
  8576. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8577. f.write("test content")
  8578. porcelain.add(self.repo_path, ["test.txt"])
  8579. porcelain.commit(self.repo_path, message=b"Initial commit")
  8580. # Add worktree
  8581. old_path = os.path.join(self.test_dir, "old-location")
  8582. porcelain.worktree_add(self.repo_path, old_path)
  8583. # Create a file in the worktree
  8584. test_file = os.path.join(old_path, "workspace.txt")
  8585. with open(test_file, "w") as f:
  8586. f.write("workspace content")
  8587. # Move it
  8588. new_path = os.path.join(self.test_dir, "new-location")
  8589. porcelain.worktree_move(self.repo_path, old_path, new_path)
  8590. # Verify old path doesn't exist, new path does
  8591. self.assertFalse(os.path.exists(old_path))
  8592. self.assertTrue(os.path.exists(new_path))
  8593. self.assertTrue(os.path.exists(os.path.join(new_path, "workspace.txt")))
  8594. # Verify it's in the list at new location
  8595. worktrees = porcelain.worktree_list(self.repo_path)
  8596. paths = [wt.path for wt in worktrees]
  8597. self.assertIn(new_path, paths)
  8598. self.assertNotIn(old_path, paths)
  8599. class VarTests(PorcelainTestCase):
  8600. """Tests for the var command."""
  8601. def test_var_author_ident(self):
  8602. """Test getting GIT_AUTHOR_IDENT."""
  8603. # Set up user config
  8604. config = self.repo.get_config()
  8605. config.set((b"user",), b"name", b"Test Author")
  8606. config.set((b"user",), b"email", b"author@example.com")
  8607. config.write_to_path()
  8608. result = porcelain.var(self.repo_path, variable="GIT_AUTHOR_IDENT")
  8609. self.assertIn("Test Author <author@example.com>", result)
  8610. # Check that timestamp and timezone are included
  8611. # Format: Name <email> timestamp timezone
  8612. # "Test Author" is 2 words, so we have: Test, Author, <email>, timestamp, timezone
  8613. parts = result.split()
  8614. self.assertGreaterEqual(
  8615. len(parts), 4
  8616. ) # At least name, <email>, timestamp, timezone
  8617. # Check last two parts are timestamp and timezone
  8618. self.assertTrue(parts[-2].isdigit()) # timestamp
  8619. self.assertRegex(parts[-1], r"[+-]\d{4}") # timezone
  8620. def test_var_committer_ident(self):
  8621. """Test getting GIT_COMMITTER_IDENT."""
  8622. # Set up user config
  8623. config = self.repo.get_config()
  8624. config.set((b"user",), b"name", b"Test Committer")
  8625. config.set((b"user",), b"email", b"committer@example.com")
  8626. config.write_to_path()
  8627. result = porcelain.var(self.repo_path, variable="GIT_COMMITTER_IDENT")
  8628. self.assertIn("Test Committer <committer@example.com>", result)
  8629. # Check that timestamp and timezone are included
  8630. parts = result.split()
  8631. self.assertGreaterEqual(
  8632. len(parts), 4
  8633. ) # At least name, <email>, timestamp, timezone
  8634. # Check last two parts are timestamp and timezone
  8635. self.assertTrue(parts[-2].isdigit()) # timestamp
  8636. self.assertRegex(parts[-1], r"[+-]\d{4}") # timezone
  8637. def test_var_editor(self):
  8638. """Test getting GIT_EDITOR."""
  8639. # Test with environment variable
  8640. self.overrideEnv("GIT_EDITOR", "vim")
  8641. result = porcelain.var(self.repo_path, variable="GIT_EDITOR")
  8642. self.assertEqual(result, "vim")
  8643. def test_var_editor_from_config(self):
  8644. """Test getting GIT_EDITOR from config."""
  8645. # Set up editor in config
  8646. config = self.repo.get_config()
  8647. config.set((b"core",), b"editor", b"emacs")
  8648. config.write_to_path()
  8649. # Make sure env var is not set
  8650. self.overrideEnv("GIT_EDITOR", None)
  8651. result = porcelain.var(self.repo_path, variable="GIT_EDITOR")
  8652. self.assertEqual(result, "emacs")
  8653. def test_var_pager(self):
  8654. """Test getting GIT_PAGER."""
  8655. # Test with environment variable
  8656. self.overrideEnv("GIT_PAGER", "less")
  8657. result = porcelain.var(self.repo_path, variable="GIT_PAGER")
  8658. self.assertEqual(result, "less")
  8659. def test_var_pager_from_config(self):
  8660. """Test getting GIT_PAGER from config."""
  8661. # Set up pager in config
  8662. config = self.repo.get_config()
  8663. config.set((b"core",), b"pager", b"more")
  8664. config.write_to_path()
  8665. # Make sure env var is not set
  8666. self.overrideEnv("GIT_PAGER", None)
  8667. result = porcelain.var(self.repo_path, variable="GIT_PAGER")
  8668. self.assertEqual(result, "more")
  8669. def test_var_default_branch(self):
  8670. """Test getting GIT_DEFAULT_BRANCH."""
  8671. # Set up default branch in config
  8672. config = self.repo.get_config()
  8673. config.set((b"init",), b"defaultBranch", b"main")
  8674. config.write_to_path()
  8675. result = porcelain.var(self.repo_path, variable="GIT_DEFAULT_BRANCH")
  8676. self.assertEqual(result, "main")
  8677. def test_var_default_branch_default(self):
  8678. """Test getting GIT_DEFAULT_BRANCH with default value."""
  8679. result = porcelain.var(self.repo_path, variable="GIT_DEFAULT_BRANCH")
  8680. self.assertEqual(result, "master")
  8681. def test_var_list_all(self):
  8682. """Test listing all logical variables."""
  8683. # Set up some config
  8684. config = self.repo.get_config()
  8685. config.set((b"user",), b"name", b"Test User")
  8686. config.set((b"user",), b"email", b"test@example.com")
  8687. config.write_to_path()
  8688. result = porcelain.var_list(self.repo_path)
  8689. self.assertIsInstance(result, dict)
  8690. # Check that logical variables are present
  8691. self.assertIn("GIT_AUTHOR_IDENT", result)
  8692. self.assertIn("GIT_COMMITTER_IDENT", result)
  8693. self.assertIn("GIT_DEFAULT_BRANCH", result)
  8694. # Config variables should NOT be included (deprecated feature)
  8695. self.assertNotIn("user.name", result)
  8696. self.assertNotIn("user.email", result)
  8697. # Verify only logical variables are present
  8698. for key in result.keys():
  8699. self.assertTrue(key.startswith("GIT_"))
  8700. def test_var_unknown_variable(self):
  8701. """Test requesting an unknown variable."""
  8702. with self.assertRaises(KeyError):
  8703. porcelain.var(self.repo_path, variable="UNKNOWN_VARIABLE")
  8704. class MergeBaseTests(PorcelainTestCase):
  8705. """Tests for merge-base, is_ancestor, and independent_commits."""
  8706. def test_merge_base_linear_history(self):
  8707. """Test merge-base with linear history."""
  8708. # Create linear history: c1 <- c2 <- c3
  8709. _c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8710. self.repo.refs[b"refs/heads/branch1"] = c2.id
  8711. self.repo.refs[b"refs/heads/branch2"] = c3.id
  8712. result = porcelain.merge_base(
  8713. self.repo.path, committishes=["refs/heads/branch1", "refs/heads/branch2"]
  8714. )
  8715. self.assertEqual([c2.id], result)
  8716. def test_merge_base_diverged(self):
  8717. """Test merge-base with diverged branches."""
  8718. # Create diverged history: c1 <- c2a, c1 <- c2b
  8719. c1, c2a, c2b = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1]])
  8720. self.repo.refs[b"refs/heads/branch-a"] = c2a.id
  8721. self.repo.refs[b"refs/heads/branch-b"] = c2b.id
  8722. result = porcelain.merge_base(
  8723. self.repo.path, committishes=["refs/heads/branch-a", "refs/heads/branch-b"]
  8724. )
  8725. self.assertEqual([c1.id], result)
  8726. def test_merge_base_all(self):
  8727. """Test merge-base with --all flag."""
  8728. # Create history with multiple common ancestors
  8729. commits = build_commit_graph(
  8730. self.repo.object_store,
  8731. [[1], [2, 1], [3, 1], [4, 2, 3], [5, 2, 3]],
  8732. )
  8733. _c1, c2, c3, c4, c5 = commits
  8734. self.repo.refs[b"refs/heads/branch1"] = c4.id
  8735. self.repo.refs[b"refs/heads/branch2"] = c5.id
  8736. # Without --all, should return only first result
  8737. result = porcelain.merge_base(
  8738. self.repo.path,
  8739. committishes=["refs/heads/branch1", "refs/heads/branch2"],
  8740. all=False,
  8741. )
  8742. self.assertEqual(1, len(result))
  8743. # With --all, should return all merge bases
  8744. result_all = porcelain.merge_base(
  8745. self.repo.path,
  8746. committishes=["refs/heads/branch1", "refs/heads/branch2"],
  8747. all=True,
  8748. )
  8749. self.assertEqual(2, len(result_all))
  8750. self.assertIn(c2.id, result_all)
  8751. self.assertIn(c3.id, result_all)
  8752. def test_merge_base_octopus(self):
  8753. """Test merge-base with --octopus flag."""
  8754. # Create three-way diverged history
  8755. commits = build_commit_graph(
  8756. self.repo.object_store, [[1], [2, 1], [3, 1], [4, 1]]
  8757. )
  8758. c1, c2, c3, c4 = commits
  8759. self.repo.refs[b"refs/heads/a"] = c2.id
  8760. self.repo.refs[b"refs/heads/b"] = c3.id
  8761. self.repo.refs[b"refs/heads/c"] = c4.id
  8762. result = porcelain.merge_base(
  8763. self.repo.path,
  8764. committishes=["refs/heads/a", "refs/heads/b", "refs/heads/c"],
  8765. octopus=True,
  8766. )
  8767. self.assertEqual([c1.id], result)
  8768. def test_merge_base_requires_two_commits(self):
  8769. """Test merge-base requires at least two commits."""
  8770. with self.assertRaises(ValueError):
  8771. porcelain.merge_base(self.repo.path, committishes=["HEAD"])
  8772. def test_is_ancestor_true(self):
  8773. """Test is_ancestor returns True when commit is an ancestor."""
  8774. # Create linear history: c1 <- c2 <- c3
  8775. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8776. self.repo.refs[b"refs/heads/main"] = c3.id
  8777. # c1 is ancestor of c3
  8778. result = porcelain.is_ancestor(
  8779. self.repo.path, ancestor=c1.id.decode(), descendant=c3.id.decode()
  8780. )
  8781. self.assertTrue(result)
  8782. # c2 is ancestor of c3
  8783. result = porcelain.is_ancestor(
  8784. self.repo.path, ancestor=c2.id.decode(), descendant=c3.id.decode()
  8785. )
  8786. self.assertTrue(result)
  8787. def test_is_ancestor_false(self):
  8788. """Test is_ancestor returns False when commit is not an ancestor."""
  8789. # Create diverged history: c1 <- c2a, c1 <- c2b
  8790. _c1, c2a, c2b = build_commit_graph(
  8791. self.repo.object_store, [[1], [2, 1], [3, 1]]
  8792. )
  8793. # c2a is not ancestor of c2b
  8794. result = porcelain.is_ancestor(
  8795. self.repo.path, ancestor=c2a.id.decode(), descendant=c2b.id.decode()
  8796. )
  8797. self.assertFalse(result)
  8798. # c2b is not ancestor of c2a
  8799. result = porcelain.is_ancestor(
  8800. self.repo.path, ancestor=c2b.id.decode(), descendant=c2a.id.decode()
  8801. )
  8802. self.assertFalse(result)
  8803. def test_is_ancestor_requires_both(self):
  8804. """Test is_ancestor requires both ancestor and descendant."""
  8805. with self.assertRaises(ValueError):
  8806. porcelain.is_ancestor(self.repo.path, ancestor="HEAD", descendant=None)
  8807. with self.assertRaises(ValueError):
  8808. porcelain.is_ancestor(self.repo.path, ancestor=None, descendant="HEAD")
  8809. def test_independent_commits_linear(self):
  8810. """Test independent_commits with linear history."""
  8811. # Create linear history: c1 <- c2 <- c3
  8812. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8813. # Only c3 is independent (c1 and c2 are ancestors)
  8814. result = porcelain.independent_commits(
  8815. self.repo.path,
  8816. committishes=[c1.id.decode(), c2.id.decode(), c3.id.decode()],
  8817. )
  8818. self.assertEqual([c3.id], result)
  8819. def test_independent_commits_diverged(self):
  8820. """Test independent_commits with diverged branches."""
  8821. # Create diverged history: c1 <- c2a, c1 <- c2b
  8822. _c1, c2a, c2b = build_commit_graph(
  8823. self.repo.object_store, [[1], [2, 1], [3, 1]]
  8824. )
  8825. # c2a and c2b are both independent (neither is ancestor of the other)
  8826. result = porcelain.independent_commits(
  8827. self.repo.path, committishes=[c2a.id.decode(), c2b.id.decode()]
  8828. )
  8829. self.assertEqual(2, len(result))
  8830. self.assertIn(c2a.id, result)
  8831. self.assertIn(c2b.id, result)
  8832. def test_independent_commits_mixed(self):
  8833. """Test independent_commits with mixed history."""
  8834. # Create mixed history
  8835. commits = build_commit_graph(
  8836. self.repo.object_store, [[1], [2, 1], [3, 1], [4, 2]]
  8837. )
  8838. _c1, c2, c3, c4 = commits
  8839. # c4 and c3 are independent; c2 is ancestor of c4
  8840. result = porcelain.independent_commits(
  8841. self.repo.path,
  8842. committishes=[c2.id.decode(), c3.id.decode(), c4.id.decode()],
  8843. )
  8844. self.assertEqual(2, len(result))
  8845. self.assertIn(c3.id, result)
  8846. self.assertIn(c4.id, result)
  8847. self.assertNotIn(c2.id, result)
  8848. def test_independent_commits_empty(self):
  8849. """Test independent_commits with empty list."""
  8850. result = porcelain.independent_commits(self.repo.path, committishes=[])
  8851. self.assertEqual([], result)
  8852. class CherryTests(PorcelainTestCase):
  8853. """Tests for cherry command."""
  8854. def test_cherry_no_changes(self):
  8855. """Test cherry when head and upstream are the same."""
  8856. # Create a simple commit
  8857. commit_sha = self.repo.do_commit(
  8858. b"Initial commit", committer=b"Test <test@example.com>"
  8859. )
  8860. # Cherry should return empty when comparing a commit to itself
  8861. results = porcelain.cherry(
  8862. self.repo.path, upstream=commit_sha.decode(), head=commit_sha.decode()
  8863. )
  8864. self.assertEqual([], results)
  8865. def test_cherry_unique_commits(self):
  8866. """Test cherry with commits unique to head."""
  8867. # Create initial commit
  8868. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  8869. f.write("base content\n")
  8870. self.repo.stage(["file1.txt"])
  8871. base_commit = self.repo.do_commit(
  8872. b"Base commit", committer=b"Test <test@example.com>"
  8873. )
  8874. # Create a new commit on head
  8875. with open(os.path.join(self.repo_path, "file2.txt"), "w") as f:
  8876. f.write("new content\n")
  8877. self.repo.stage(["file2.txt"])
  8878. head_commit = self.repo.do_commit(
  8879. b"New commit", committer=b"Test <test@example.com>"
  8880. )
  8881. # Cherry should show the new commit as unique
  8882. results = porcelain.cherry(
  8883. self.repo.path, upstream=base_commit.decode(), head=head_commit.decode()
  8884. )
  8885. self.assertEqual(1, len(results))
  8886. status, commit_sha, message = results[0]
  8887. self.assertEqual("+", status)
  8888. self.assertEqual(head_commit, commit_sha)
  8889. self.assertIsNone(message)
  8890. def test_cherry_verbose(self):
  8891. """Test cherry with verbose flag."""
  8892. # Create initial commit
  8893. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  8894. f.write("base content\n")
  8895. self.repo.stage(["file1.txt"])
  8896. base_commit = self.repo.do_commit(
  8897. b"Base commit", committer=b"Test <test@example.com>"
  8898. )
  8899. # Create a new commit on head
  8900. with open(os.path.join(self.repo_path, "file2.txt"), "w") as f:
  8901. f.write("new content\n")
  8902. self.repo.stage(["file2.txt"])
  8903. head_commit = self.repo.do_commit(
  8904. b"New commit on head", committer=b"Test <test@example.com>"
  8905. )
  8906. # Cherry with verbose should include commit message
  8907. results = porcelain.cherry(
  8908. self.repo.path,
  8909. upstream=base_commit.decode(),
  8910. head=head_commit.decode(),
  8911. verbose=True,
  8912. )
  8913. self.assertEqual(1, len(results))
  8914. status, commit_sha, message = results[0]
  8915. self.assertEqual("+", status)
  8916. self.assertEqual(head_commit, commit_sha)
  8917. self.assertEqual(b"New commit on head", message)
  8918. def test_cherry_equivalent_patches(self):
  8919. """Test cherry with equivalent patches (cherry-picked commits)."""
  8920. # Create base commit
  8921. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  8922. f.write("line1\n")
  8923. self.repo.stage(["file.txt"])
  8924. base_commit = self.repo.do_commit(
  8925. b"Base commit", committer=b"Test <test@example.com>"
  8926. )
  8927. # Create upstream branch with a change
  8928. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  8929. f.write("line1\nline2\n")
  8930. self.repo.stage(["file.txt"])
  8931. upstream_commit = self.repo.do_commit(
  8932. b"Add line2", committer=b"Test <test@example.com>"
  8933. )
  8934. # Reset to base and create same change on head branch
  8935. self.repo.refs[b"HEAD"] = base_commit
  8936. self.repo.reset_index()
  8937. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  8938. f.write("line1\nline2\n")
  8939. self.repo.stage(["file.txt"])
  8940. head_commit = self.repo.do_commit(
  8941. b"Add line2 (different metadata)",
  8942. committer=b"Different <different@example.com>",
  8943. )
  8944. # Cherry should mark this as equivalent (-)
  8945. results = porcelain.cherry(
  8946. self.repo.path,
  8947. upstream=upstream_commit.decode(),
  8948. head=head_commit.decode(),
  8949. )
  8950. self.assertEqual(1, len(results))
  8951. status, commit_sha, _message = results[0]
  8952. self.assertEqual("-", status)
  8953. self.assertEqual(head_commit, commit_sha)
  8954. class GrepTests(PorcelainTestCase):
  8955. def test_basic_grep(self) -> None:
  8956. """Test basic pattern matching in files."""
  8957. # Create some test files
  8958. with open(os.path.join(self.repo_path, "foo.txt"), "w") as f:
  8959. f.write("hello world\ngoodbye world\n")
  8960. with open(os.path.join(self.repo_path, "bar.txt"), "w") as f:
  8961. f.write("foo bar\nbaz qux\n")
  8962. porcelain.add(self.repo, paths=["foo.txt", "bar.txt"])
  8963. porcelain.commit(self.repo, message=b"Add test files")
  8964. # Search for "world"
  8965. outstream = StringIO()
  8966. porcelain.grep(self.repo, "world", outstream=outstream)
  8967. output = outstream.getvalue().replace("\r\n", "\n")
  8968. self.assertEqual("foo.txt:hello world\nfoo.txt:goodbye world\n", output)
  8969. def test_grep_with_line_numbers(self) -> None:
  8970. """Test grep with line numbers."""
  8971. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8972. f.write("line one\nline two\nline three\n")
  8973. porcelain.add(self.repo, paths=["test.txt"])
  8974. porcelain.commit(self.repo, message=b"Add test file")
  8975. outstream = StringIO()
  8976. porcelain.grep(self.repo, "line", outstream=outstream, line_number=True)
  8977. output = outstream.getvalue().replace("\r\n", "\n")
  8978. self.assertEqual(
  8979. "test.txt:1:line one\ntest.txt:2:line two\ntest.txt:3:line three\n",
  8980. output,
  8981. )
  8982. def test_grep_case_insensitive(self) -> None:
  8983. """Test case-insensitive grep."""
  8984. with open(os.path.join(self.repo_path, "case.txt"), "w") as f:
  8985. f.write("Hello WORLD\nGoodbye world\n")
  8986. porcelain.add(self.repo, paths=["case.txt"])
  8987. porcelain.commit(self.repo, message=b"Add case file")
  8988. outstream = StringIO()
  8989. porcelain.grep(self.repo, "HELLO", outstream=outstream, ignore_case=True)
  8990. output = outstream.getvalue().replace("\r\n", "\n")
  8991. self.assertEqual("case.txt:Hello WORLD\n", output)
  8992. def test_grep_with_pathspec(self) -> None:
  8993. """Test grep with pathspec filtering."""
  8994. os.makedirs(os.path.join(self.repo_path, "subdir"))
  8995. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  8996. f.write("pattern match\n")
  8997. with open(os.path.join(self.repo_path, "subdir", "file2.txt"), "w") as f:
  8998. f.write("pattern match\n")
  8999. porcelain.add(self.repo, paths=["file1.txt", "subdir/file2.txt"])
  9000. porcelain.commit(self.repo, message=b"Add files")
  9001. # Search only in subdir
  9002. outstream = StringIO()
  9003. porcelain.grep(self.repo, "pattern", outstream=outstream, pathspecs=["subdir/"])
  9004. output = outstream.getvalue().replace("\r\n", "\n")
  9005. self.assertEqual("subdir/file2.txt:pattern match\n", output)
  9006. def test_grep_no_matches(self) -> None:
  9007. """Test grep with no matches."""
  9008. with open(os.path.join(self.repo_path, "empty.txt"), "w") as f:
  9009. f.write("nothing to see here\n")
  9010. porcelain.add(self.repo, paths=["empty.txt"])
  9011. porcelain.commit(self.repo, message=b"Add empty file")
  9012. outstream = StringIO()
  9013. porcelain.grep(self.repo, "nonexistent", outstream=outstream)
  9014. output = outstream.getvalue()
  9015. self.assertEqual("", output)
  9016. def test_grep_regex_pattern(self) -> None:
  9017. """Test grep with regex patterns."""
  9018. with open(os.path.join(self.repo_path, "regex.txt"), "w") as f:
  9019. f.write("test123\ntest456\nnotest\n")
  9020. porcelain.add(self.repo, paths=["regex.txt"])
  9021. porcelain.commit(self.repo, message=b"Add regex file")
  9022. # Search for "test" followed by digits
  9023. outstream = StringIO()
  9024. porcelain.grep(self.repo, r"test\d+", outstream=outstream)
  9025. output = outstream.getvalue().replace("\r\n", "\n")
  9026. self.assertEqual("regex.txt:test123\nregex.txt:test456\n", output)
  9027. def test_grep_invalid_pattern(self) -> None:
  9028. """Test grep with invalid regex pattern."""
  9029. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  9030. f.write("test\n")
  9031. porcelain.add(self.repo, paths=["test.txt"])
  9032. porcelain.commit(self.repo, message=b"Add test file")
  9033. outstream = StringIO()
  9034. with self.assertRaises(ValueError):
  9035. porcelain.grep(self.repo, "[invalid", outstream=outstream)
  9036. def test_grep_no_head(self) -> None:
  9037. """Test grep fails when there's no HEAD commit."""
  9038. # Create a fresh repo with no commits
  9039. empty_repo_path = os.path.join(self.test_dir, "empty_repo")
  9040. empty_repo = Repo.init(empty_repo_path, mkdir=True)
  9041. self.addCleanup(empty_repo.close)
  9042. outstream = StringIO()
  9043. with self.assertRaises(ValueError):
  9044. porcelain.grep(empty_repo, "pattern", outstream=outstream)
  9045. class ReplaceListTests(PorcelainTestCase):
  9046. def test_empty(self) -> None:
  9047. """Test listing replacements when there are none."""
  9048. replacements = porcelain.replace_list(self.repo)
  9049. self.assertEqual([], replacements)
  9050. def test_list_replacements(self) -> None:
  9051. """Test listing replacement refs."""
  9052. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9053. self.repo[b"HEAD"] = c1.id
  9054. # Create a replacement
  9055. porcelain.replace_create(self.repo, c1.id, c2.id)
  9056. # List replacements
  9057. replacements = porcelain.replace_list(self.repo)
  9058. self.assertEqual(1, len(replacements))
  9059. self.assertEqual((c1.id, c2.id), replacements[0])
  9060. class ReplaceCreateTests(PorcelainTestCase):
  9061. def test_create_replacement(self) -> None:
  9062. """Test creating a replacement ref."""
  9063. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9064. self.repo[b"HEAD"] = c1.id
  9065. # Create a replacement
  9066. porcelain.replace_create(self.repo, c1.id, c2.id)
  9067. # Verify the replacement ref was created (c1.id is already 40-char hex bytes)
  9068. replace_ref = b"refs/replace/" + c1.id
  9069. self.assertIn(replace_ref, self.repo.refs)
  9070. self.assertEqual(c2.id, self.repo.refs[replace_ref])
  9071. def test_create_replacement_with_bytes(self) -> None:
  9072. """Test creating a replacement ref with bytes arguments."""
  9073. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9074. self.repo[b"HEAD"] = c1.id
  9075. # Create a replacement using bytes arguments
  9076. porcelain.replace_create(self.repo, c1.id, c2.id)
  9077. # Verify the replacement ref was created
  9078. replace_ref = b"refs/replace/" + c1.id
  9079. self.assertIn(replace_ref, self.repo.refs)
  9080. self.assertEqual(c2.id, self.repo.refs[replace_ref])
  9081. class ReplaceDeleteTests(PorcelainTestCase):
  9082. def test_delete_replacement(self) -> None:
  9083. """Test deleting a replacement ref."""
  9084. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9085. self.repo[b"HEAD"] = c1.id
  9086. # Create a replacement
  9087. porcelain.replace_create(self.repo, c1.id, c2.id)
  9088. # Verify it exists
  9089. replacements = porcelain.replace_list(self.repo)
  9090. self.assertEqual(1, len(replacements))
  9091. # Delete the replacement
  9092. porcelain.replace_delete(self.repo, c1.id)
  9093. # Verify it's gone
  9094. replacements = porcelain.replace_list(self.repo)
  9095. self.assertEqual(0, len(replacements))
  9096. def test_delete_replacement_with_bytes(self) -> None:
  9097. """Test deleting a replacement ref with bytes argument."""
  9098. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9099. self.repo[b"HEAD"] = c1.id
  9100. # Create a replacement
  9101. porcelain.replace_create(self.repo, c1.id, c2.id)
  9102. # Delete using bytes argument
  9103. porcelain.replace_delete(self.repo, c1.id)
  9104. # Verify it's gone
  9105. replacements = porcelain.replace_list(self.repo)
  9106. self.assertEqual(0, len(replacements))
  9107. def test_delete_nonexistent_replacement(self) -> None:
  9108. """Test deleting a replacement ref that doesn't exist raises KeyError."""
  9109. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9110. self.repo[b"HEAD"] = c1.id
  9111. # Try to delete a non-existent replacement
  9112. with self.assertRaises(KeyError):
  9113. porcelain.replace_delete(self.repo, c1.id)
  9114. class GitReflogActionTests(PorcelainTestCase):
  9115. """Tests for GIT_REFLOG_ACTION environment variable support."""
  9116. def test_reset_with_git_reflog_action(self) -> None:
  9117. """Test that reset respects GIT_REFLOG_ACTION environment variable."""
  9118. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9119. self.repo.refs[b"HEAD"] = c2.id
  9120. # Set GIT_REFLOG_ACTION environment variable
  9121. self.overrideEnv("GIT_REFLOG_ACTION", "custom reset action")
  9122. # Reset to c1
  9123. porcelain.reset(self.repo, "hard", c1.id.decode())
  9124. # Check reflog message - HEAD is a symref to refs/heads/master
  9125. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/master"))
  9126. self.assertEqual(1, len(entries))
  9127. self.assertEqual(b"custom reset action", entries[0].message)
  9128. def test_commit_amend_with_git_reflog_action(self) -> None:
  9129. """Test that commit --amend respects GIT_REFLOG_ACTION environment variable."""
  9130. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9131. self.repo.refs[b"HEAD"] = c1.id
  9132. # Set GIT_REFLOG_ACTION environment variable
  9133. self.overrideEnv("GIT_REFLOG_ACTION", "custom amend action")
  9134. # Amend the commit
  9135. porcelain.commit(self.repo, b"amended message", amend=True)
  9136. # Check reflog message - HEAD is a symref to refs/heads/master
  9137. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/master"))
  9138. self.assertEqual(1, len(entries))
  9139. self.assertEqual(b"custom amend action", entries[0].message)
  9140. def test_branch_create_with_git_reflog_action(self) -> None:
  9141. """Test that branch_create respects GIT_REFLOG_ACTION environment variable."""
  9142. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9143. self.repo.refs[b"HEAD"] = c1.id
  9144. # Set GIT_REFLOG_ACTION environment variable
  9145. self.overrideEnv("GIT_REFLOG_ACTION", "custom branch action")
  9146. # Create a new branch
  9147. porcelain.branch_create(self.repo, b"test-branch")
  9148. # Check reflog message
  9149. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/test-branch"))
  9150. self.assertEqual(1, len(entries))
  9151. self.assertEqual(b"custom branch action", entries[0].message)
  9152. def test_reset_without_git_reflog_action(self) -> None:
  9153. """Test that reset uses default message when GIT_REFLOG_ACTION is not set."""
  9154. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9155. self.repo.refs[b"HEAD"] = c2.id
  9156. # Reset to c1 without GIT_REFLOG_ACTION
  9157. porcelain.reset(self.repo, "hard", c1.id.decode())
  9158. # Check reflog message contains default format - HEAD is a symref to refs/heads/master
  9159. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/master"))
  9160. self.assertEqual(1, len(entries))
  9161. self.assertTrue(entries[0].message.startswith(b"reset: moving to"))
  9162. def test_branch_create_without_git_reflog_action(self) -> None:
  9163. """Test that branch_create uses default message when GIT_REFLOG_ACTION is not set."""
  9164. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9165. self.repo.refs[b"HEAD"] = c1.id
  9166. # Create a new branch without GIT_REFLOG_ACTION
  9167. porcelain.branch_create(self.repo, b"test-branch")
  9168. # Check reflog message contains default format
  9169. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/test-branch"))
  9170. self.assertEqual(1, len(entries))
  9171. self.assertTrue(entries[0].message.startswith(b"branch: Created from"))
  9172. class PorcelainMailinfoTests(TestCase):
  9173. """Tests for porcelain.mailinfo function."""
  9174. def test_mailinfo_basic(self) -> None:
  9175. """Test basic mailinfo functionality."""
  9176. from io import BytesIO
  9177. email_content = b"""From: Test User <test@example.com>
  9178. Subject: [PATCH] Add feature
  9179. Date: Mon, 1 Jan 2024 12:00:00 +0000
  9180. Commit message here.
  9181. ---
  9182. diff --git a/file.txt b/file.txt
  9183. """
  9184. result = porcelain.mailinfo(BytesIO(email_content))
  9185. self.assertEqual("Test User", result.author_name)
  9186. self.assertEqual("test@example.com", result.author_email)
  9187. self.assertEqual("Add feature", result.subject)
  9188. self.assertIn("Commit message here.", result.message)
  9189. self.assertIn("diff --git", result.patch)
  9190. def test_mailinfo_write_to_files(self) -> None:
  9191. """Test mailinfo writing message and patch to files."""
  9192. from io import BytesIO
  9193. email_content = b"""From: Test <test@example.com>
  9194. Subject: Test
  9195. Message content
  9196. ---
  9197. Patch content
  9198. """
  9199. with tempfile.TemporaryDirectory() as tmpdir:
  9200. msg_file = os.path.join(tmpdir, "msg")
  9201. patch_file = os.path.join(tmpdir, "patch")
  9202. result = porcelain.mailinfo(
  9203. BytesIO(email_content), msg_file=msg_file, patch_file=patch_file
  9204. )
  9205. # Check that files were written
  9206. self.assertTrue(os.path.exists(msg_file))
  9207. self.assertTrue(os.path.exists(patch_file))
  9208. # Check file contents
  9209. with open(msg_file) as f:
  9210. msg_content = f.read()
  9211. self.assertIn("Message content", msg_content)
  9212. with open(patch_file) as f:
  9213. patch_content = f.read()
  9214. self.assertIn("Patch content", patch_content)
  9215. # Check return value
  9216. self.assertEqual("Test", result.subject)
  9217. def test_mailinfo_with_options(self) -> None:
  9218. """Test mailinfo with various options."""
  9219. from io import BytesIO
  9220. email_content = b"""From: Test <test@example.com>
  9221. Subject: [RFC][PATCH] Feature
  9222. Message-ID: <id@example.com>
  9223. Text before scissors
  9224. -- >8 --
  9225. Text after scissors
  9226. """
  9227. # Test with keep_non_patch, scissors, and message_id
  9228. result = porcelain.mailinfo(
  9229. BytesIO(email_content),
  9230. keep_non_patch=True,
  9231. scissors=True,
  9232. message_id=True,
  9233. )
  9234. self.assertEqual("[RFC] Feature", result.subject)
  9235. self.assertIn("Text after scissors", result.message)
  9236. self.assertNotIn("Text before scissors", result.message)
  9237. self.assertIn("Message-ID:", result.message)
  9238. def test_mailinfo_from_file_path(self) -> None:
  9239. """Test mailinfo reading from file path."""
  9240. email_content = b"""From: Test <test@example.com>
  9241. Subject: Test
  9242. Body
  9243. """
  9244. with tempfile.TemporaryDirectory() as tmpdir:
  9245. email_path = os.path.join(tmpdir, "email.txt")
  9246. with open(email_path, "wb") as f:
  9247. f.write(email_content)
  9248. result = porcelain.mailinfo(input_path=email_path)
  9249. self.assertEqual("Test", result.subject)
  9250. self.assertEqual("test@example.com", result.author_email)