2
0

test_porcelain.py 321 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838
  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. signoff=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. signoff=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 signoff=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 signoff=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. signoff=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 signoff=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 signoff=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. signoff=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. class TimezoneTests(PorcelainTestCase):
  754. def put_envs(self, value) -> None:
  755. self.overrideEnv("GIT_AUTHOR_DATE", value)
  756. self.overrideEnv("GIT_COMMITTER_DATE", value)
  757. def fallback(self, value) -> None:
  758. self.put_envs(value)
  759. self.assertRaises(porcelain.TimezoneFormatError, porcelain.get_user_timezones)
  760. def test_internal_format(self) -> None:
  761. self.put_envs("0 +0500")
  762. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  763. def test_rfc_2822(self) -> None:
  764. self.put_envs("Mon, 20 Nov 1995 19:12:08 -0500")
  765. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  766. self.put_envs("Mon, 20 Nov 1995 19:12:08")
  767. self.assertTupleEqual((0, 0), porcelain.get_user_timezones())
  768. def test_iso8601(self) -> None:
  769. self.put_envs("1995-11-20T19:12:08-0501")
  770. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  771. self.put_envs("1995-11-20T19:12:08+0501")
  772. self.assertTupleEqual((18060, 18060), porcelain.get_user_timezones())
  773. self.put_envs("1995-11-20T19:12:08-05:01")
  774. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  775. self.put_envs("1995-11-20 19:12:08-05")
  776. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  777. # https://github.com/git/git/blob/96b2d4fa927c5055adc5b1d08f10a5d7352e2989/t/t6300-for-each-ref.sh#L128
  778. self.put_envs("2006-07-03 17:18:44 +0200")
  779. self.assertTupleEqual((7200, 7200), porcelain.get_user_timezones())
  780. def test_missing_or_malformed(self) -> None:
  781. # TODO: add more here
  782. self.fallback("0 + 0500")
  783. self.fallback("a +0500")
  784. self.fallback("1995-11-20T19:12:08")
  785. self.fallback("1995-11-20T19:12:08-05:")
  786. self.fallback("1995.11.20")
  787. self.fallback("11/20/1995")
  788. self.fallback("20.11.1995")
  789. def test_different_envs(self) -> None:
  790. self.overrideEnv("GIT_AUTHOR_DATE", "0 +0500")
  791. self.overrideEnv("GIT_COMMITTER_DATE", "0 +0501")
  792. self.assertTupleEqual((18000, 18060), porcelain.get_user_timezones())
  793. def test_no_envs(self) -> None:
  794. local_timezone = time.localtime().tm_gmtoff
  795. self.put_envs("0 +0500")
  796. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  797. self.overrideEnv("GIT_COMMITTER_DATE", None)
  798. self.assertTupleEqual((18000, local_timezone), porcelain.get_user_timezones())
  799. self.put_envs("0 +0500")
  800. self.overrideEnv("GIT_AUTHOR_DATE", None)
  801. self.assertTupleEqual((local_timezone, 18000), porcelain.get_user_timezones())
  802. self.put_envs("0 +0500")
  803. self.overrideEnv("GIT_AUTHOR_DATE", None)
  804. self.overrideEnv("GIT_COMMITTER_DATE", None)
  805. self.assertTupleEqual(
  806. (local_timezone, local_timezone), porcelain.get_user_timezones()
  807. )
  808. class CleanTests(PorcelainTestCase):
  809. def put_files(self, tracked, ignored, untracked, empty_dirs) -> None:
  810. """Put the described files in the wd."""
  811. all_files = tracked | ignored | untracked
  812. for file_path in all_files:
  813. abs_path = os.path.join(self.repo.path, file_path)
  814. # File may need to be written in a dir that doesn't exist yet, so
  815. # create the parent dir(s) as necessary
  816. parent_dir = os.path.dirname(abs_path)
  817. try:
  818. os.makedirs(parent_dir)
  819. except FileExistsError:
  820. pass
  821. with open(abs_path, "w") as f:
  822. f.write("")
  823. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  824. f.writelines(ignored)
  825. for dir_path in empty_dirs:
  826. os.mkdir(os.path.join(self.repo.path, "empty_dir"))
  827. files_to_add = [os.path.join(self.repo.path, t) for t in tracked]
  828. porcelain.add(repo=self.repo.path, paths=files_to_add)
  829. porcelain.commit(repo=self.repo.path, message="init commit")
  830. def assert_wd(self, expected_paths) -> None:
  831. """Assert paths of files and dirs in wd are same as expected_paths."""
  832. control_dir_rel = os.path.relpath(self.repo._controldir, self.repo.path)
  833. # normalize paths to simplify comparison across platforms
  834. found_paths = {
  835. os.path.normpath(p)
  836. for p in flat_walk_dir(self.repo.path)
  837. if not p.split(os.sep)[0] == control_dir_rel
  838. }
  839. norm_expected_paths = {os.path.normpath(p) for p in expected_paths}
  840. self.assertEqual(found_paths, norm_expected_paths)
  841. def test_from_root(self) -> None:
  842. self.put_files(
  843. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  844. ignored={"ignored_file"},
  845. untracked={
  846. "untracked_file",
  847. "tracked_dir/untracked_dir/untracked_file",
  848. "untracked_dir/untracked_dir/untracked_file",
  849. },
  850. empty_dirs={"empty_dir"},
  851. )
  852. porcelain.clean(repo=self.repo.path, target_dir=self.repo.path)
  853. self.assert_wd(
  854. {
  855. "tracked_file",
  856. "tracked_dir/tracked_file",
  857. ".gitignore",
  858. "ignored_file",
  859. "tracked_dir",
  860. }
  861. )
  862. def test_from_subdir(self) -> None:
  863. self.put_files(
  864. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  865. ignored={"ignored_file"},
  866. untracked={
  867. "untracked_file",
  868. "tracked_dir/untracked_dir/untracked_file",
  869. "untracked_dir/untracked_dir/untracked_file",
  870. },
  871. empty_dirs={"empty_dir"},
  872. )
  873. porcelain.clean(
  874. repo=self.repo,
  875. target_dir=os.path.join(self.repo.path, "untracked_dir"),
  876. )
  877. self.assert_wd(
  878. {
  879. "tracked_file",
  880. "tracked_dir/tracked_file",
  881. ".gitignore",
  882. "ignored_file",
  883. "untracked_file",
  884. "tracked_dir/untracked_dir/untracked_file",
  885. "empty_dir",
  886. "untracked_dir",
  887. "tracked_dir",
  888. "tracked_dir/untracked_dir",
  889. }
  890. )
  891. class CloneTests(PorcelainTestCase):
  892. def test_simple_local(self) -> None:
  893. f1_1 = make_object(Blob, data=b"f1")
  894. commit_spec = [[1], [2, 1], [3, 1, 2]]
  895. trees = {
  896. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  897. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  898. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  899. }
  900. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  901. self.repo.refs[b"refs/heads/master"] = c3.id
  902. self.repo.refs[b"refs/tags/foo"] = c3.id
  903. target_path = tempfile.mkdtemp()
  904. errstream = BytesIO()
  905. self.addCleanup(shutil.rmtree, target_path)
  906. r = porcelain.clone(
  907. self.repo.path, target_path, checkout=False, errstream=errstream
  908. )
  909. self.addCleanup(r.close)
  910. self.assertEqual(r.path, target_path)
  911. target_repo = Repo(target_path)
  912. self.addCleanup(target_repo.close)
  913. self.assertEqual(0, len(target_repo.open_index()))
  914. self.assertEqual(c3.id, target_repo.refs[b"refs/tags/foo"])
  915. self.assertNotIn(b"f1", os.listdir(target_path))
  916. self.assertNotIn(b"f2", os.listdir(target_path))
  917. c = r.get_config()
  918. encoded_path = self.repo.path
  919. if not isinstance(encoded_path, bytes):
  920. encoded_path_bytes = encoded_path.encode("utf-8")
  921. else:
  922. encoded_path_bytes = encoded_path
  923. self.assertEqual(encoded_path_bytes, c.get((b"remote", b"origin"), b"url"))
  924. self.assertEqual(
  925. b"+refs/heads/*:refs/remotes/origin/*",
  926. c.get((b"remote", b"origin"), b"fetch"),
  927. )
  928. def test_simple_local_with_checkout(self) -> None:
  929. f1_1 = make_object(Blob, data=b"f1")
  930. commit_spec = [[1], [2, 1], [3, 1, 2]]
  931. trees = {
  932. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  933. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  934. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  935. }
  936. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  937. self.repo.refs[b"refs/heads/master"] = c3.id
  938. target_path = tempfile.mkdtemp()
  939. errstream = BytesIO()
  940. self.addCleanup(shutil.rmtree, target_path)
  941. with porcelain.clone(
  942. self.repo.path, target_path, checkout=True, errstream=errstream
  943. ) as r:
  944. self.assertEqual(r.path, target_path)
  945. with Repo(target_path) as r:
  946. self.assertEqual(r.head(), c3.id)
  947. self.assertIn("f1", os.listdir(target_path))
  948. self.assertIn("f2", os.listdir(target_path))
  949. def test_bare_local_with_checkout(self) -> None:
  950. f1_1 = make_object(Blob, data=b"f1")
  951. commit_spec = [[1], [2, 1], [3, 1, 2]]
  952. trees = {
  953. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  954. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  955. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  956. }
  957. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  958. self.repo.refs[b"refs/heads/master"] = c3.id
  959. target_path = tempfile.mkdtemp()
  960. errstream = BytesIO()
  961. self.addCleanup(shutil.rmtree, target_path)
  962. with porcelain.clone(
  963. self.repo.path, target_path, bare=True, errstream=errstream
  964. ) as r:
  965. self.assertEqual(r.path, target_path)
  966. with Repo(target_path) as r:
  967. r.head()
  968. self.assertRaises(NoIndexPresent, r.open_index)
  969. self.assertNotIn(b"f1", os.listdir(target_path))
  970. self.assertNotIn(b"f2", os.listdir(target_path))
  971. def test_no_checkout_with_bare(self) -> None:
  972. f1_1 = make_object(Blob, data=b"f1")
  973. commit_spec = [[1]]
  974. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  975. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  976. self.repo.refs[b"refs/heads/master"] = c1.id
  977. self.repo.refs[b"HEAD"] = c1.id
  978. target_path = tempfile.mkdtemp()
  979. errstream = BytesIO()
  980. self.addCleanup(shutil.rmtree, target_path)
  981. self.assertRaises(
  982. porcelain.Error,
  983. porcelain.clone,
  984. self.repo.path,
  985. target_path,
  986. checkout=True,
  987. bare=True,
  988. errstream=errstream,
  989. )
  990. def test_no_head_no_checkout(self) -> None:
  991. f1_1 = make_object(Blob, data=b"f1")
  992. commit_spec = [[1]]
  993. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  994. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  995. self.repo.refs[b"refs/heads/master"] = c1.id
  996. target_path = tempfile.mkdtemp()
  997. self.addCleanup(shutil.rmtree, target_path)
  998. errstream = BytesIO()
  999. r = porcelain.clone(
  1000. self.repo.path, target_path, checkout=True, errstream=errstream
  1001. )
  1002. r.close()
  1003. def test_no_head_no_checkout_outstream_errstream_autofallback(self) -> None:
  1004. f1_1 = make_object(Blob, data=b"f1")
  1005. commit_spec = [[1]]
  1006. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1007. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1008. self.repo.refs[b"refs/heads/master"] = c1.id
  1009. target_path = tempfile.mkdtemp()
  1010. self.addCleanup(shutil.rmtree, target_path)
  1011. errstream = porcelain.NoneStream()
  1012. r = porcelain.clone(
  1013. self.repo.path, target_path, checkout=True, errstream=errstream
  1014. )
  1015. r.close()
  1016. def test_source_broken(self) -> None:
  1017. with tempfile.TemporaryDirectory() as parent:
  1018. target_path = os.path.join(parent, "target")
  1019. self.assertRaises(
  1020. Exception, porcelain.clone, "/nonexistent/repo", target_path
  1021. )
  1022. self.assertFalse(os.path.exists(target_path))
  1023. def test_fetch_symref(self) -> None:
  1024. f1_1 = make_object(Blob, data=b"f1")
  1025. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1026. [c1] = build_commit_graph(self.repo.object_store, [[1]], trees)
  1027. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/else")
  1028. self.repo.refs[b"refs/heads/else"] = c1.id
  1029. target_path = tempfile.mkdtemp()
  1030. errstream = BytesIO()
  1031. self.addCleanup(shutil.rmtree, target_path)
  1032. r = porcelain.clone(
  1033. self.repo.path, target_path, checkout=False, errstream=errstream
  1034. )
  1035. self.addCleanup(r.close)
  1036. self.assertEqual(r.path, target_path)
  1037. target_repo = Repo(target_path)
  1038. self.addCleanup(target_repo.close)
  1039. self.assertEqual(0, len(target_repo.open_index()))
  1040. self.assertEqual(c1.id, target_repo.refs[b"refs/heads/else"])
  1041. self.assertEqual(c1.id, target_repo.refs[b"HEAD"])
  1042. self.assertEqual(
  1043. {
  1044. b"HEAD": b"refs/heads/else",
  1045. b"refs/remotes/origin/HEAD": b"refs/remotes/origin/else",
  1046. },
  1047. target_repo.refs.get_symrefs(),
  1048. )
  1049. def test_detached_head(self) -> None:
  1050. f1_1 = make_object(Blob, data=b"f1")
  1051. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1052. trees = {
  1053. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1054. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1055. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1056. }
  1057. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1058. self.repo.refs[b"refs/heads/master"] = c2.id
  1059. self.repo.refs.remove_if_equals(b"HEAD", None)
  1060. self.repo.refs[b"HEAD"] = c3.id
  1061. target_path = tempfile.mkdtemp()
  1062. self.addCleanup(shutil.rmtree, target_path)
  1063. errstream = porcelain.NoneStream()
  1064. with porcelain.clone(
  1065. self.repo.path, target_path, checkout=True, errstream=errstream
  1066. ) as r:
  1067. self.assertEqual(c3.id, r.refs[b"HEAD"])
  1068. def test_clone_pathlib(self) -> None:
  1069. from pathlib import Path
  1070. f1_1 = make_object(Blob, data=b"f1")
  1071. commit_spec = [[1]]
  1072. trees = {1: [(b"f1", f1_1)]}
  1073. c1 = build_commit_graph(self.repo.object_store, commit_spec, trees)[0]
  1074. self.repo.refs[b"refs/heads/master"] = c1.id
  1075. target_dir = tempfile.mkdtemp()
  1076. self.addCleanup(shutil.rmtree, target_dir)
  1077. target_path = Path(target_dir) / "clone_repo"
  1078. errstream = BytesIO()
  1079. r = porcelain.clone(
  1080. self.repo.path, target_path, checkout=False, errstream=errstream
  1081. )
  1082. self.addCleanup(r.close)
  1083. self.assertEqual(r.path, str(target_path))
  1084. self.assertTrue(os.path.exists(str(target_path)))
  1085. def test_clone_with_recurse_submodules(self) -> None:
  1086. # Create a submodule repository
  1087. sub_repo_path = tempfile.mkdtemp()
  1088. self.addCleanup(shutil.rmtree, sub_repo_path)
  1089. sub_repo = Repo.init(sub_repo_path)
  1090. self.addCleanup(sub_repo.close)
  1091. # Add a file to the submodule repo
  1092. sub_file = os.path.join(sub_repo_path, "subfile.txt")
  1093. with open(sub_file, "w") as f:
  1094. f.write("submodule content")
  1095. porcelain.add(sub_repo, paths=[sub_file])
  1096. sub_commit = porcelain.commit(
  1097. sub_repo,
  1098. message=b"Initial submodule commit",
  1099. author=b"Test Author <test@example.com>",
  1100. committer=b"Test Committer <test@example.com>",
  1101. )
  1102. # Create main repository with submodule
  1103. main_file = os.path.join(self.repo.path, "main.txt")
  1104. with open(main_file, "w") as f:
  1105. f.write("main content")
  1106. porcelain.add(self.repo, paths=[main_file])
  1107. porcelain.submodule_add(self.repo, sub_repo_path, "sub")
  1108. # Manually add the submodule to the index since submodule_add doesn't do it
  1109. # when the repository is local (to maintain backward compatibility)
  1110. from dulwich.index import IndexEntry
  1111. from dulwich.objects import S_IFGITLINK
  1112. index = self.repo.open_index()
  1113. index[b"sub"] = IndexEntry(
  1114. ctime=0,
  1115. mtime=0,
  1116. dev=0,
  1117. ino=0,
  1118. mode=S_IFGITLINK,
  1119. uid=0,
  1120. gid=0,
  1121. size=0,
  1122. sha=sub_commit,
  1123. flags=0,
  1124. )
  1125. index.write()
  1126. porcelain.add(self.repo, paths=[".gitmodules"])
  1127. porcelain.commit(
  1128. self.repo,
  1129. message=b"Add submodule",
  1130. author=b"Test Author <test@example.com>",
  1131. committer=b"Test Committer <test@example.com>",
  1132. )
  1133. # Clone with recurse_submodules
  1134. target_path = tempfile.mkdtemp()
  1135. self.addCleanup(shutil.rmtree, target_path)
  1136. cloned = porcelain.clone(
  1137. self.repo.path,
  1138. target_path,
  1139. recurse_submodules=True,
  1140. )
  1141. self.addCleanup(cloned.close)
  1142. # Check main file exists
  1143. cloned_main = os.path.join(target_path, "main.txt")
  1144. self.assertTrue(os.path.exists(cloned_main))
  1145. with open(cloned_main) as f:
  1146. self.assertEqual(f.read(), "main content")
  1147. # Check submodule file exists
  1148. cloned_sub_file = os.path.join(target_path, "sub", "subfile.txt")
  1149. self.assertTrue(os.path.exists(cloned_sub_file))
  1150. with open(cloned_sub_file) as f:
  1151. self.assertEqual(f.read(), "submodule content")
  1152. class InitTests(TestCase):
  1153. def test_non_bare(self) -> None:
  1154. repo_dir = tempfile.mkdtemp()
  1155. self.addCleanup(shutil.rmtree, repo_dir)
  1156. porcelain.init(repo_dir)
  1157. def test_bare(self) -> None:
  1158. repo_dir = tempfile.mkdtemp()
  1159. self.addCleanup(shutil.rmtree, repo_dir)
  1160. porcelain.init(repo_dir, bare=True)
  1161. def test_init_pathlib(self) -> None:
  1162. from pathlib import Path
  1163. repo_dir = tempfile.mkdtemp()
  1164. self.addCleanup(shutil.rmtree, repo_dir)
  1165. repo_path = Path(repo_dir)
  1166. # Test non-bare repo with pathlib
  1167. repo = porcelain.init(repo_path)
  1168. self.assertTrue(os.path.exists(os.path.join(repo_dir, ".git")))
  1169. repo.close()
  1170. def test_init_bare_pathlib(self) -> None:
  1171. from pathlib import Path
  1172. repo_dir = tempfile.mkdtemp()
  1173. self.addCleanup(shutil.rmtree, repo_dir)
  1174. repo_path = Path(repo_dir)
  1175. # Test bare repo with pathlib
  1176. repo = porcelain.init(repo_path, bare=True)
  1177. self.assertTrue(os.path.exists(os.path.join(repo_dir, "refs")))
  1178. repo.close()
  1179. class AddTests(PorcelainTestCase):
  1180. def test_add_default_paths(self) -> None:
  1181. # create a file for initial commit
  1182. fullpath = os.path.join(self.repo.path, "blah")
  1183. with open(fullpath, "w") as f:
  1184. f.write("\n")
  1185. porcelain.add(repo=self.repo.path, paths=[fullpath])
  1186. porcelain.commit(
  1187. repo=self.repo.path,
  1188. message=b"test",
  1189. author=b"test <email>",
  1190. committer=b"test <email>",
  1191. )
  1192. # Add a second test file and a file in a directory
  1193. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1194. f.write("\n")
  1195. os.mkdir(os.path.join(self.repo.path, "adir"))
  1196. with open(os.path.join(self.repo.path, "adir", "afile"), "w") as f:
  1197. f.write("\n")
  1198. cwd = os.getcwd()
  1199. self.addCleanup(os.chdir, cwd)
  1200. os.chdir(self.repo.path)
  1201. self.assertEqual({"foo", "blah", "adir", ".git"}, set(os.listdir(".")))
  1202. added, ignored = porcelain.add(self.repo.path)
  1203. # Normalize paths to use forward slashes for comparison
  1204. added_normalized = [path.replace(os.sep, "/") for path in added]
  1205. self.assertEqual(
  1206. (added_normalized, ignored),
  1207. (["foo", "adir/afile"], set()),
  1208. )
  1209. # Check that foo was added and nothing in .git was modified
  1210. index = self.repo.open_index()
  1211. self.assertEqual(sorted(index), [b"adir/afile", b"blah", b"foo"])
  1212. def test_add_default_paths_subdir(self) -> None:
  1213. os.mkdir(os.path.join(self.repo.path, "foo"))
  1214. with open(os.path.join(self.repo.path, "blah"), "w") as f:
  1215. f.write("\n")
  1216. with open(os.path.join(self.repo.path, "foo", "blie"), "w") as f:
  1217. f.write("\n")
  1218. cwd = os.getcwd()
  1219. self.addCleanup(os.chdir, cwd)
  1220. os.chdir(os.path.join(self.repo.path, "foo"))
  1221. porcelain.add(repo=self.repo.path)
  1222. porcelain.commit(
  1223. repo=self.repo.path,
  1224. message=b"test",
  1225. author=b"test <email>",
  1226. committer=b"test <email>",
  1227. )
  1228. index = self.repo.open_index()
  1229. # After fix: add() with no paths should behave like git add -A (add everything)
  1230. self.assertEqual(sorted(index), [b"blah", b"foo/blie"])
  1231. def test_add_file(self) -> None:
  1232. fullpath = os.path.join(self.repo.path, "foo")
  1233. with open(fullpath, "w") as f:
  1234. f.write("BAR")
  1235. porcelain.add(self.repo.path, paths=[fullpath])
  1236. self.assertIn(b"foo", self.repo.open_index())
  1237. def test_add_ignored(self) -> None:
  1238. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1239. f.write("foo\nsubdir/")
  1240. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1241. f.write("BAR")
  1242. with open(os.path.join(self.repo.path, "bar"), "w") as f:
  1243. f.write("BAR")
  1244. os.mkdir(os.path.join(self.repo.path, "subdir"))
  1245. with open(os.path.join(self.repo.path, "subdir", "baz"), "w") as f:
  1246. f.write("BAZ")
  1247. (added, ignored) = porcelain.add(
  1248. self.repo.path,
  1249. paths=[
  1250. os.path.join(self.repo.path, "foo"),
  1251. os.path.join(self.repo.path, "bar"),
  1252. os.path.join(self.repo.path, "subdir"),
  1253. ],
  1254. )
  1255. self.assertIn(b"bar", self.repo.open_index())
  1256. self.assertEqual({"bar"}, set(added))
  1257. self.assertEqual({"foo", "subdir/"}, ignored)
  1258. def test_add_from_ignored_directory(self) -> None:
  1259. # Test for issue #550 - adding files when cwd is in ignored directory
  1260. # Create .gitignore that ignores build/
  1261. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1262. f.write("build/\n")
  1263. # Create ignored directory
  1264. build_dir = os.path.join(self.repo.path, "build")
  1265. os.mkdir(build_dir)
  1266. # Create a file in the repo (not in ignored directory)
  1267. src_file = os.path.join(self.repo.path, "source.py")
  1268. with open(src_file, "w") as f:
  1269. f.write("print('hello')\n")
  1270. # Save current directory and change to ignored directory
  1271. original_cwd = os.getcwd()
  1272. try:
  1273. os.chdir(build_dir)
  1274. # Add file using absolute path from within ignored directory
  1275. (added, ignored) = porcelain.add(self.repo.path, paths=[src_file])
  1276. self.assertIn(b"source.py", self.repo.open_index())
  1277. self.assertEqual({"source.py"}, set(added))
  1278. finally:
  1279. os.chdir(original_cwd)
  1280. def test_add_file_absolute_path(self) -> None:
  1281. # Absolute paths are (not yet) supported
  1282. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1283. f.write("BAR")
  1284. porcelain.add(self.repo, paths=[os.path.join(self.repo.path, "foo")])
  1285. self.assertIn(b"foo", self.repo.open_index())
  1286. def test_add_not_in_repo(self) -> None:
  1287. with open(os.path.join(self.test_dir, "foo"), "w") as f:
  1288. f.write("BAR")
  1289. self.assertRaises(
  1290. ValueError,
  1291. porcelain.add,
  1292. self.repo,
  1293. paths=[os.path.join(self.test_dir, "foo")],
  1294. )
  1295. self.assertRaises(
  1296. (ValueError, FileNotFoundError),
  1297. porcelain.add,
  1298. self.repo,
  1299. paths=["../foo"],
  1300. )
  1301. self.assertEqual([], list(self.repo.open_index()))
  1302. def test_add_file_clrf_conversion(self) -> None:
  1303. from dulwich.index import IndexEntry
  1304. # Set the right configuration to the repo
  1305. c = self.repo.get_config()
  1306. c.set("core", "autocrlf", "input")
  1307. c.write_to_path()
  1308. # Add a file with CRLF line-ending
  1309. fullpath = os.path.join(self.repo.path, "foo")
  1310. with open(fullpath, "wb") as f:
  1311. f.write(b"line1\r\nline2")
  1312. porcelain.add(self.repo.path, paths=[fullpath])
  1313. # The line-endings should have been converted to LF
  1314. index = self.repo.open_index()
  1315. self.assertIn(b"foo", index)
  1316. entry = index[b"foo"]
  1317. assert isinstance(entry, IndexEntry)
  1318. blob = self.repo[entry.sha]
  1319. self.assertEqual(blob.data, b"line1\nline2")
  1320. def test_add_symlink_outside_repo(self) -> None:
  1321. """Test adding a symlink that points outside the repository."""
  1322. # Create a symlink pointing outside the repository
  1323. symlink_path = os.path.join(self.repo.path, "symlink_to_nowhere")
  1324. os.symlink("/nonexistent/path", symlink_path)
  1325. # Adding the symlink should succeed (matching Git's behavior)
  1326. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1327. # Should successfully add the symlink
  1328. self.assertIn("symlink_to_nowhere", added)
  1329. self.assertEqual(len(ignored), 0)
  1330. # Verify symlink is actually staged
  1331. index = self.repo.open_index()
  1332. self.assertIn(b"symlink_to_nowhere", index)
  1333. def test_add_symlink_to_file_inside_repo(self) -> None:
  1334. """Test adding a symlink that points to a file inside the repository."""
  1335. # Create a regular file
  1336. target_file = os.path.join(self.repo.path, "target.txt")
  1337. with open(target_file, "w") as f:
  1338. f.write("target content")
  1339. # Create a symlink to the file
  1340. symlink_path = os.path.join(self.repo.path, "link_to_target")
  1341. os.symlink("target.txt", symlink_path)
  1342. # Add both the target and the symlink
  1343. added, ignored = porcelain.add(
  1344. self.repo.path, paths=[target_file, symlink_path]
  1345. )
  1346. # Both should be added successfully
  1347. self.assertIn("target.txt", added)
  1348. self.assertIn("link_to_target", added)
  1349. self.assertEqual(len(ignored), 0)
  1350. # Verify both are in the index
  1351. index = self.repo.open_index()
  1352. self.assertIn(b"target.txt", index)
  1353. self.assertIn(b"link_to_target", index)
  1354. def test_add_symlink_to_directory_inside_repo(self) -> None:
  1355. """Test adding a symlink that points to a directory inside the repository."""
  1356. # Create a directory with some files
  1357. target_dir = os.path.join(self.repo.path, "target_dir")
  1358. os.mkdir(target_dir)
  1359. with open(os.path.join(target_dir, "file1.txt"), "w") as f:
  1360. f.write("content1")
  1361. with open(os.path.join(target_dir, "file2.txt"), "w") as f:
  1362. f.write("content2")
  1363. # Create a symlink to the directory
  1364. symlink_path = os.path.join(self.repo.path, "link_to_dir")
  1365. os.symlink("target_dir", symlink_path)
  1366. # Add the symlink
  1367. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1368. # When adding a symlink to a directory, it follows the symlink and adds contents
  1369. self.assertEqual(len(added), 2)
  1370. self.assertIn("link_to_dir/file1.txt", added)
  1371. self.assertIn("link_to_dir/file2.txt", added)
  1372. self.assertEqual(len(ignored), 0)
  1373. # Verify files are added through the symlink path
  1374. index = self.repo.open_index()
  1375. self.assertIn(b"link_to_dir/file1.txt", index)
  1376. self.assertIn(b"link_to_dir/file2.txt", index)
  1377. # The original target directory files are not added
  1378. self.assertNotIn(b"target_dir/file1.txt", index)
  1379. self.assertNotIn(b"target_dir/file2.txt", index)
  1380. def test_add_symlink_chain(self) -> None:
  1381. """Test adding a chain of symlinks (symlink to symlink)."""
  1382. # Create a regular file
  1383. target_file = os.path.join(self.repo.path, "original.txt")
  1384. with open(target_file, "w") as f:
  1385. f.write("original content")
  1386. # Create first symlink
  1387. first_link = os.path.join(self.repo.path, "link1")
  1388. os.symlink("original.txt", first_link)
  1389. # Create second symlink pointing to first
  1390. second_link = os.path.join(self.repo.path, "link2")
  1391. os.symlink("link1", second_link)
  1392. # Add all files
  1393. added, ignored = porcelain.add(
  1394. self.repo.path, paths=[target_file, first_link, second_link]
  1395. )
  1396. # All should be added
  1397. self.assertEqual(len(added), 3)
  1398. self.assertIn("original.txt", added)
  1399. self.assertIn("link1", added)
  1400. self.assertIn("link2", added)
  1401. # Verify all are in the index
  1402. index = self.repo.open_index()
  1403. self.assertIn(b"original.txt", index)
  1404. self.assertIn(b"link1", index)
  1405. self.assertIn(b"link2", index)
  1406. def test_add_broken_symlink(self) -> None:
  1407. """Test adding a broken symlink (points to non-existent target)."""
  1408. # Create a symlink to a non-existent file
  1409. broken_link = os.path.join(self.repo.path, "broken_link")
  1410. os.symlink("does_not_exist.txt", broken_link)
  1411. # Add the broken symlink
  1412. added, ignored = porcelain.add(self.repo.path, paths=[broken_link])
  1413. # Should be added successfully (Git tracks the symlink, not its target)
  1414. self.assertIn("broken_link", added)
  1415. self.assertEqual(len(ignored), 0)
  1416. # Verify it's in the index
  1417. index = self.repo.open_index()
  1418. self.assertIn(b"broken_link", index)
  1419. def test_add_symlink_relative_outside_repo(self) -> None:
  1420. """Test adding a symlink that uses '..' to point outside the repository."""
  1421. # Create a file outside the repo
  1422. outside_file = os.path.join(self.test_dir, "outside.txt")
  1423. with open(outside_file, "w") as f:
  1424. f.write("outside content")
  1425. # Create a symlink using relative path to go outside
  1426. symlink_path = os.path.join(self.repo.path, "link_outside")
  1427. os.symlink("../outside.txt", symlink_path)
  1428. # Add the symlink
  1429. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1430. # Should be added successfully
  1431. self.assertIn("link_outside", added)
  1432. self.assertEqual(len(ignored), 0)
  1433. # Verify it's in the index
  1434. index = self.repo.open_index()
  1435. self.assertIn(b"link_outside", index)
  1436. def test_add_symlink_absolute_to_system(self) -> None:
  1437. """Test adding a symlink with absolute path to system directory."""
  1438. # Create a symlink to a system directory
  1439. symlink_path = os.path.join(self.repo.path, "link_to_tmp")
  1440. if os.name == "nt":
  1441. # On Windows, use a system directory like TEMP
  1442. symlink_target = os.environ["TEMP"]
  1443. else:
  1444. # On Unix-like systems, use /tmp
  1445. symlink_target = "/tmp"
  1446. os.symlink(symlink_target, symlink_path)
  1447. # Adding a symlink to a directory outside the repo should raise ValueError
  1448. with self.assertRaises(ValueError) as cm:
  1449. porcelain.add(self.repo.path, paths=[symlink_path])
  1450. # Check that the error indicates the path is outside the repository
  1451. self.assertIn("is not in the subpath of", str(cm.exception))
  1452. def test_add_file_through_symlink(self) -> None:
  1453. """Test adding a file through a symlinked directory."""
  1454. # Create a directory with a file
  1455. real_dir = os.path.join(self.repo.path, "real_dir")
  1456. os.mkdir(real_dir)
  1457. real_file = os.path.join(real_dir, "file.txt")
  1458. with open(real_file, "w") as f:
  1459. f.write("content")
  1460. # Create a symlink to the directory
  1461. link_dir = os.path.join(self.repo.path, "link_dir")
  1462. os.symlink("real_dir", link_dir)
  1463. # Try to add the file through the symlink path
  1464. symlink_file_path = os.path.join(link_dir, "file.txt")
  1465. # This should add the real file, not create a new entry
  1466. added, ignored = porcelain.add(self.repo.path, paths=[symlink_file_path])
  1467. # The real file should be added
  1468. self.assertIn("real_dir/file.txt", added)
  1469. self.assertEqual(len(added), 1)
  1470. # Verify correct path in index
  1471. index = self.repo.open_index()
  1472. self.assertIn(b"real_dir/file.txt", index)
  1473. # Should not create a separate entry for the symlink path
  1474. self.assertNotIn(b"link_dir/file.txt", index)
  1475. def test_add_repo_path(self) -> None:
  1476. """Test adding the repository path itself should add all untracked files."""
  1477. # Create some untracked files
  1478. with open(os.path.join(self.repo.path, "file1.txt"), "w") as f:
  1479. f.write("content1")
  1480. with open(os.path.join(self.repo.path, "file2.txt"), "w") as f:
  1481. f.write("content2")
  1482. # Add the repository path itself
  1483. added, ignored = porcelain.add(self.repo.path, paths=[self.repo.path])
  1484. # Should add all untracked files, not stage './'
  1485. self.assertIn("file1.txt", added)
  1486. self.assertIn("file2.txt", added)
  1487. self.assertNotIn("./", added)
  1488. # Verify files are actually staged
  1489. index = self.repo.open_index()
  1490. self.assertIn(b"file1.txt", index)
  1491. self.assertIn(b"file2.txt", index)
  1492. def test_add_directory_contents(self) -> None:
  1493. """Test adding a directory adds all files within it."""
  1494. # Create a subdirectory with multiple files
  1495. subdir = os.path.join(self.repo.path, "subdir")
  1496. os.mkdir(subdir)
  1497. with open(os.path.join(subdir, "file1.txt"), "w") as f:
  1498. f.write("content1")
  1499. with open(os.path.join(subdir, "file2.txt"), "w") as f:
  1500. f.write("content2")
  1501. with open(os.path.join(subdir, "file3.txt"), "w") as f:
  1502. f.write("content3")
  1503. # Add the directory
  1504. added, ignored = porcelain.add(self.repo.path, paths=["subdir"])
  1505. # Should add all files in the directory
  1506. self.assertEqual(len(added), 3)
  1507. # Normalize paths to use forward slashes for comparison
  1508. added_normalized = [path.replace(os.sep, "/") for path in added]
  1509. self.assertIn("subdir/file1.txt", added_normalized)
  1510. self.assertIn("subdir/file2.txt", added_normalized)
  1511. self.assertIn("subdir/file3.txt", added_normalized)
  1512. # Verify files are actually staged
  1513. index = self.repo.open_index()
  1514. self.assertIn(b"subdir/file1.txt", index)
  1515. self.assertIn(b"subdir/file2.txt", index)
  1516. self.assertIn(b"subdir/file3.txt", index)
  1517. def test_add_nested_directories(self) -> None:
  1518. """Test adding a directory with nested subdirectories."""
  1519. # Create nested directory structure
  1520. dir1 = os.path.join(self.repo.path, "dir1")
  1521. dir2 = os.path.join(dir1, "dir2")
  1522. dir3 = os.path.join(dir2, "dir3")
  1523. os.makedirs(dir3)
  1524. # Add files at each level
  1525. with open(os.path.join(dir1, "file1.txt"), "w") as f:
  1526. f.write("level1")
  1527. with open(os.path.join(dir2, "file2.txt"), "w") as f:
  1528. f.write("level2")
  1529. with open(os.path.join(dir3, "file3.txt"), "w") as f:
  1530. f.write("level3")
  1531. # Add the top-level directory
  1532. added, ignored = porcelain.add(self.repo.path, paths=["dir1"])
  1533. # Should add all files recursively
  1534. self.assertEqual(len(added), 3)
  1535. # Normalize paths to use forward slashes for comparison
  1536. added_normalized = [path.replace(os.sep, "/") for path in added]
  1537. self.assertIn("dir1/file1.txt", added_normalized)
  1538. self.assertIn("dir1/dir2/file2.txt", added_normalized)
  1539. self.assertIn("dir1/dir2/dir3/file3.txt", added_normalized)
  1540. # Verify files are actually staged
  1541. index = self.repo.open_index()
  1542. self.assertIn(b"dir1/file1.txt", index)
  1543. self.assertIn(b"dir1/dir2/file2.txt", index)
  1544. self.assertIn(b"dir1/dir2/dir3/file3.txt", index)
  1545. def test_add_directory_with_tracked_files(self) -> None:
  1546. """Test adding a directory with some files already tracked."""
  1547. # Create a subdirectory with files
  1548. subdir = os.path.join(self.repo.path, "mixed")
  1549. os.mkdir(subdir)
  1550. # Create and commit one file
  1551. tracked_file = os.path.join(subdir, "tracked.txt")
  1552. with open(tracked_file, "w") as f:
  1553. f.write("already tracked")
  1554. porcelain.add(self.repo.path, paths=[tracked_file])
  1555. porcelain.commit(
  1556. repo=self.repo.path,
  1557. message=b"Add tracked file",
  1558. author=b"test <email>",
  1559. committer=b"test <email>",
  1560. )
  1561. # Add more untracked files
  1562. with open(os.path.join(subdir, "untracked1.txt"), "w") as f:
  1563. f.write("new file 1")
  1564. with open(os.path.join(subdir, "untracked2.txt"), "w") as f:
  1565. f.write("new file 2")
  1566. # Add the directory
  1567. added, ignored = porcelain.add(self.repo.path, paths=["mixed"])
  1568. # Should only add the untracked files
  1569. self.assertEqual(len(added), 2)
  1570. # Normalize paths to use forward slashes for comparison
  1571. added_normalized = [path.replace(os.sep, "/") for path in added]
  1572. self.assertIn("mixed/untracked1.txt", added_normalized)
  1573. self.assertIn("mixed/untracked2.txt", added_normalized)
  1574. self.assertNotIn("mixed/tracked.txt", added)
  1575. # Verify the index contains all files
  1576. index = self.repo.open_index()
  1577. self.assertIn(b"mixed/tracked.txt", index)
  1578. self.assertIn(b"mixed/untracked1.txt", index)
  1579. self.assertIn(b"mixed/untracked2.txt", index)
  1580. def test_add_directory_with_gitignore(self) -> None:
  1581. """Test adding a directory respects .gitignore patterns."""
  1582. # Create .gitignore
  1583. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1584. f.write("*.log\n*.tmp\nbuild/\n")
  1585. # Create directory with mixed files
  1586. testdir = os.path.join(self.repo.path, "testdir")
  1587. os.mkdir(testdir)
  1588. # Create various files
  1589. with open(os.path.join(testdir, "important.txt"), "w") as f:
  1590. f.write("keep this")
  1591. with open(os.path.join(testdir, "debug.log"), "w") as f:
  1592. f.write("ignore this")
  1593. with open(os.path.join(testdir, "temp.tmp"), "w") as f:
  1594. f.write("ignore this too")
  1595. with open(os.path.join(testdir, "readme.md"), "w") as f:
  1596. f.write("keep this too")
  1597. # Create a build directory that should be ignored
  1598. builddir = os.path.join(testdir, "build")
  1599. os.mkdir(builddir)
  1600. with open(os.path.join(builddir, "output.txt"), "w") as f:
  1601. f.write("ignore entire directory")
  1602. # Add the directory
  1603. added, ignored = porcelain.add(self.repo.path, paths=["testdir"])
  1604. # Should only add non-ignored files
  1605. # Normalize paths to use forward slashes for comparison
  1606. added_normalized = {path.replace(os.sep, "/") for path in added}
  1607. self.assertEqual(
  1608. added_normalized, {"testdir/important.txt", "testdir/readme.md"}
  1609. )
  1610. # Check ignored files
  1611. # Normalize paths to use forward slashes for comparison
  1612. ignored_normalized = {path.replace(os.sep, "/") for path in ignored}
  1613. self.assertIn("testdir/debug.log", ignored_normalized)
  1614. self.assertIn("testdir/temp.tmp", ignored_normalized)
  1615. self.assertIn("testdir/build/", ignored_normalized)
  1616. def test_add_multiple_directories(self) -> None:
  1617. """Test adding multiple directories in one call."""
  1618. # Create multiple directories
  1619. for dirname in ["dir1", "dir2", "dir3"]:
  1620. dirpath = os.path.join(self.repo.path, dirname)
  1621. os.mkdir(dirpath)
  1622. # Add files to each directory
  1623. for i in range(2):
  1624. with open(os.path.join(dirpath, f"file{i}.txt"), "w") as f:
  1625. f.write(f"content {dirname} {i}")
  1626. # Add all directories at once
  1627. added, ignored = porcelain.add(self.repo.path, paths=["dir1", "dir2", "dir3"])
  1628. # Should add all files from all directories
  1629. self.assertEqual(len(added), 6)
  1630. # Normalize paths to use forward slashes for comparison
  1631. added_normalized = [path.replace(os.sep, "/") for path in added]
  1632. for dirname in ["dir1", "dir2", "dir3"]:
  1633. for i in range(2):
  1634. self.assertIn(f"{dirname}/file{i}.txt", added_normalized)
  1635. # Verify all files are staged
  1636. index = self.repo.open_index()
  1637. self.assertEqual(len(index), 6)
  1638. def test_add_default_paths_includes_modified_files(self) -> None:
  1639. """Test that add() with no paths includes both untracked and modified files."""
  1640. # Create and commit initial file
  1641. initial_file = os.path.join(self.repo.path, "existing.txt")
  1642. with open(initial_file, "w") as f:
  1643. f.write("initial content\n")
  1644. porcelain.add(repo=self.repo.path, paths=[initial_file])
  1645. porcelain.commit(
  1646. repo=self.repo.path,
  1647. message=b"initial commit",
  1648. author=b"test <email>",
  1649. committer=b"test <email>",
  1650. )
  1651. # Modify the existing file (this creates an unstaged change)
  1652. with open(initial_file, "w") as f:
  1653. f.write("modified content\n")
  1654. # Create a new untracked file
  1655. new_file = os.path.join(self.repo.path, "new.txt")
  1656. with open(new_file, "w") as f:
  1657. f.write("new file content\n")
  1658. # Call add() with no paths - should stage both modified and untracked files
  1659. added_files, ignored_files = porcelain.add(repo=self.repo.path)
  1660. # Verify both files were added
  1661. self.assertIn("existing.txt", added_files)
  1662. self.assertIn("new.txt", added_files)
  1663. self.assertEqual(len(ignored_files), 0)
  1664. # Verify both files are now staged
  1665. index = self.repo.open_index()
  1666. self.assertIn(b"existing.txt", index)
  1667. self.assertIn(b"new.txt", index)
  1668. class RemoveTests(PorcelainTestCase):
  1669. def test_remove_file(self) -> None:
  1670. fullpath = os.path.join(self.repo.path, "foo")
  1671. with open(fullpath, "w") as f:
  1672. f.write("BAR")
  1673. porcelain.add(self.repo.path, paths=[fullpath])
  1674. porcelain.commit(
  1675. repo=self.repo,
  1676. message=b"test",
  1677. author=b"test <email>",
  1678. committer=b"test <email>",
  1679. )
  1680. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "foo")))
  1681. cwd = os.getcwd()
  1682. self.addCleanup(os.chdir, cwd)
  1683. os.chdir(self.repo.path)
  1684. porcelain.remove(self.repo.path, paths=["foo"])
  1685. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1686. def test_remove_file_staged(self) -> None:
  1687. fullpath = os.path.join(self.repo.path, "foo")
  1688. with open(fullpath, "w") as f:
  1689. f.write("BAR")
  1690. cwd = os.getcwd()
  1691. self.addCleanup(os.chdir, cwd)
  1692. os.chdir(self.repo.path)
  1693. porcelain.add(self.repo.path, paths=[fullpath])
  1694. self.assertRaises(Exception, porcelain.rm, self.repo.path, paths=["foo"])
  1695. def test_remove_file_removed_on_disk(self) -> None:
  1696. fullpath = os.path.join(self.repo.path, "foo")
  1697. with open(fullpath, "w") as f:
  1698. f.write("BAR")
  1699. porcelain.add(self.repo.path, paths=[fullpath])
  1700. cwd = os.getcwd()
  1701. self.addCleanup(os.chdir, cwd)
  1702. os.chdir(self.repo.path)
  1703. os.remove(fullpath)
  1704. porcelain.remove(self.repo.path, paths=["foo"])
  1705. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1706. def test_remove_from_different_directory(self) -> None:
  1707. # Create a subdirectory with a file
  1708. subdir = os.path.join(self.repo.path, "mydir")
  1709. os.makedirs(subdir)
  1710. fullpath = os.path.join(subdir, "myfile")
  1711. with open(fullpath, "w") as f:
  1712. f.write("BAR")
  1713. # Add and commit the file
  1714. porcelain.add(self.repo.path, paths=[fullpath])
  1715. porcelain.commit(
  1716. repo=self.repo,
  1717. message=b"test",
  1718. author=b"test <email>",
  1719. committer=b"test <email>",
  1720. )
  1721. # Change to a different directory
  1722. cwd = os.getcwd()
  1723. tempdir = tempfile.mkdtemp()
  1724. def cleanup():
  1725. os.chdir(cwd)
  1726. shutil.rmtree(tempdir)
  1727. self.addCleanup(cleanup)
  1728. os.chdir(tempdir)
  1729. # Remove the file using relative path from repository root
  1730. porcelain.remove(self.repo.path, paths=["mydir/myfile"])
  1731. # Verify file was removed
  1732. self.assertFalse(os.path.exists(fullpath))
  1733. def test_remove_with_absolute_path(self) -> None:
  1734. # Create a file
  1735. fullpath = os.path.join(self.repo.path, "foo")
  1736. with open(fullpath, "w") as f:
  1737. f.write("BAR")
  1738. # Add and commit the file
  1739. porcelain.add(self.repo.path, paths=[fullpath])
  1740. porcelain.commit(
  1741. repo=self.repo,
  1742. message=b"test",
  1743. author=b"test <email>",
  1744. committer=b"test <email>",
  1745. )
  1746. # Change to a different directory
  1747. cwd = os.getcwd()
  1748. tempdir = tempfile.mkdtemp()
  1749. def cleanup():
  1750. os.chdir(cwd)
  1751. shutil.rmtree(tempdir)
  1752. self.addCleanup(cleanup)
  1753. os.chdir(tempdir)
  1754. # Remove the file using absolute path
  1755. porcelain.remove(self.repo.path, paths=[fullpath])
  1756. # Verify file was removed
  1757. self.assertFalse(os.path.exists(fullpath))
  1758. def test_remove_with_filter_normalization(self) -> None:
  1759. # Enable autocrlf to normalize line endings
  1760. config = self.repo.get_config()
  1761. config.set(("core",), "autocrlf", b"true")
  1762. config.write_to_path()
  1763. # Create a file with LF line endings (will be stored with LF in index)
  1764. fullpath = os.path.join(self.repo.path, "foo.txt")
  1765. with open(fullpath, "wb") as f:
  1766. f.write(b"line1\nline2\nline3")
  1767. # Add and commit the file (stored with LF in index)
  1768. porcelain.add(self.repo.path, paths=[fullpath])
  1769. porcelain.commit(
  1770. repo=self.repo,
  1771. message=b"Add file with LF",
  1772. author=b"test <email>",
  1773. committer=b"test <email>",
  1774. )
  1775. # Simulate checkout with CRLF conversion (as would happen on Windows)
  1776. with open(fullpath, "wb") as f:
  1777. f.write(b"line1\r\nline2\r\nline3")
  1778. # Verify file exists
  1779. self.assertTrue(os.path.exists(fullpath))
  1780. # Remove the file - this should not fail even though working tree has CRLF
  1781. # and index has LF (thanks to the normalization in the commit)
  1782. cwd = os.getcwd()
  1783. os.chdir(self.repo.path)
  1784. self.addCleanup(os.chdir, cwd)
  1785. porcelain.remove(self.repo.path, paths=["foo.txt"])
  1786. # Verify file was removed
  1787. self.assertFalse(os.path.exists(fullpath))
  1788. class MvTests(PorcelainTestCase):
  1789. def test_mv_file(self) -> None:
  1790. # Create a file
  1791. fullpath = os.path.join(self.repo.path, "foo")
  1792. with open(fullpath, "w") as f:
  1793. f.write("BAR")
  1794. # Add and commit the file
  1795. porcelain.add(self.repo.path, paths=[fullpath])
  1796. porcelain.commit(
  1797. repo=self.repo,
  1798. message=b"test",
  1799. author=b"test <email>",
  1800. committer=b"test <email>",
  1801. )
  1802. # Move the file
  1803. porcelain.mv(self.repo.path, "foo", "bar")
  1804. # Verify old path doesn't exist and new path does
  1805. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1806. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "bar")))
  1807. # Verify index was updated
  1808. index = self.repo.open_index()
  1809. self.assertNotIn(b"foo", index)
  1810. self.assertIn(b"bar", index)
  1811. def test_mv_file_to_existing_directory(self) -> None:
  1812. # Create a file and a directory
  1813. fullpath = os.path.join(self.repo.path, "foo")
  1814. with open(fullpath, "w") as f:
  1815. f.write("BAR")
  1816. dirpath = os.path.join(self.repo.path, "mydir")
  1817. os.makedirs(dirpath)
  1818. # Add and commit the file
  1819. porcelain.add(self.repo.path, paths=[fullpath])
  1820. porcelain.commit(
  1821. repo=self.repo,
  1822. message=b"test",
  1823. author=b"test <email>",
  1824. committer=b"test <email>",
  1825. )
  1826. # Move the file into the directory
  1827. porcelain.mv(self.repo.path, "foo", "mydir")
  1828. # Verify file moved into directory
  1829. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1830. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "mydir", "foo")))
  1831. # Verify index was updated
  1832. index = self.repo.open_index()
  1833. self.assertNotIn(b"foo", index)
  1834. self.assertIn(b"mydir/foo", index)
  1835. def test_mv_file_force_overwrite(self) -> None:
  1836. # Create two files
  1837. fullpath1 = os.path.join(self.repo.path, "foo")
  1838. with open(fullpath1, "w") as f:
  1839. f.write("FOO")
  1840. fullpath2 = os.path.join(self.repo.path, "bar")
  1841. with open(fullpath2, "w") as f:
  1842. f.write("BAR")
  1843. # Add and commit both files
  1844. porcelain.add(self.repo.path, paths=[fullpath1, fullpath2])
  1845. porcelain.commit(
  1846. repo=self.repo,
  1847. message=b"test",
  1848. author=b"test <email>",
  1849. committer=b"test <email>",
  1850. )
  1851. # Try to move without force (should fail)
  1852. self.assertRaises(porcelain.Error, porcelain.mv, self.repo.path, "foo", "bar")
  1853. # Move with force
  1854. porcelain.mv(self.repo.path, "foo", "bar", force=True)
  1855. # Verify foo doesn't exist and bar has foo's content
  1856. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1857. with open(os.path.join(self.repo.path, "bar")) as f:
  1858. self.assertEqual(f.read(), "FOO")
  1859. def test_mv_file_not_tracked(self) -> None:
  1860. # Create an untracked file
  1861. fullpath = os.path.join(self.repo.path, "untracked")
  1862. with open(fullpath, "w") as f:
  1863. f.write("UNTRACKED")
  1864. # Try to move it (should fail)
  1865. self.assertRaises(
  1866. porcelain.Error, porcelain.mv, self.repo.path, "untracked", "tracked"
  1867. )
  1868. def test_mv_file_not_exists(self) -> None:
  1869. # Try to move a non-existent file
  1870. self.assertRaises(
  1871. porcelain.Error, porcelain.mv, self.repo.path, "nonexistent", "destination"
  1872. )
  1873. def test_mv_absolute_paths(self) -> None:
  1874. # Create a file
  1875. fullpath = os.path.join(self.repo.path, "foo")
  1876. with open(fullpath, "w") as f:
  1877. f.write("BAR")
  1878. # Add and commit the file
  1879. porcelain.add(self.repo.path, paths=[fullpath])
  1880. porcelain.commit(
  1881. repo=self.repo,
  1882. message=b"test",
  1883. author=b"test <email>",
  1884. committer=b"test <email>",
  1885. )
  1886. # Move using absolute paths
  1887. dest_path = os.path.join(self.repo.path, "bar")
  1888. porcelain.mv(self.repo.path, fullpath, dest_path)
  1889. # Verify file moved
  1890. self.assertFalse(os.path.exists(fullpath))
  1891. self.assertTrue(os.path.exists(dest_path))
  1892. def test_mv_from_different_directory(self) -> None:
  1893. # Create a subdirectory with a file
  1894. subdir = os.path.join(self.repo.path, "mydir")
  1895. os.makedirs(subdir)
  1896. fullpath = os.path.join(subdir, "myfile")
  1897. with open(fullpath, "w") as f:
  1898. f.write("BAR")
  1899. # Add and commit the file
  1900. porcelain.add(self.repo.path, paths=[fullpath])
  1901. porcelain.commit(
  1902. repo=self.repo,
  1903. message=b"test",
  1904. author=b"test <email>",
  1905. committer=b"test <email>",
  1906. )
  1907. # Change to a different directory and move the file
  1908. cwd = os.getcwd()
  1909. tempdir = tempfile.mkdtemp()
  1910. def cleanup():
  1911. os.chdir(cwd)
  1912. shutil.rmtree(tempdir)
  1913. self.addCleanup(cleanup)
  1914. os.chdir(tempdir)
  1915. # Move the file using relative path from repository root
  1916. porcelain.mv(self.repo.path, "mydir/myfile", "renamed")
  1917. # Verify file was moved
  1918. self.assertFalse(os.path.exists(fullpath))
  1919. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "renamed")))
  1920. class LogTests(PorcelainTestCase):
  1921. def test_simple(self) -> None:
  1922. c1, c2, c3 = build_commit_graph(
  1923. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1924. )
  1925. self.repo.refs[b"HEAD"] = c3.id
  1926. self.maxDiff = None
  1927. outstream = StringIO()
  1928. porcelain.log(self.repo.path, outstream=outstream)
  1929. self.assertEqual(
  1930. outstream.getvalue(),
  1931. """\
  1932. --------------------------------------------------
  1933. commit: 4a3b887baa9ecb2d054d2469b628aef84e2d74f0
  1934. merge: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  1935. Author: Test Author <test@nodomain.com>
  1936. Committer: Test Committer <test@nodomain.com>
  1937. Date: Fri Jan 01 2010 00:00:00 +0000
  1938. Commit 3
  1939. --------------------------------------------------
  1940. commit: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  1941. Author: Test Author <test@nodomain.com>
  1942. Committer: Test Committer <test@nodomain.com>
  1943. Date: Fri Jan 01 2010 00:00:00 +0000
  1944. Commit 2
  1945. --------------------------------------------------
  1946. commit: 11d3cf672a19366435c1983c7340b008ec6b8bf3
  1947. Author: Test Author <test@nodomain.com>
  1948. Committer: Test Committer <test@nodomain.com>
  1949. Date: Fri Jan 01 2010 00:00:00 +0000
  1950. Commit 1
  1951. """,
  1952. )
  1953. def test_max_entries(self) -> None:
  1954. c1, c2, c3 = build_commit_graph(
  1955. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1956. )
  1957. self.repo.refs[b"HEAD"] = c3.id
  1958. outstream = StringIO()
  1959. porcelain.log(self.repo.path, outstream=outstream, max_entries=1)
  1960. self.assertEqual(1, outstream.getvalue().count("-" * 50))
  1961. def test_no_revisions(self) -> None:
  1962. outstream = StringIO()
  1963. porcelain.log(self.repo.path, outstream=outstream)
  1964. self.assertEqual("", outstream.getvalue())
  1965. def test_empty_message(self) -> None:
  1966. c1 = make_commit(message="")
  1967. self.repo.object_store.add_object(c1)
  1968. self.repo.refs[b"HEAD"] = c1.id
  1969. outstream = StringIO()
  1970. porcelain.log(self.repo.path, outstream=outstream)
  1971. self.assertEqual(
  1972. outstream.getvalue(),
  1973. """\
  1974. --------------------------------------------------
  1975. commit: 4a7ad5552fad70647a81fb9a4a923ccefcca4b76
  1976. Author: Test Author <test@nodomain.com>
  1977. Committer: Test Committer <test@nodomain.com>
  1978. Date: Fri Jan 01 2010 00:00:00 +0000
  1979. """,
  1980. )
  1981. class ShowTests(PorcelainTestCase):
  1982. def test_nolist(self) -> None:
  1983. c1, c2, c3 = build_commit_graph(
  1984. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1985. )
  1986. self.repo.refs[b"HEAD"] = c3.id
  1987. outstream = StringIO()
  1988. porcelain.show(self.repo.path, objects=c3.id, outstream=outstream)
  1989. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  1990. def test_simple(self) -> None:
  1991. c1, c2, c3 = build_commit_graph(
  1992. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1993. )
  1994. self.repo.refs[b"HEAD"] = c3.id
  1995. outstream = StringIO()
  1996. porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream)
  1997. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  1998. def test_blob(self) -> None:
  1999. b = Blob.from_string(b"The Foo\n")
  2000. self.repo.object_store.add_object(b)
  2001. outstream = StringIO()
  2002. porcelain.show(self.repo.path, objects=[b.id], outstream=outstream)
  2003. self.assertEqual(outstream.getvalue(), "The Foo\n")
  2004. def test_commit_no_parent(self) -> None:
  2005. a = Blob.from_string(b"The Foo\n")
  2006. ta = Tree()
  2007. ta.add(b"somename", 0o100644, a.id)
  2008. ca = make_commit(tree=ta.id)
  2009. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2010. outstream = StringIO()
  2011. porcelain.show(self.repo.path, objects=[ca.id], outstream=outstream)
  2012. self.assertMultiLineEqual(
  2013. outstream.getvalue(),
  2014. """\
  2015. --------------------------------------------------
  2016. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2017. Author: Test Author <test@nodomain.com>
  2018. Committer: Test Committer <test@nodomain.com>
  2019. Date: Fri Jan 01 2010 00:00:00 +0000
  2020. Test message.
  2021. diff --git a/somename b/somename
  2022. new file mode 100644
  2023. index 0000000..ea5c7bf
  2024. --- /dev/null
  2025. +++ b/somename
  2026. @@ -0,0 +1 @@
  2027. +The Foo
  2028. """,
  2029. )
  2030. def test_tag(self) -> None:
  2031. a = Blob.from_string(b"The Foo\n")
  2032. ta = Tree()
  2033. ta.add(b"somename", 0o100644, a.id)
  2034. ca = make_commit(tree=ta.id)
  2035. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2036. porcelain.tag_create(
  2037. self.repo.path,
  2038. b"tryme",
  2039. b"foo <foo@bar.com>",
  2040. b"bar",
  2041. annotated=True,
  2042. objectish=ca.id,
  2043. tag_time=1552854211,
  2044. tag_timezone=0,
  2045. )
  2046. outstream = StringIO()
  2047. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2048. self.maxDiff = None
  2049. self.assertMultiLineEqual(
  2050. outstream.getvalue(),
  2051. """\
  2052. Tagger: foo <foo@bar.com>
  2053. Date: Sun Mar 17 2019 20:23:31 +0000
  2054. bar
  2055. --------------------------------------------------
  2056. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2057. Author: Test Author <test@nodomain.com>
  2058. Committer: Test Committer <test@nodomain.com>
  2059. Date: Fri Jan 01 2010 00:00:00 +0000
  2060. Test message.
  2061. diff --git a/somename b/somename
  2062. new file mode 100644
  2063. index 0000000..ea5c7bf
  2064. --- /dev/null
  2065. +++ b/somename
  2066. @@ -0,0 +1 @@
  2067. +The Foo
  2068. """,
  2069. )
  2070. def test_tag_unicode(self) -> None:
  2071. a = Blob.from_string(b"The Foo\n")
  2072. ta = Tree()
  2073. ta.add(b"somename", 0o100644, a.id)
  2074. ca = make_commit(tree=ta.id)
  2075. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2076. porcelain.tag_create(
  2077. self.repo.path,
  2078. "tryme",
  2079. "foo <foo@bar.com>",
  2080. "bar",
  2081. annotated=True,
  2082. objectish=ca.id,
  2083. tag_time=1552854211,
  2084. tag_timezone=0,
  2085. )
  2086. outstream = StringIO()
  2087. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2088. self.maxDiff = None
  2089. self.assertMultiLineEqual(
  2090. outstream.getvalue(),
  2091. """\
  2092. Tagger: foo <foo@bar.com>
  2093. Date: Sun Mar 17 2019 20:23:31 +0000
  2094. bar
  2095. --------------------------------------------------
  2096. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2097. Author: Test Author <test@nodomain.com>
  2098. Committer: Test Committer <test@nodomain.com>
  2099. Date: Fri Jan 01 2010 00:00:00 +0000
  2100. Test message.
  2101. diff --git a/somename b/somename
  2102. new file mode 100644
  2103. index 0000000..ea5c7bf
  2104. --- /dev/null
  2105. +++ b/somename
  2106. @@ -0,0 +1 @@
  2107. +The Foo
  2108. """,
  2109. )
  2110. def test_commit_with_change(self) -> None:
  2111. a = Blob.from_string(b"The Foo\n")
  2112. ta = Tree()
  2113. ta.add(b"somename", 0o100644, a.id)
  2114. ca = make_commit(tree=ta.id)
  2115. b = Blob.from_string(b"The Bar\n")
  2116. tb = Tree()
  2117. tb.add(b"somename", 0o100644, b.id)
  2118. cb = make_commit(tree=tb.id, parents=[ca.id])
  2119. self.repo.object_store.add_objects(
  2120. [
  2121. (a, None),
  2122. (b, None),
  2123. (ta, None),
  2124. (tb, None),
  2125. (ca, None),
  2126. (cb, None),
  2127. ]
  2128. )
  2129. outstream = StringIO()
  2130. porcelain.show(self.repo.path, objects=[cb.id], outstream=outstream)
  2131. self.assertMultiLineEqual(
  2132. outstream.getvalue(),
  2133. """\
  2134. --------------------------------------------------
  2135. commit: 2c6b6c9cb72c130956657e1fdae58e5b103744fa
  2136. Author: Test Author <test@nodomain.com>
  2137. Committer: Test Committer <test@nodomain.com>
  2138. Date: Fri Jan 01 2010 00:00:00 +0000
  2139. Test message.
  2140. diff --git a/somename b/somename
  2141. index ea5c7bf..fd38bcb 100644
  2142. --- a/somename
  2143. +++ b/somename
  2144. @@ -1 +1 @@
  2145. -The Foo
  2146. +The Bar
  2147. """,
  2148. )
  2149. class FormatPatchTests(PorcelainTestCase):
  2150. def test_format_patch_single_commit(self) -> None:
  2151. # Create initial commit
  2152. tree1 = Tree()
  2153. c1 = make_commit(
  2154. tree=tree1,
  2155. message=b"Initial commit",
  2156. )
  2157. self.repo.object_store.add_objects([(tree1, None), (c1, None)])
  2158. # Create second commit
  2159. b = Blob.from_string(b"modified")
  2160. tree = Tree()
  2161. tree.add(b"test.txt", 0o100644, b.id)
  2162. c2 = make_commit(
  2163. tree=tree,
  2164. parents=[c1.id],
  2165. message=b"Add test.txt",
  2166. )
  2167. self.repo.object_store.add_objects([(b, None), (tree, None), (c2, None)])
  2168. self.repo[b"HEAD"] = c2.id
  2169. # Generate patch for single commit
  2170. with tempfile.TemporaryDirectory() as tmpdir:
  2171. patches = porcelain.format_patch(
  2172. self.repo.path,
  2173. committish=c2.id,
  2174. outdir=tmpdir,
  2175. )
  2176. self.assertEqual(len(patches), 1)
  2177. self.assertTrue(patches[0].endswith("-Add-test.txt.patch"))
  2178. # Verify patch content
  2179. with open(patches[0], "rb") as f:
  2180. content = f.read()
  2181. self.assertIn(b"Subject: [PATCH 1/1] Add test.txt", content)
  2182. self.assertIn(b"+modified", content)
  2183. def test_format_patch_multiple_commits(self) -> None:
  2184. # Create commit chain
  2185. commits = []
  2186. for i in range(3):
  2187. blob = Blob.from_string(f"content {i}".encode())
  2188. tree = Tree()
  2189. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  2190. parents = [commits[-1].id] if commits else []
  2191. commit = make_commit(
  2192. tree=tree,
  2193. parents=parents,
  2194. message=f"Commit {i}".encode(),
  2195. )
  2196. self.repo.object_store.add_objects(
  2197. [(blob, None), (tree, None), (commit, None)]
  2198. )
  2199. commits.append(commit)
  2200. self.repo[b"HEAD"] = commits[-1].id
  2201. # Test generating last 2 commits
  2202. with tempfile.TemporaryDirectory() as tmpdir:
  2203. patches = porcelain.format_patch(
  2204. self.repo.path,
  2205. n=2,
  2206. outdir=tmpdir,
  2207. )
  2208. self.assertEqual(len(patches), 2)
  2209. self.assertTrue(patches[0].endswith("-Commit-1.patch"))
  2210. self.assertTrue(patches[1].endswith("-Commit-2.patch"))
  2211. # Check patch numbering
  2212. with open(patches[0], "rb") as f:
  2213. self.assertIn(b"Subject: [PATCH 1/2] Commit 1", f.read())
  2214. with open(patches[1], "rb") as f:
  2215. self.assertIn(b"Subject: [PATCH 2/2] Commit 2", f.read())
  2216. def test_format_patch_range(self) -> None:
  2217. # Create commit chain
  2218. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  2219. self.repo[b"HEAD"] = c3.id
  2220. # Test commit range
  2221. with tempfile.TemporaryDirectory() as tmpdir:
  2222. patches = porcelain.format_patch(
  2223. self.repo.path,
  2224. committish=(c1.id, c3.id),
  2225. outdir=tmpdir,
  2226. )
  2227. # Should include c2 and c3
  2228. self.assertEqual(len(patches), 2)
  2229. def test_format_patch_stdout(self) -> None:
  2230. # Create a commit
  2231. blob = Blob.from_string(b"test content")
  2232. tree = Tree()
  2233. tree.add(b"test.txt", 0o100644, blob.id)
  2234. commit = make_commit(
  2235. tree=tree,
  2236. message=b"Test commit",
  2237. )
  2238. self.repo.object_store.add_objects([(blob, None), (tree, None), (commit, None)])
  2239. self.repo[b"HEAD"] = commit.id
  2240. # Test stdout output
  2241. outstream = BytesIO()
  2242. patches = porcelain.format_patch(
  2243. self.repo.path,
  2244. committish=commit.id,
  2245. stdout=True,
  2246. outstream=outstream,
  2247. )
  2248. # Should return empty list when writing to stdout
  2249. self.assertEqual(patches, [])
  2250. # Check stdout content
  2251. outstream.seek(0)
  2252. content = outstream.read()
  2253. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  2254. self.assertIn(b"diff --git", content)
  2255. def test_format_patch_no_commits(self) -> None:
  2256. # Test with a new repository with no commits
  2257. # Just remove HEAD to simulate empty repo
  2258. patches = porcelain.format_patch(
  2259. self.repo.path,
  2260. n=5,
  2261. )
  2262. self.assertEqual(patches, [])
  2263. class SymbolicRefTests(PorcelainTestCase):
  2264. def test_set_wrong_symbolic_ref(self) -> None:
  2265. c1, c2, c3 = build_commit_graph(
  2266. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2267. )
  2268. self.repo.refs[b"HEAD"] = c3.id
  2269. self.assertRaises(
  2270. porcelain.Error, porcelain.symbolic_ref, self.repo.path, b"foobar"
  2271. )
  2272. def test_set_force_wrong_symbolic_ref(self) -> None:
  2273. c1, c2, c3 = build_commit_graph(
  2274. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2275. )
  2276. self.repo.refs[b"HEAD"] = c3.id
  2277. porcelain.symbolic_ref(self.repo.path, b"force_foobar", force=True)
  2278. # test if we actually changed the file
  2279. with self.repo.get_named_file("HEAD") as f:
  2280. new_ref = f.read()
  2281. self.assertEqual(new_ref, b"ref: refs/heads/force_foobar\n")
  2282. def test_set_symbolic_ref(self) -> None:
  2283. c1, c2, c3 = build_commit_graph(
  2284. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2285. )
  2286. self.repo.refs[b"HEAD"] = c3.id
  2287. porcelain.symbolic_ref(self.repo.path, b"master")
  2288. def test_set_symbolic_ref_other_than_master(self) -> None:
  2289. c1, c2, c3 = build_commit_graph(
  2290. self.repo.object_store,
  2291. [[1], [2, 1], [3, 1, 2]],
  2292. attrs=dict(refs="develop"),
  2293. )
  2294. self.repo.refs[b"HEAD"] = c3.id
  2295. self.repo.refs[b"refs/heads/develop"] = c3.id
  2296. porcelain.symbolic_ref(self.repo.path, b"develop")
  2297. # test if we actually changed the file
  2298. with self.repo.get_named_file("HEAD") as f:
  2299. new_ref = f.read()
  2300. self.assertEqual(new_ref, b"ref: refs/heads/develop\n")
  2301. class DiffTreeTests(PorcelainTestCase):
  2302. def test_empty(self) -> None:
  2303. c1, c2, c3 = build_commit_graph(
  2304. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2305. )
  2306. self.repo.refs[b"HEAD"] = c3.id
  2307. outstream = BytesIO()
  2308. porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream)
  2309. self.assertEqual(outstream.getvalue(), b"")
  2310. class DiffTests(PorcelainTestCase):
  2311. def test_diff_uncommitted_stage(self) -> None:
  2312. # Test diff in repository with no commits yet
  2313. fullpath = os.path.join(self.repo.path, "test.txt")
  2314. with open(fullpath, "w") as f:
  2315. f.write("Hello, world!\n")
  2316. porcelain.add(self.repo.path, paths=["test.txt"])
  2317. outstream = BytesIO()
  2318. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2319. diff_output = outstream.getvalue()
  2320. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2321. self.assertIn(b"new file mode", diff_output)
  2322. self.assertIn(b"+Hello, world!", diff_output)
  2323. def test_diff_uncommitted_working_tree(self) -> None:
  2324. # Test unstaged changes in repository with no commits
  2325. fullpath = os.path.join(self.repo.path, "test.txt")
  2326. with open(fullpath, "w") as f:
  2327. f.write("Hello, world!\n")
  2328. porcelain.add(self.repo.path, paths=["test.txt"])
  2329. # Modify file in working tree
  2330. with open(fullpath, "w") as f:
  2331. f.write("Hello, world!\nNew line\n")
  2332. outstream = BytesIO()
  2333. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2334. diff_output = outstream.getvalue()
  2335. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2336. self.assertIn(b"+New line", diff_output)
  2337. def test_diff_with_commits_staged(self) -> None:
  2338. # Test staged changes with existing commits
  2339. fullpath = os.path.join(self.repo.path, "test.txt")
  2340. with open(fullpath, "w") as f:
  2341. f.write("Initial content\n")
  2342. porcelain.add(self.repo.path, paths=["test.txt"])
  2343. porcelain.commit(self.repo.path, message=b"Initial commit")
  2344. # Modify and stage
  2345. with open(fullpath, "w") as f:
  2346. f.write("Initial content\nModified\n")
  2347. porcelain.add(self.repo.path, paths=["test.txt"])
  2348. outstream = BytesIO()
  2349. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2350. diff_output = outstream.getvalue()
  2351. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2352. self.assertIn(b"+Modified", diff_output)
  2353. def test_diff_with_commits_unstaged(self) -> None:
  2354. # Test unstaged changes with existing commits
  2355. fullpath = os.path.join(self.repo.path, "test.txt")
  2356. with open(fullpath, "w") as f:
  2357. f.write("Initial content\n")
  2358. porcelain.add(self.repo.path, paths=["test.txt"])
  2359. porcelain.commit(self.repo.path, message=b"Initial commit")
  2360. # Modify without staging
  2361. with open(fullpath, "w") as f:
  2362. f.write("Initial content\nModified\n")
  2363. outstream = BytesIO()
  2364. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2365. diff_output = outstream.getvalue()
  2366. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2367. self.assertIn(b"+Modified", diff_output)
  2368. def test_diff_file_deletion(self) -> None:
  2369. # Test showing file deletion
  2370. fullpath = os.path.join(self.repo.path, "test.txt")
  2371. with open(fullpath, "w") as f:
  2372. f.write("Content to delete\n")
  2373. porcelain.add(self.repo.path, paths=["test.txt"])
  2374. porcelain.commit(self.repo.path, message=b"Add file")
  2375. # Delete file
  2376. os.unlink(fullpath)
  2377. outstream = BytesIO()
  2378. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2379. diff_output = outstream.getvalue()
  2380. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2381. self.assertIn(b"deleted file mode", diff_output)
  2382. self.assertIn(b"-Content to delete", diff_output)
  2383. def test_diff_with_paths(self) -> None:
  2384. # Test diff with specific paths
  2385. # Create two files
  2386. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2387. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2388. with open(fullpath1, "w") as f:
  2389. f.write("File 1 content\n")
  2390. with open(fullpath2, "w") as f:
  2391. f.write("File 2 content\n")
  2392. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2393. porcelain.commit(self.repo.path, message=b"Add two files")
  2394. # Modify both files
  2395. with open(fullpath1, "w") as f:
  2396. f.write("File 1 modified\n")
  2397. with open(fullpath2, "w") as f:
  2398. f.write("File 2 modified\n")
  2399. # Test diff with specific path
  2400. outstream = BytesIO()
  2401. porcelain.diff(self.repo.path, paths=["file1.txt"], outstream=outstream)
  2402. diff_output = outstream.getvalue()
  2403. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2404. self.assertIn(b"-File 1 content", diff_output)
  2405. self.assertIn(b"+File 1 modified", diff_output)
  2406. # file2.txt should not appear in diff
  2407. self.assertNotIn(b"file2.txt", diff_output)
  2408. def test_diff_with_paths_multiple(self) -> None:
  2409. # Test diff with multiple paths
  2410. # Create three files
  2411. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2412. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2413. fullpath3 = os.path.join(self.repo.path, "file3.txt")
  2414. with open(fullpath1, "w") as f:
  2415. f.write("File 1 content\n")
  2416. with open(fullpath2, "w") as f:
  2417. f.write("File 2 content\n")
  2418. with open(fullpath3, "w") as f:
  2419. f.write("File 3 content\n")
  2420. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt", "file3.txt"])
  2421. porcelain.commit(self.repo.path, message=b"Add three files")
  2422. # Modify all files
  2423. with open(fullpath1, "w") as f:
  2424. f.write("File 1 modified\n")
  2425. with open(fullpath2, "w") as f:
  2426. f.write("File 2 modified\n")
  2427. with open(fullpath3, "w") as f:
  2428. f.write("File 3 modified\n")
  2429. # Test diff with two specific paths
  2430. outstream = BytesIO()
  2431. porcelain.diff(
  2432. self.repo.path, paths=["file1.txt", "file3.txt"], outstream=outstream
  2433. )
  2434. diff_output = outstream.getvalue()
  2435. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2436. self.assertIn(b"diff --git a/file3.txt b/file3.txt", diff_output)
  2437. # file2.txt should not appear in diff
  2438. self.assertNotIn(b"file2.txt", diff_output)
  2439. def test_diff_with_paths_directory(self) -> None:
  2440. # Test diff with directory paths
  2441. # Create files in subdirectory
  2442. os.mkdir(os.path.join(self.repo.path, "subdir"))
  2443. fullpath1 = os.path.join(self.repo.path, "subdir", "file1.txt")
  2444. fullpath2 = os.path.join(self.repo.path, "subdir", "file2.txt")
  2445. fullpath3 = os.path.join(self.repo.path, "root.txt")
  2446. with open(fullpath1, "w") as f:
  2447. f.write("Subdir file 1\n")
  2448. with open(fullpath2, "w") as f:
  2449. f.write("Subdir file 2\n")
  2450. with open(fullpath3, "w") as f:
  2451. f.write("Root file\n")
  2452. porcelain.add(
  2453. self.repo.path, paths=["subdir/file1.txt", "subdir/file2.txt", "root.txt"]
  2454. )
  2455. porcelain.commit(self.repo.path, message=b"Add files in subdir")
  2456. # Modify all files
  2457. with open(fullpath1, "w") as f:
  2458. f.write("Subdir file 1 modified\n")
  2459. with open(fullpath2, "w") as f:
  2460. f.write("Subdir file 2 modified\n")
  2461. with open(fullpath3, "w") as f:
  2462. f.write("Root file modified\n")
  2463. # Test diff with directory path
  2464. outstream = BytesIO()
  2465. porcelain.diff(self.repo.path, paths=["subdir"], outstream=outstream)
  2466. diff_output = outstream.getvalue()
  2467. self.assertIn(b"subdir/file1.txt", diff_output)
  2468. self.assertIn(b"subdir/file2.txt", diff_output)
  2469. # root.txt should not appear in diff
  2470. self.assertNotIn(b"root.txt", diff_output)
  2471. def test_diff_staged_with_paths(self) -> None:
  2472. # Test staged diff with specific paths
  2473. # Create two files
  2474. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2475. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2476. with open(fullpath1, "w") as f:
  2477. f.write("File 1 content\n")
  2478. with open(fullpath2, "w") as f:
  2479. f.write("File 2 content\n")
  2480. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2481. porcelain.commit(self.repo.path, message=b"Add two files")
  2482. # Modify and stage both files
  2483. with open(fullpath1, "w") as f:
  2484. f.write("File 1 staged\n")
  2485. with open(fullpath2, "w") as f:
  2486. f.write("File 2 staged\n")
  2487. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2488. # Test staged diff with specific path
  2489. outstream = BytesIO()
  2490. porcelain.diff(
  2491. self.repo.path, staged=True, paths=["file1.txt"], outstream=outstream
  2492. )
  2493. diff_output = outstream.getvalue()
  2494. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2495. self.assertIn(b"-File 1 content", diff_output)
  2496. self.assertIn(b"+File 1 staged", diff_output)
  2497. # file2.txt should not appear in diff
  2498. self.assertNotIn(b"file2.txt", diff_output)
  2499. def test_diff_with_commit_and_paths(self) -> None:
  2500. # Test diff against specific commit with paths
  2501. # Create initial file
  2502. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2503. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2504. with open(fullpath1, "w") as f:
  2505. f.write("Initial content 1\n")
  2506. with open(fullpath2, "w") as f:
  2507. f.write("Initial content 2\n")
  2508. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2509. first_commit = porcelain.commit(self.repo.path, message=b"Initial commit")
  2510. # Make second commit
  2511. with open(fullpath1, "w") as f:
  2512. f.write("Second content 1\n")
  2513. with open(fullpath2, "w") as f:
  2514. f.write("Second content 2\n")
  2515. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2516. porcelain.commit(self.repo.path, message=b"Second commit")
  2517. # Modify working tree
  2518. with open(fullpath1, "w") as f:
  2519. f.write("Working content 1\n")
  2520. with open(fullpath2, "w") as f:
  2521. f.write("Working content 2\n")
  2522. # Test diff against first commit with specific path
  2523. outstream = BytesIO()
  2524. porcelain.diff(
  2525. self.repo.path,
  2526. commit=first_commit,
  2527. paths=["file1.txt"],
  2528. outstream=outstream,
  2529. )
  2530. diff_output = outstream.getvalue()
  2531. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2532. self.assertIn(b"-Initial content 1", diff_output)
  2533. self.assertIn(b"+Working content 1", diff_output)
  2534. # file2.txt should not appear in diff
  2535. self.assertNotIn(b"file2.txt", diff_output)
  2536. class CommitTreeTests(PorcelainTestCase):
  2537. def test_simple(self) -> None:
  2538. c1, c2, c3 = build_commit_graph(
  2539. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2540. )
  2541. b = Blob()
  2542. b.data = b"foo the bar"
  2543. t = Tree()
  2544. t.add(b"somename", 0o100644, b.id)
  2545. self.repo.object_store.add_object(t)
  2546. self.repo.object_store.add_object(b)
  2547. sha = porcelain.commit_tree(
  2548. self.repo.path,
  2549. t.id,
  2550. message=b"Withcommit.",
  2551. author=b"Joe <joe@example.com>",
  2552. committer=b"Jane <jane@example.com>",
  2553. )
  2554. self.assertIsInstance(sha, bytes)
  2555. self.assertEqual(len(sha), 40)
  2556. class RevListTests(PorcelainTestCase):
  2557. def test_simple(self) -> None:
  2558. c1, c2, c3 = build_commit_graph(
  2559. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2560. )
  2561. outstream = BytesIO()
  2562. porcelain.rev_list(self.repo.path, [c3.id], outstream=outstream)
  2563. self.assertEqual(
  2564. c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue()
  2565. )
  2566. @skipIf(
  2567. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  2568. "gpgme not easily available or supported on Windows and PyPy",
  2569. )
  2570. class TagCreateSignTests(PorcelainGpgTestCase):
  2571. def test_default_key(self) -> None:
  2572. c1, c2, c3 = build_commit_graph(
  2573. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2574. )
  2575. self.repo.refs[b"HEAD"] = c3.id
  2576. cfg = self.repo.get_config()
  2577. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2578. self.import_default_key()
  2579. porcelain.tag_create(
  2580. self.repo.path,
  2581. b"tryme",
  2582. b"foo <foo@bar.com>",
  2583. b"bar",
  2584. annotated=True,
  2585. sign=True,
  2586. )
  2587. tags = self.repo.refs.as_dict(b"refs/tags")
  2588. self.assertEqual(list(tags.keys()), [b"tryme"])
  2589. tag = self.repo[b"refs/tags/tryme"]
  2590. self.assertIsInstance(tag, Tag)
  2591. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2592. self.assertEqual(b"bar\n", tag.message)
  2593. self.assertRecentTimestamp(tag.tag_time)
  2594. tag = self.repo[b"refs/tags/tryme"]
  2595. assert isinstance(tag, Tag)
  2596. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2597. tag.verify()
  2598. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2599. self.import_non_default_key()
  2600. self.assertRaises(
  2601. gpg.errors.MissingSignatures,
  2602. tag.verify,
  2603. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  2604. )
  2605. assert tag.signature is not None
  2606. tag._chunked_text = [b"bad data", tag.signature]
  2607. self.assertRaises(
  2608. gpg.errors.BadSignatures,
  2609. tag.verify,
  2610. )
  2611. def test_non_default_key(self) -> None:
  2612. c1, c2, c3 = build_commit_graph(
  2613. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2614. )
  2615. self.repo.refs[b"HEAD"] = c3.id
  2616. cfg = self.repo.get_config()
  2617. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2618. self.import_non_default_key()
  2619. porcelain.tag_create(
  2620. self.repo.path,
  2621. b"tryme",
  2622. b"foo <foo@bar.com>",
  2623. b"bar",
  2624. annotated=True,
  2625. sign=True,
  2626. )
  2627. tags = self.repo.refs.as_dict(b"refs/tags")
  2628. self.assertEqual(list(tags.keys()), [b"tryme"])
  2629. tag = self.repo[b"refs/tags/tryme"]
  2630. self.assertIsInstance(tag, Tag)
  2631. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2632. self.assertEqual(b"bar\n", tag.message)
  2633. self.assertRecentTimestamp(tag.tag_time)
  2634. tag = self.repo[b"refs/tags/tryme"]
  2635. assert isinstance(tag, Tag)
  2636. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2637. tag.verify()
  2638. def test_sign_uses_config_signingkey(self) -> None:
  2639. """Test that sign=True uses user.signingKey from config."""
  2640. c1, c2, c3 = build_commit_graph(
  2641. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2642. )
  2643. self.repo.refs[b"HEAD"] = c3.id
  2644. # Set up user.signingKey in config
  2645. cfg = self.repo.get_config()
  2646. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2647. cfg.write_to_path()
  2648. self.import_default_key()
  2649. # Create tag with sign=True (should use signingKey from config)
  2650. porcelain.tag_create(
  2651. self.repo.path,
  2652. b"signed-tag",
  2653. b"foo <foo@bar.com>",
  2654. b"Tag with configured key",
  2655. annotated=True,
  2656. sign=True, # This should read user.signingKey from config
  2657. )
  2658. tags = self.repo.refs.as_dict(b"refs/tags")
  2659. self.assertEqual(list(tags.keys()), [b"signed-tag"])
  2660. tag = self.repo[b"refs/tags/signed-tag"]
  2661. self.assertIsInstance(tag, Tag)
  2662. # Verify the tag is signed with the configured key
  2663. tag.verify()
  2664. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2665. def test_tag_gpg_sign_config_enabled(self) -> None:
  2666. """Test that tag.gpgSign=true automatically signs tags."""
  2667. c1, c2, c3 = build_commit_graph(
  2668. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2669. )
  2670. self.repo.refs[b"HEAD"] = c3.id
  2671. # Set up user.signingKey and tag.gpgSign in config
  2672. cfg = self.repo.get_config()
  2673. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2674. cfg.set(("tag",), "gpgSign", True)
  2675. cfg.write_to_path()
  2676. self.import_default_key()
  2677. # Create tag without explicit sign parameter (should auto-sign due to config)
  2678. porcelain.tag_create(
  2679. self.repo.path,
  2680. b"auto-signed-tag",
  2681. b"foo <foo@bar.com>",
  2682. b"Auto-signed tag",
  2683. annotated=True,
  2684. # No sign parameter - should use tag.gpgSign config
  2685. )
  2686. tags = self.repo.refs.as_dict(b"refs/tags")
  2687. self.assertEqual(list(tags.keys()), [b"auto-signed-tag"])
  2688. tag = self.repo[b"refs/tags/auto-signed-tag"]
  2689. self.assertIsInstance(tag, Tag)
  2690. # Verify the tag is signed due to config
  2691. tag.verify()
  2692. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2693. def test_tag_gpg_sign_config_disabled(self) -> None:
  2694. """Test that tag.gpgSign=false does not sign tags."""
  2695. c1, c2, c3 = build_commit_graph(
  2696. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2697. )
  2698. self.repo.refs[b"HEAD"] = c3.id
  2699. # Set up user.signingKey and tag.gpgSign=false in config
  2700. cfg = self.repo.get_config()
  2701. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2702. cfg.set(("tag",), "gpgSign", False)
  2703. cfg.write_to_path()
  2704. self.import_default_key()
  2705. # Create tag without explicit sign parameter (should not sign)
  2706. porcelain.tag_create(
  2707. self.repo.path,
  2708. b"unsigned-tag",
  2709. b"foo <foo@bar.com>",
  2710. b"Unsigned tag",
  2711. annotated=True,
  2712. # No sign parameter - should use tag.gpgSign=false config
  2713. )
  2714. tags = self.repo.refs.as_dict(b"refs/tags")
  2715. self.assertEqual(list(tags.keys()), [b"unsigned-tag"])
  2716. tag = self.repo[b"refs/tags/unsigned-tag"]
  2717. self.assertIsInstance(tag, Tag)
  2718. # Verify the tag is not signed
  2719. self.assertIsNone(tag._signature)
  2720. def test_tag_gpg_sign_config_no_signing_key(self) -> None:
  2721. """Test that tag.gpgSign=true works without user.signingKey (uses default)."""
  2722. c1, c2, c3 = build_commit_graph(
  2723. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2724. )
  2725. self.repo.refs[b"HEAD"] = c3.id
  2726. # Set up tag.gpgSign but no user.signingKey
  2727. cfg = self.repo.get_config()
  2728. cfg.set(("tag",), "gpgSign", True)
  2729. cfg.write_to_path()
  2730. self.import_default_key()
  2731. # Create tag without explicit sign parameter (should auto-sign with default key)
  2732. porcelain.tag_create(
  2733. self.repo.path,
  2734. b"default-signed-tag",
  2735. b"foo <foo@bar.com>",
  2736. b"Default signed tag",
  2737. annotated=True,
  2738. # No sign parameter - should use tag.gpgSign config with default key
  2739. )
  2740. tags = self.repo.refs.as_dict(b"refs/tags")
  2741. self.assertEqual(list(tags.keys()), [b"default-signed-tag"])
  2742. tag = self.repo[b"refs/tags/default-signed-tag"]
  2743. self.assertIsInstance(tag, Tag)
  2744. # Verify the tag is signed with default key
  2745. tag.verify()
  2746. def test_explicit_sign_overrides_config(self) -> None:
  2747. """Test that explicit sign parameter overrides tag.gpgSign config."""
  2748. c1, c2, c3 = build_commit_graph(
  2749. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2750. )
  2751. self.repo.refs[b"HEAD"] = c3.id
  2752. # Set up tag.gpgSign=false but explicitly pass sign=True
  2753. cfg = self.repo.get_config()
  2754. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2755. cfg.set(("tag",), "gpgSign", False)
  2756. cfg.write_to_path()
  2757. self.import_default_key()
  2758. # Create tag with explicit sign=True (should override config)
  2759. porcelain.tag_create(
  2760. self.repo.path,
  2761. b"explicit-signed-tag",
  2762. b"foo <foo@bar.com>",
  2763. b"Explicitly signed tag",
  2764. annotated=True,
  2765. sign=True, # This should override tag.gpgSign=false
  2766. )
  2767. tags = self.repo.refs.as_dict(b"refs/tags")
  2768. self.assertEqual(list(tags.keys()), [b"explicit-signed-tag"])
  2769. tag = self.repo[b"refs/tags/explicit-signed-tag"]
  2770. self.assertIsInstance(tag, Tag)
  2771. # Verify the tag is signed despite config=false
  2772. tag.verify()
  2773. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2774. def test_explicit_false_disables_tag_signing(self) -> None:
  2775. """Test that explicit sign=False disables signing even with config=true."""
  2776. c1, c2, c3 = build_commit_graph(
  2777. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2778. )
  2779. self.repo.refs[b"HEAD"] = c3.id
  2780. # Set up tag.gpgSign=true but explicitly pass sign=False
  2781. cfg = self.repo.get_config()
  2782. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2783. cfg.set(("tag",), "gpgSign", True)
  2784. cfg.write_to_path()
  2785. self.import_default_key()
  2786. # Create tag with explicit sign=False (should disable signing)
  2787. porcelain.tag_create(
  2788. self.repo.path,
  2789. b"explicit-unsigned-tag",
  2790. b"foo <foo@bar.com>",
  2791. b"Explicitly unsigned tag",
  2792. annotated=True,
  2793. sign=False, # This should override tag.gpgSign=true
  2794. )
  2795. tags = self.repo.refs.as_dict(b"refs/tags")
  2796. self.assertEqual(list(tags.keys()), [b"explicit-unsigned-tag"])
  2797. tag = self.repo[b"refs/tags/explicit-unsigned-tag"]
  2798. self.assertIsInstance(tag, Tag)
  2799. # Verify the tag is NOT signed despite config=true
  2800. self.assertIsNone(tag._signature)
  2801. class TagCreateTests(PorcelainTestCase):
  2802. def test_annotated(self) -> None:
  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. porcelain.tag_create(
  2808. self.repo.path,
  2809. b"tryme",
  2810. b"foo <foo@bar.com>",
  2811. b"bar",
  2812. annotated=True,
  2813. )
  2814. tags = self.repo.refs.as_dict(b"refs/tags")
  2815. self.assertEqual(list(tags.keys()), [b"tryme"])
  2816. tag = self.repo[b"refs/tags/tryme"]
  2817. self.assertIsInstance(tag, Tag)
  2818. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2819. self.assertEqual(b"bar\n", tag.message)
  2820. self.assertRecentTimestamp(tag.tag_time)
  2821. def test_unannotated(self) -> None:
  2822. c1, c2, c3 = build_commit_graph(
  2823. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2824. )
  2825. self.repo.refs[b"HEAD"] = c3.id
  2826. porcelain.tag_create(self.repo.path, b"tryme", annotated=False)
  2827. tags = self.repo.refs.as_dict(b"refs/tags")
  2828. self.assertEqual(list(tags.keys()), [b"tryme"])
  2829. self.repo[b"refs/tags/tryme"]
  2830. self.assertEqual(list(tags.values()), [self.repo.head()])
  2831. def test_unannotated_unicode(self) -> None:
  2832. c1, c2, c3 = build_commit_graph(
  2833. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2834. )
  2835. self.repo.refs[b"HEAD"] = c3.id
  2836. porcelain.tag_create(self.repo.path, "tryme", annotated=False)
  2837. tags = self.repo.refs.as_dict(b"refs/tags")
  2838. self.assertEqual(list(tags.keys()), [b"tryme"])
  2839. self.repo[b"refs/tags/tryme"]
  2840. self.assertEqual(list(tags.values()), [self.repo.head()])
  2841. class TagListTests(PorcelainTestCase):
  2842. def test_empty(self) -> None:
  2843. tags = porcelain.tag_list(self.repo.path)
  2844. self.assertEqual([], tags)
  2845. def test_simple(self) -> None:
  2846. self.repo.refs[b"refs/tags/foo"] = b"aa" * 20
  2847. self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20
  2848. tags = porcelain.tag_list(self.repo.path)
  2849. self.assertEqual([b"bar/bla", b"foo"], tags)
  2850. class TagDeleteTests(PorcelainTestCase):
  2851. def test_simple(self) -> None:
  2852. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  2853. self.repo[b"HEAD"] = c1.id
  2854. porcelain.tag_create(self.repo, b"foo")
  2855. self.assertIn(b"foo", porcelain.tag_list(self.repo))
  2856. porcelain.tag_delete(self.repo, b"foo")
  2857. self.assertNotIn(b"foo", porcelain.tag_list(self.repo))
  2858. class ResetTests(PorcelainTestCase):
  2859. def test_hard_head(self) -> None:
  2860. fullpath = os.path.join(self.repo.path, "foo")
  2861. with open(fullpath, "w") as f:
  2862. f.write("BAR")
  2863. porcelain.add(self.repo.path, paths=[fullpath])
  2864. porcelain.commit(
  2865. self.repo.path,
  2866. message=b"Some message",
  2867. committer=b"Jane <jane@example.com>",
  2868. author=b"John <john@example.com>",
  2869. )
  2870. with open(os.path.join(self.repo.path, "foo"), "wb") as f:
  2871. f.write(b"OOH")
  2872. porcelain.reset(self.repo, "hard", b"HEAD")
  2873. index = self.repo.open_index()
  2874. changes = list(
  2875. tree_changes(
  2876. self.repo.object_store,
  2877. index.commit(self.repo.object_store),
  2878. self.repo[b"HEAD"].tree,
  2879. )
  2880. )
  2881. self.assertEqual([], changes)
  2882. def test_hard_commit(self) -> None:
  2883. fullpath = os.path.join(self.repo.path, "foo")
  2884. with open(fullpath, "w") as f:
  2885. f.write("BAR")
  2886. porcelain.add(self.repo.path, paths=[fullpath])
  2887. sha = porcelain.commit(
  2888. self.repo.path,
  2889. message=b"Some message",
  2890. committer=b"Jane <jane@example.com>",
  2891. author=b"John <john@example.com>",
  2892. )
  2893. with open(fullpath, "wb") as f:
  2894. f.write(b"BAZ")
  2895. porcelain.add(self.repo.path, paths=[fullpath])
  2896. porcelain.commit(
  2897. self.repo.path,
  2898. message=b"Some other message",
  2899. committer=b"Jane <jane@example.com>",
  2900. author=b"John <john@example.com>",
  2901. )
  2902. porcelain.reset(self.repo, "hard", sha)
  2903. index = self.repo.open_index()
  2904. changes = list(
  2905. tree_changes(
  2906. self.repo.object_store,
  2907. index.commit(self.repo.object_store),
  2908. self.repo[sha].tree,
  2909. )
  2910. )
  2911. self.assertEqual([], changes)
  2912. def test_hard_commit_short_hash(self) -> None:
  2913. fullpath = os.path.join(self.repo.path, "foo")
  2914. with open(fullpath, "w") as f:
  2915. f.write("BAR")
  2916. porcelain.add(self.repo.path, paths=[fullpath])
  2917. sha = porcelain.commit(
  2918. self.repo.path,
  2919. message=b"Some message",
  2920. committer=b"Jane <jane@example.com>",
  2921. author=b"John <john@example.com>",
  2922. )
  2923. with open(fullpath, "wb") as f:
  2924. f.write(b"BAZ")
  2925. porcelain.add(self.repo.path, paths=[fullpath])
  2926. porcelain.commit(
  2927. self.repo.path,
  2928. message=b"Some other message",
  2929. committer=b"Jane <jane@example.com>",
  2930. author=b"John <john@example.com>",
  2931. )
  2932. # Test with short hash (7 characters)
  2933. short_sha = sha[:7].decode("ascii")
  2934. porcelain.reset(self.repo, "hard", short_sha)
  2935. index = self.repo.open_index()
  2936. changes = list(
  2937. tree_changes(
  2938. self.repo.object_store,
  2939. index.commit(self.repo.object_store),
  2940. self.repo[sha].tree,
  2941. )
  2942. )
  2943. self.assertEqual([], changes)
  2944. def test_hard_deletes_untracked_files(self) -> None:
  2945. """Test that reset --hard deletes files that don't exist in target tree."""
  2946. # Create and commit a file
  2947. fullpath = os.path.join(self.repo.path, "foo")
  2948. with open(fullpath, "w") as f:
  2949. f.write("BAR")
  2950. porcelain.add(self.repo.path, paths=[fullpath])
  2951. sha1 = porcelain.commit(
  2952. self.repo.path,
  2953. message=b"First commit",
  2954. committer=b"Jane <jane@example.com>",
  2955. author=b"John <john@example.com>",
  2956. )
  2957. # Create another file and commit
  2958. fullpath2 = os.path.join(self.repo.path, "bar")
  2959. with open(fullpath2, "w") as f:
  2960. f.write("BAZ")
  2961. porcelain.add(self.repo.path, paths=[fullpath2])
  2962. porcelain.commit(
  2963. self.repo.path,
  2964. message=b"Second commit",
  2965. committer=b"Jane <jane@example.com>",
  2966. author=b"John <john@example.com>",
  2967. )
  2968. # Reset hard to first commit - this should delete 'bar'
  2969. porcelain.reset(self.repo, "hard", sha1)
  2970. # Check that 'foo' still exists and 'bar' is deleted
  2971. self.assertTrue(os.path.exists(fullpath))
  2972. self.assertFalse(os.path.exists(fullpath2))
  2973. # Check index matches first commit
  2974. index = self.repo.open_index()
  2975. self.assertIn(b"foo", index)
  2976. self.assertNotIn(b"bar", index)
  2977. def test_hard_deletes_files_in_subdirs(self) -> None:
  2978. """Test that reset --hard deletes files in subdirectories."""
  2979. # Create and commit files in subdirectory
  2980. subdir = os.path.join(self.repo.path, "subdir")
  2981. os.makedirs(subdir)
  2982. file1 = os.path.join(subdir, "file1")
  2983. file2 = os.path.join(subdir, "file2")
  2984. with open(file1, "w") as f:
  2985. f.write("content1")
  2986. with open(file2, "w") as f:
  2987. f.write("content2")
  2988. porcelain.add(self.repo.path, paths=[file1, file2])
  2989. porcelain.commit(
  2990. self.repo.path,
  2991. message=b"First commit",
  2992. committer=b"Jane <jane@example.com>",
  2993. author=b"John <john@example.com>",
  2994. )
  2995. # Remove one file from subdirectory and commit
  2996. porcelain.rm(self.repo.path, paths=[file2])
  2997. sha2 = porcelain.commit(
  2998. self.repo.path,
  2999. message=b"Remove file2",
  3000. committer=b"Jane <jane@example.com>",
  3001. author=b"John <john@example.com>",
  3002. )
  3003. # Create file2 again (untracked)
  3004. with open(file2, "w") as f:
  3005. f.write("new content")
  3006. # Reset to commit that has file2 removed - untracked file2 should remain
  3007. porcelain.reset(self.repo, "hard", sha2)
  3008. self.assertTrue(os.path.exists(file1))
  3009. # Untracked files are not removed by reset --hard
  3010. self.assertTrue(os.path.exists(file2))
  3011. def test_hard_reset_to_remote_branch(self) -> None:
  3012. """Test reset --hard to remote branch deletes local files not in remote."""
  3013. # Create a file and commit
  3014. file1 = os.path.join(self.repo.path, "file1")
  3015. with open(file1, "w") as f:
  3016. f.write("content1")
  3017. porcelain.add(self.repo.path, paths=[file1])
  3018. sha1 = porcelain.commit(
  3019. self.repo.path,
  3020. message=b"Initial commit",
  3021. committer=b"Jane <jane@example.com>",
  3022. author=b"John <john@example.com>",
  3023. )
  3024. # Create a "remote" ref that doesn't have additional files
  3025. self.repo.refs[b"refs/remotes/origin/master"] = sha1
  3026. # Add another file locally and commit
  3027. file2 = os.path.join(self.repo.path, "file2")
  3028. with open(file2, "w") as f:
  3029. f.write("content2")
  3030. porcelain.add(self.repo.path, paths=[file2])
  3031. porcelain.commit(
  3032. self.repo.path,
  3033. message=b"Add file2",
  3034. committer=b"Jane <jane@example.com>",
  3035. author=b"John <john@example.com>",
  3036. )
  3037. # Both files should exist
  3038. self.assertTrue(os.path.exists(file1))
  3039. self.assertTrue(os.path.exists(file2))
  3040. # Reset to remote branch - should delete file2
  3041. porcelain.reset(self.repo, "hard", b"refs/remotes/origin/master")
  3042. # file1 should exist, file2 should be deleted
  3043. self.assertTrue(os.path.exists(file1))
  3044. self.assertFalse(os.path.exists(file2))
  3045. def test_mixed_reset(self) -> None:
  3046. # Create initial commit
  3047. fullpath = os.path.join(self.repo.path, "foo")
  3048. with open(fullpath, "w") as f:
  3049. f.write("BAR")
  3050. porcelain.add(self.repo.path, paths=[fullpath])
  3051. first_sha = porcelain.commit(
  3052. self.repo.path,
  3053. message=b"First commit",
  3054. committer=b"Jane <jane@example.com>",
  3055. author=b"John <john@example.com>",
  3056. )
  3057. # Make second commit with modified content
  3058. with open(fullpath, "w") as f:
  3059. f.write("BAZ")
  3060. porcelain.add(self.repo.path, paths=[fullpath])
  3061. porcelain.commit(
  3062. self.repo.path,
  3063. message=b"Second commit",
  3064. committer=b"Jane <jane@example.com>",
  3065. author=b"John <john@example.com>",
  3066. )
  3067. # Modify working tree without staging
  3068. with open(fullpath, "w") as f:
  3069. f.write("MODIFIED")
  3070. # Mixed reset to first commit
  3071. porcelain.reset(self.repo, "mixed", first_sha)
  3072. # Check that HEAD points to first commit
  3073. self.assertEqual(self.repo.head(), first_sha)
  3074. # Check that index matches first commit
  3075. index = self.repo.open_index()
  3076. changes = list(
  3077. tree_changes(
  3078. self.repo.object_store,
  3079. index.commit(self.repo.object_store),
  3080. self.repo[first_sha].tree,
  3081. )
  3082. )
  3083. self.assertEqual([], changes)
  3084. # Check that working tree is unchanged (still has "MODIFIED")
  3085. with open(fullpath) as f:
  3086. self.assertEqual(f.read(), "MODIFIED")
  3087. def test_soft_reset(self) -> None:
  3088. # Create initial commit
  3089. fullpath = os.path.join(self.repo.path, "foo")
  3090. with open(fullpath, "w") as f:
  3091. f.write("BAR")
  3092. porcelain.add(self.repo.path, paths=[fullpath])
  3093. first_sha = porcelain.commit(
  3094. self.repo.path,
  3095. message=b"First commit",
  3096. committer=b"Jane <jane@example.com>",
  3097. author=b"John <john@example.com>",
  3098. )
  3099. # Make second commit with modified content
  3100. with open(fullpath, "w") as f:
  3101. f.write("BAZ")
  3102. porcelain.add(self.repo.path, paths=[fullpath])
  3103. porcelain.commit(
  3104. self.repo.path,
  3105. message=b"Second commit",
  3106. committer=b"Jane <jane@example.com>",
  3107. author=b"John <john@example.com>",
  3108. )
  3109. # Stage a new change
  3110. with open(fullpath, "w") as f:
  3111. f.write("STAGED")
  3112. porcelain.add(self.repo.path, paths=[fullpath])
  3113. # Soft reset to first commit
  3114. porcelain.reset(self.repo, "soft", first_sha)
  3115. # Check that HEAD points to first commit
  3116. self.assertEqual(self.repo.head(), first_sha)
  3117. # Check that index still has the staged change (not reset)
  3118. index = self.repo.open_index()
  3119. # The index should still contain the staged content, not the first commit's content
  3120. self.assertIn(b"foo", index)
  3121. # Check that working tree is unchanged
  3122. with open(fullpath) as f:
  3123. self.assertEqual(f.read(), "STAGED")
  3124. class ResetFileTests(PorcelainTestCase):
  3125. def test_reset_modify_file_to_commit(self) -> None:
  3126. file = "foo"
  3127. full_path = os.path.join(self.repo.path, file)
  3128. with open(full_path, "w") as f:
  3129. f.write("hello")
  3130. porcelain.add(self.repo, paths=[full_path])
  3131. sha = porcelain.commit(
  3132. self.repo,
  3133. message=b"unitest",
  3134. committer=b"Jane <jane@example.com>",
  3135. author=b"John <john@example.com>",
  3136. )
  3137. with open(full_path, "a") as f:
  3138. f.write("something new")
  3139. porcelain.reset_file(self.repo, file, target=sha)
  3140. with open(full_path) as f:
  3141. self.assertEqual("hello", f.read())
  3142. def test_reset_remove_file_to_commit(self) -> None:
  3143. file = "foo"
  3144. full_path = os.path.join(self.repo.path, file)
  3145. with open(full_path, "w") as f:
  3146. f.write("hello")
  3147. porcelain.add(self.repo, paths=[full_path])
  3148. sha = porcelain.commit(
  3149. self.repo,
  3150. message=b"unitest",
  3151. committer=b"Jane <jane@example.com>",
  3152. author=b"John <john@example.com>",
  3153. )
  3154. os.remove(full_path)
  3155. porcelain.reset_file(self.repo, file, target=sha)
  3156. with open(full_path) as f:
  3157. self.assertEqual("hello", f.read())
  3158. def test_resetfile_with_dir(self) -> None:
  3159. os.mkdir(os.path.join(self.repo.path, "new_dir"))
  3160. full_path = os.path.join(self.repo.path, "new_dir", "foo")
  3161. with open(full_path, "w") as f:
  3162. f.write("hello")
  3163. porcelain.add(self.repo, paths=[full_path])
  3164. sha = porcelain.commit(
  3165. self.repo,
  3166. message=b"unitest",
  3167. committer=b"Jane <jane@example.com>",
  3168. author=b"John <john@example.com>",
  3169. )
  3170. with open(full_path, "a") as f:
  3171. f.write("something new")
  3172. porcelain.commit(
  3173. self.repo,
  3174. message=b"unitest 2",
  3175. committer=b"Jane <jane@example.com>",
  3176. author=b"John <john@example.com>",
  3177. )
  3178. porcelain.reset_file(self.repo, os.path.join("new_dir", "foo"), target=sha)
  3179. with open(full_path) as f:
  3180. self.assertEqual("hello", f.read())
  3181. def _commit_file_with_content(repo, filename, content):
  3182. file_path = os.path.join(repo.path, filename)
  3183. with open(file_path, "w") as f:
  3184. f.write(content)
  3185. porcelain.add(repo, paths=[file_path])
  3186. sha = porcelain.commit(
  3187. repo,
  3188. message=b"add " + filename.encode(),
  3189. committer=b"Jane <jane@example.com>",
  3190. author=b"John <john@example.com>",
  3191. )
  3192. return sha, file_path
  3193. class RevertTests(PorcelainTestCase):
  3194. def test_revert_simple(self) -> None:
  3195. # Create initial commit
  3196. fullpath = os.path.join(self.repo.path, "foo")
  3197. with open(fullpath, "w") as f:
  3198. f.write("initial content\n")
  3199. porcelain.add(self.repo.path, paths=[fullpath])
  3200. porcelain.commit(
  3201. self.repo.path,
  3202. message=b"Initial commit",
  3203. committer=b"Jane <jane@example.com>",
  3204. author=b"John <john@example.com>",
  3205. )
  3206. # Make a change
  3207. with open(fullpath, "w") as f:
  3208. f.write("modified content\n")
  3209. porcelain.add(self.repo.path, paths=[fullpath])
  3210. change_sha = porcelain.commit(
  3211. self.repo.path,
  3212. message=b"Change content",
  3213. committer=b"Jane <jane@example.com>",
  3214. author=b"John <john@example.com>",
  3215. )
  3216. # Revert the change
  3217. revert_sha = porcelain.revert(self.repo.path, commits=[change_sha])
  3218. # Check the file content is back to initial
  3219. with open(fullpath) as f:
  3220. self.assertEqual("initial content\n", f.read())
  3221. # Check the revert commit message
  3222. revert_commit = self.repo[revert_sha]
  3223. self.assertIn(b'Revert "Change content"', revert_commit.message)
  3224. self.assertIn(change_sha[:7], revert_commit.message)
  3225. def test_revert_multiple(self) -> None:
  3226. # Create initial commit
  3227. fullpath = os.path.join(self.repo.path, "foo")
  3228. with open(fullpath, "w") as f:
  3229. f.write("line1\n")
  3230. porcelain.add(self.repo.path, paths=[fullpath])
  3231. porcelain.commit(
  3232. self.repo.path,
  3233. message=b"Initial commit",
  3234. committer=b"Jane <jane@example.com>",
  3235. author=b"John <john@example.com>",
  3236. )
  3237. # Add line2
  3238. with open(fullpath, "a") as f:
  3239. f.write("line2\n")
  3240. porcelain.add(self.repo.path, paths=[fullpath])
  3241. commit1 = porcelain.commit(
  3242. self.repo.path,
  3243. message=b"Add line2",
  3244. committer=b"Jane <jane@example.com>",
  3245. author=b"John <john@example.com>",
  3246. )
  3247. # Add line3
  3248. with open(fullpath, "a") as f:
  3249. f.write("line3\n")
  3250. porcelain.add(self.repo.path, paths=[fullpath])
  3251. commit2 = porcelain.commit(
  3252. self.repo.path,
  3253. message=b"Add line3",
  3254. committer=b"Jane <jane@example.com>",
  3255. author=b"John <john@example.com>",
  3256. )
  3257. # Revert both commits (in reverse order)
  3258. porcelain.revert(self.repo.path, commits=[commit2, commit1])
  3259. # Check file is back to initial state
  3260. with open(fullpath) as f:
  3261. self.assertEqual("line1\n", f.read())
  3262. def test_revert_no_commit(self) -> None:
  3263. # Create initial commit
  3264. fullpath = os.path.join(self.repo.path, "foo")
  3265. with open(fullpath, "w") as f:
  3266. f.write("initial\n")
  3267. porcelain.add(self.repo.path, paths=[fullpath])
  3268. porcelain.commit(
  3269. self.repo.path,
  3270. message=b"Initial",
  3271. committer=b"Jane <jane@example.com>",
  3272. author=b"John <john@example.com>",
  3273. )
  3274. # Make a change
  3275. with open(fullpath, "w") as f:
  3276. f.write("changed\n")
  3277. porcelain.add(self.repo.path, paths=[fullpath])
  3278. change_sha = porcelain.commit(
  3279. self.repo.path,
  3280. message=b"Change",
  3281. committer=b"Jane <jane@example.com>",
  3282. author=b"John <john@example.com>",
  3283. )
  3284. # Revert with no_commit
  3285. result = porcelain.revert(self.repo.path, commits=[change_sha], no_commit=True)
  3286. # Should return None
  3287. self.assertIsNone(result)
  3288. # File should be reverted
  3289. with open(fullpath) as f:
  3290. self.assertEqual("initial\n", f.read())
  3291. # HEAD should still point to the change commit
  3292. self.assertEqual(self.repo.refs[b"HEAD"], change_sha)
  3293. def test_revert_custom_message(self) -> None:
  3294. # Create commits
  3295. fullpath = os.path.join(self.repo.path, "foo")
  3296. with open(fullpath, "w") as f:
  3297. f.write("initial\n")
  3298. porcelain.add(self.repo.path, paths=[fullpath])
  3299. porcelain.commit(
  3300. self.repo.path,
  3301. message=b"Initial",
  3302. committer=b"Jane <jane@example.com>",
  3303. author=b"John <john@example.com>",
  3304. )
  3305. with open(fullpath, "w") as f:
  3306. f.write("changed\n")
  3307. porcelain.add(self.repo.path, paths=[fullpath])
  3308. change_sha = porcelain.commit(
  3309. self.repo.path,
  3310. message=b"Change",
  3311. committer=b"Jane <jane@example.com>",
  3312. author=b"John <john@example.com>",
  3313. )
  3314. # Revert with custom message
  3315. custom_msg = "Custom revert message"
  3316. revert_sha = porcelain.revert(
  3317. self.repo.path, commits=[change_sha], message=custom_msg
  3318. )
  3319. # Check the message
  3320. revert_commit = self.repo[revert_sha]
  3321. self.assertEqual(custom_msg.encode("utf-8"), revert_commit.message)
  3322. def test_revert_no_parent(self) -> None:
  3323. # Try to revert the initial commit (no parent)
  3324. fullpath = os.path.join(self.repo.path, "foo")
  3325. with open(fullpath, "w") as f:
  3326. f.write("content\n")
  3327. porcelain.add(self.repo.path, paths=[fullpath])
  3328. initial_sha = porcelain.commit(
  3329. self.repo.path,
  3330. message=b"Initial",
  3331. committer=b"Jane <jane@example.com>",
  3332. author=b"John <john@example.com>",
  3333. )
  3334. # Should raise an error
  3335. with self.assertRaises(porcelain.Error) as cm:
  3336. porcelain.revert(self.repo.path, commits=[initial_sha])
  3337. self.assertIn("no parents", str(cm.exception))
  3338. class CheckoutTests(PorcelainTestCase):
  3339. def setUp(self) -> None:
  3340. super().setUp()
  3341. self._sha, self._foo_path = _commit_file_with_content(
  3342. self.repo, "foo", "hello\n"
  3343. )
  3344. porcelain.branch_create(self.repo, "uni")
  3345. def test_checkout_to_existing_branch(self) -> None:
  3346. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3347. porcelain.checkout(self.repo, b"uni")
  3348. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3349. def test_checkout_to_non_existing_branch(self) -> None:
  3350. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3351. with self.assertRaises(KeyError):
  3352. porcelain.checkout(self.repo, b"bob")
  3353. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3354. def test_checkout_to_branch_with_modified_files(self) -> None:
  3355. with open(self._foo_path, "a") as f:
  3356. f.write("new message\n")
  3357. porcelain.add(self.repo, paths=[self._foo_path])
  3358. status = list(porcelain.status(self.repo))
  3359. self.assertEqual(
  3360. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  3361. )
  3362. # The new checkout behavior prevents switching with staged changes
  3363. with self.assertRaises(porcelain.CheckoutError):
  3364. porcelain.checkout(self.repo, b"uni")
  3365. # Should still be on master
  3366. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3367. # Force checkout should work
  3368. porcelain.checkout(self.repo, b"uni", force=True)
  3369. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3370. def test_checkout_with_deleted_files(self) -> None:
  3371. porcelain.remove(self.repo.path, [os.path.join(self.repo.path, "foo")])
  3372. status = list(porcelain.status(self.repo))
  3373. self.assertEqual(
  3374. [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status
  3375. )
  3376. # The new checkout behavior prevents switching with staged deletions
  3377. with self.assertRaises(porcelain.CheckoutError):
  3378. porcelain.checkout(self.repo, b"uni")
  3379. # Should still be on master
  3380. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3381. # Force checkout should work
  3382. porcelain.checkout(self.repo, b"uni", force=True)
  3383. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3384. def test_checkout_to_branch_with_added_files(self) -> None:
  3385. file_path = os.path.join(self.repo.path, "bar")
  3386. with open(file_path, "w") as f:
  3387. f.write("bar content\n")
  3388. porcelain.add(self.repo, paths=[file_path])
  3389. status = list(porcelain.status(self.repo))
  3390. self.assertEqual(
  3391. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3392. )
  3393. # Both branches have file 'foo' checkout should be fine.
  3394. porcelain.checkout(self.repo, b"uni")
  3395. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3396. status = list(porcelain.status(self.repo))
  3397. self.assertEqual(
  3398. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3399. )
  3400. def test_checkout_to_branch_with_modified_file_not_present(self) -> None:
  3401. # Commit a new file that the other branch doesn't have.
  3402. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3403. # Modify the file the other branch doesn't have.
  3404. with open(nee_path, "a") as f:
  3405. f.write("bar content\n")
  3406. porcelain.add(self.repo, paths=[nee_path])
  3407. status = list(porcelain.status(self.repo))
  3408. self.assertEqual(
  3409. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3410. )
  3411. # Checkout should fail when there are staged changes that would be lost
  3412. # This matches Git's behavior to prevent data loss
  3413. from dulwich.errors import WorkingTreeModifiedError
  3414. with self.assertRaises(WorkingTreeModifiedError) as cm:
  3415. porcelain.checkout(self.repo, b"uni")
  3416. self.assertIn("nee", str(cm.exception))
  3417. # Should still be on master branch
  3418. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3419. # The staged changes should still be present
  3420. status = list(porcelain.status(self.repo))
  3421. self.assertEqual(
  3422. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3423. )
  3424. self.assertTrue(os.path.exists(nee_path))
  3425. # Force checkout should work and lose the changes
  3426. porcelain.checkout(self.repo, b"uni", force=True)
  3427. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3428. # Now the file should be gone
  3429. self.assertFalse(os.path.exists(nee_path))
  3430. def test_checkout_to_branch_with_modified_file_not_present_forced(self) -> None:
  3431. # Commit a new file that the other branch doesn't have.
  3432. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3433. # Modify the file the other branch doesn't have.
  3434. with open(nee_path, "a") as f:
  3435. f.write("bar content\n")
  3436. porcelain.add(self.repo, paths=[nee_path])
  3437. status = list(porcelain.status(self.repo))
  3438. self.assertEqual(
  3439. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3440. )
  3441. # 'uni' branch doesn't have 'nee' and it has been modified, but we force to reset the entire index.
  3442. porcelain.checkout(self.repo, b"uni", force=True)
  3443. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3444. status = list(porcelain.status(self.repo))
  3445. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3446. def test_checkout_to_branch_with_unstaged_files(self) -> None:
  3447. # Edit `foo`.
  3448. with open(self._foo_path, "a") as f:
  3449. f.write("new message")
  3450. status = list(porcelain.status(self.repo))
  3451. self.assertEqual(
  3452. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  3453. )
  3454. # The new checkout behavior prevents switching with unstaged changes
  3455. with self.assertRaises(porcelain.CheckoutError):
  3456. porcelain.checkout(self.repo, b"uni")
  3457. # Should still be on master
  3458. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3459. # Force checkout should work
  3460. porcelain.checkout(self.repo, b"uni", force=True)
  3461. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3462. def test_checkout_to_branch_with_untracked_files(self) -> None:
  3463. with open(os.path.join(self.repo.path, "neu"), "a") as f:
  3464. f.write("new message\n")
  3465. status = list(porcelain.status(self.repo))
  3466. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3467. porcelain.checkout(self.repo, b"uni")
  3468. status = list(porcelain.status(self.repo))
  3469. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3470. def test_checkout_to_branch_with_new_files(self) -> None:
  3471. porcelain.checkout(self.repo, b"uni")
  3472. sub_directory = os.path.join(self.repo.path, "sub1")
  3473. os.mkdir(sub_directory)
  3474. for index in range(5):
  3475. _commit_file_with_content(
  3476. self.repo, "new_file_" + str(index + 1), "Some content\n"
  3477. )
  3478. _commit_file_with_content(
  3479. self.repo,
  3480. os.path.join("sub1", "new_file_" + str(index + 10)),
  3481. "Good content\n",
  3482. )
  3483. status = list(porcelain.status(self.repo))
  3484. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3485. porcelain.checkout(self.repo, b"master")
  3486. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3487. status = list(porcelain.status(self.repo))
  3488. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3489. porcelain.checkout(self.repo, b"uni")
  3490. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3491. status = list(porcelain.status(self.repo))
  3492. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3493. def test_checkout_to_branch_with_file_in_sub_directory(self) -> None:
  3494. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3495. os.makedirs(sub_directory)
  3496. sub_directory_file = os.path.join(sub_directory, "neu")
  3497. with open(sub_directory_file, "w") as f:
  3498. f.write("new message\n")
  3499. porcelain.add(self.repo, paths=[sub_directory_file])
  3500. porcelain.commit(
  3501. self.repo,
  3502. message=b"add " + sub_directory_file.encode(),
  3503. committer=b"Jane <jane@example.com>",
  3504. author=b"John <john@example.com>",
  3505. )
  3506. status = list(porcelain.status(self.repo))
  3507. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3508. self.assertTrue(os.path.isdir(sub_directory))
  3509. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3510. porcelain.checkout(self.repo, b"uni")
  3511. status = list(porcelain.status(self.repo))
  3512. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3513. self.assertFalse(os.path.isdir(sub_directory))
  3514. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3515. porcelain.checkout(self.repo, b"master")
  3516. self.assertTrue(os.path.isdir(sub_directory))
  3517. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3518. def test_checkout_to_branch_with_multiple_files_in_sub_directory(self) -> None:
  3519. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3520. os.makedirs(sub_directory)
  3521. sub_directory_file_1 = os.path.join(sub_directory, "neu")
  3522. with open(sub_directory_file_1, "w") as f:
  3523. f.write("new message\n")
  3524. sub_directory_file_2 = os.path.join(sub_directory, "gus")
  3525. with open(sub_directory_file_2, "w") as f:
  3526. f.write("alternative message\n")
  3527. porcelain.add(self.repo, paths=[sub_directory_file_1, sub_directory_file_2])
  3528. porcelain.commit(
  3529. self.repo,
  3530. message=b"add files neu and gus.",
  3531. committer=b"Jane <jane@example.com>",
  3532. author=b"John <john@example.com>",
  3533. )
  3534. status = list(porcelain.status(self.repo))
  3535. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3536. self.assertTrue(os.path.isdir(sub_directory))
  3537. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3538. porcelain.checkout(self.repo, b"uni")
  3539. status = list(porcelain.status(self.repo))
  3540. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3541. self.assertFalse(os.path.isdir(sub_directory))
  3542. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3543. def _commit_something_wrong(self):
  3544. with open(self._foo_path, "a") as f:
  3545. f.write("something wrong")
  3546. porcelain.add(self.repo, paths=[self._foo_path])
  3547. return porcelain.commit(
  3548. self.repo,
  3549. message=b"I may added something wrong",
  3550. committer=b"Jane <jane@example.com>",
  3551. author=b"John <john@example.com>",
  3552. )
  3553. def test_checkout_to_commit_sha(self) -> None:
  3554. self._commit_something_wrong()
  3555. porcelain.checkout(self.repo, self._sha)
  3556. self.assertEqual(self._sha, self.repo.head())
  3557. def test_checkout_to_head(self) -> None:
  3558. new_sha = self._commit_something_wrong()
  3559. porcelain.checkout(self.repo, b"HEAD")
  3560. self.assertEqual(new_sha, self.repo.head())
  3561. def _checkout_remote_branch(self):
  3562. errstream = BytesIO()
  3563. outstream = BytesIO()
  3564. porcelain.commit(
  3565. repo=self.repo.path,
  3566. message=b"init",
  3567. author=b"author <email>",
  3568. committer=b"committer <email>",
  3569. )
  3570. # Setup target repo cloned from temp test repo
  3571. clone_path = tempfile.mkdtemp()
  3572. self.addCleanup(shutil.rmtree, clone_path)
  3573. target_repo = porcelain.clone(
  3574. self.repo.path, target=clone_path, errstream=errstream
  3575. )
  3576. self.addCleanup(target_repo.close)
  3577. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  3578. # create a second file to be pushed back to origin
  3579. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3580. os.close(handle)
  3581. porcelain.add(repo=clone_path, paths=[fullpath])
  3582. porcelain.commit(
  3583. repo=clone_path,
  3584. message=b"push",
  3585. author=b"author <email>",
  3586. committer=b"committer <email>",
  3587. )
  3588. # Setup a non-checked out branch in the remote
  3589. refs_path = b"refs/heads/foo"
  3590. new_id = self.repo[b"HEAD"].id
  3591. self.assertNotEqual(new_id, ZERO_SHA)
  3592. self.repo.refs[refs_path] = new_id
  3593. # Push to the remote
  3594. porcelain.push(
  3595. clone_path,
  3596. "origin",
  3597. b"HEAD:" + refs_path,
  3598. outstream=outstream,
  3599. errstream=errstream,
  3600. )
  3601. self.assertEqual(
  3602. target_repo.refs[b"refs/remotes/origin/foo"],
  3603. target_repo.refs[b"HEAD"],
  3604. )
  3605. # The new checkout behavior treats origin/foo as a ref and creates detached HEAD
  3606. porcelain.checkout(target_repo, b"origin/foo")
  3607. original_id = target_repo[b"HEAD"].id
  3608. uni_id = target_repo[b"refs/remotes/origin/uni"].id
  3609. # Should be in detached HEAD state
  3610. with self.assertRaises((ValueError, IndexError)):
  3611. porcelain.active_branch(target_repo)
  3612. expected_refs = {
  3613. b"HEAD": original_id,
  3614. b"refs/heads/master": original_id,
  3615. # No local foo branch is created anymore
  3616. b"refs/remotes/origin/foo": original_id,
  3617. b"refs/remotes/origin/uni": uni_id,
  3618. b"refs/remotes/origin/HEAD": new_id,
  3619. b"refs/remotes/origin/master": new_id,
  3620. }
  3621. self.assertEqual(expected_refs, target_repo.get_refs())
  3622. return target_repo
  3623. def test_checkout_remote_branch(self) -> None:
  3624. repo = self._checkout_remote_branch()
  3625. repo.close()
  3626. def test_checkout_remote_branch_then_master_then_remote_branch_again(self) -> None:
  3627. target_repo = self._checkout_remote_branch()
  3628. # Should be in detached HEAD state
  3629. with self.assertRaises((ValueError, IndexError)):
  3630. porcelain.active_branch(target_repo)
  3631. # Save the commit SHA before adding bar
  3632. detached_commit_sha, _ = _commit_file_with_content(
  3633. target_repo, "bar", "something\n"
  3634. )
  3635. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3636. porcelain.checkout(target_repo, b"master")
  3637. self.assertEqual(b"master", porcelain.active_branch(target_repo))
  3638. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3639. # Going back to origin/foo won't have bar because the commit was made in detached state
  3640. porcelain.checkout(target_repo, b"origin/foo")
  3641. # Should be in detached HEAD state again
  3642. with self.assertRaises((ValueError, IndexError)):
  3643. porcelain.active_branch(target_repo)
  3644. # bar is NOT there because we're back at the original origin/foo commit
  3645. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3646. # But we can checkout the specific commit to get bar back
  3647. porcelain.checkout(target_repo, detached_commit_sha.decode())
  3648. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3649. target_repo.close()
  3650. def test_checkout_new_branch_from_remote_sets_tracking(self) -> None:
  3651. # Create a "remote" repository
  3652. remote_path = tempfile.mkdtemp()
  3653. self.addCleanup(shutil.rmtree, remote_path)
  3654. remote_repo = porcelain.init(remote_path)
  3655. # Add a commit to the remote
  3656. remote_sha, _ = _commit_file_with_content(
  3657. remote_repo, "bar", "remote content\n"
  3658. )
  3659. # Clone the remote repository
  3660. target_path = tempfile.mkdtemp()
  3661. self.addCleanup(shutil.rmtree, target_path)
  3662. target_repo = porcelain.clone(remote_path, target_path)
  3663. self.addCleanup(target_repo.close)
  3664. # Create a remote tracking branch reference
  3665. remote_branch_ref = b"refs/remotes/origin/feature"
  3666. target_repo.refs[remote_branch_ref] = remote_sha
  3667. # Checkout a new branch from the remote branch
  3668. porcelain.checkout(target_repo, remote_branch_ref, new_branch=b"local-feature")
  3669. # Verify the branch was created and is active
  3670. self.assertEqual(b"local-feature", porcelain.active_branch(target_repo))
  3671. # Verify tracking configuration was set
  3672. config = target_repo.get_config()
  3673. self.assertEqual(
  3674. b"origin", config.get((b"branch", b"local-feature"), b"remote")
  3675. )
  3676. self.assertEqual(
  3677. b"refs/heads/feature", config.get((b"branch", b"local-feature"), b"merge")
  3678. )
  3679. target_repo.close()
  3680. remote_repo.close()
  3681. class GeneralCheckoutTests(PorcelainTestCase):
  3682. """Tests for the general checkout function that handles branches, tags, and commits."""
  3683. def setUp(self) -> None:
  3684. super().setUp()
  3685. # Create initial commit
  3686. self._sha1, self._foo_path = _commit_file_with_content(
  3687. self.repo, "foo", "initial content\n"
  3688. )
  3689. # Create a branch
  3690. porcelain.branch_create(self.repo, "feature")
  3691. # Create another commit on master
  3692. self._sha2, self._bar_path = _commit_file_with_content(
  3693. self.repo, "bar", "bar content\n"
  3694. )
  3695. # Create a tag
  3696. porcelain.tag_create(self.repo, "v1.0", objectish=self._sha1)
  3697. def test_checkout_branch(self) -> None:
  3698. """Test checking out a branch."""
  3699. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3700. # Checkout feature branch
  3701. porcelain.checkout(self.repo, "feature")
  3702. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3703. # File 'bar' should not exist in feature branch
  3704. self.assertFalse(os.path.exists(self._bar_path))
  3705. # Go back to master
  3706. porcelain.checkout(self.repo, "master")
  3707. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3708. # File 'bar' should exist again
  3709. self.assertTrue(os.path.exists(self._bar_path))
  3710. def test_checkout_commit(self) -> None:
  3711. """Test checking out a specific commit (detached HEAD)."""
  3712. # Checkout first commit by SHA
  3713. porcelain.checkout(self.repo, self._sha1.decode("ascii"))
  3714. # Should be in detached HEAD state - active_branch raises IndexError
  3715. with self.assertRaises((ValueError, IndexError)):
  3716. porcelain.active_branch(self.repo)
  3717. # File 'bar' should not exist
  3718. self.assertFalse(os.path.exists(self._bar_path))
  3719. # HEAD should point to the commit
  3720. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3721. def test_checkout_tag(self) -> None:
  3722. """Test checking out a tag (detached HEAD)."""
  3723. # Checkout tag
  3724. porcelain.checkout(self.repo, "v1.0")
  3725. # Should be in detached HEAD state - active_branch raises IndexError
  3726. with self.assertRaises((ValueError, IndexError)):
  3727. porcelain.active_branch(self.repo)
  3728. # File 'bar' should not exist (tag points to first commit)
  3729. self.assertFalse(os.path.exists(self._bar_path))
  3730. # HEAD should point to the tagged commit
  3731. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3732. def test_checkout_new_branch(self) -> None:
  3733. """Test creating a new branch during checkout (like git checkout -b)."""
  3734. # Create and checkout new branch from current HEAD
  3735. porcelain.checkout(self.repo, "master", new_branch="new-feature")
  3736. self.assertEqual(b"new-feature", porcelain.active_branch(self.repo))
  3737. self.assertTrue(os.path.exists(self._bar_path))
  3738. # Create and checkout new branch from specific commit
  3739. porcelain.checkout(self.repo, self._sha1.decode("ascii"), new_branch="from-old")
  3740. self.assertEqual(b"from-old", porcelain.active_branch(self.repo))
  3741. self.assertFalse(os.path.exists(self._bar_path))
  3742. def test_checkout_with_uncommitted_changes(self) -> None:
  3743. """Test checkout behavior with uncommitted changes."""
  3744. # Modify a file
  3745. with open(self._foo_path, "w") as f:
  3746. f.write("modified content\n")
  3747. # Should raise error when trying to checkout
  3748. with self.assertRaises(porcelain.CheckoutError) as cm:
  3749. porcelain.checkout(self.repo, "feature")
  3750. self.assertIn("local changes", str(cm.exception))
  3751. self.assertIn("foo", str(cm.exception))
  3752. # Should still be on master
  3753. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3754. def test_checkout_force(self) -> None:
  3755. """Test forced checkout discards local changes for files that differ between branches."""
  3756. # Modify a file
  3757. with open(self._foo_path, "w") as f:
  3758. f.write("modified content\n")
  3759. # Force checkout should succeed
  3760. porcelain.checkout(self.repo, "feature", force=True)
  3761. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3762. # Since foo has the same content in master and feature branches,
  3763. # checkout should NOT restore it - the modified content should remain
  3764. with open(self._foo_path) as f:
  3765. content = f.read()
  3766. self.assertEqual("modified content\n", content)
  3767. def test_checkout_nonexistent_ref(self) -> None:
  3768. """Test checkout of non-existent branch/commit."""
  3769. with self.assertRaises(KeyError):
  3770. porcelain.checkout(self.repo, "nonexistent")
  3771. def test_checkout_partial_sha(self) -> None:
  3772. """Test checkout with partial SHA."""
  3773. # Git typically allows checkout with partial SHA
  3774. partial_sha = self._sha1.decode("ascii")[:7]
  3775. porcelain.checkout(self.repo, partial_sha)
  3776. # Should be in detached HEAD state at the right commit
  3777. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3778. def test_checkout_preserves_untracked_files(self) -> None:
  3779. """Test that checkout preserves untracked files."""
  3780. # Create an untracked file
  3781. untracked_path = os.path.join(self.repo.path, "untracked.txt")
  3782. with open(untracked_path, "w") as f:
  3783. f.write("untracked content\n")
  3784. # Checkout another branch
  3785. porcelain.checkout(self.repo, "feature")
  3786. # Untracked file should still exist
  3787. self.assertTrue(os.path.exists(untracked_path))
  3788. with open(untracked_path) as f:
  3789. content = f.read()
  3790. self.assertEqual("untracked content\n", content)
  3791. def test_checkout_full_ref_paths(self) -> None:
  3792. """Test checkout with full ref paths."""
  3793. # Test checkout with full branch ref path
  3794. porcelain.checkout(self.repo, "refs/heads/feature")
  3795. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3796. # Test checkout with full tag ref path
  3797. porcelain.checkout(self.repo, "refs/tags/v1.0")
  3798. # Should be in detached HEAD state
  3799. with self.assertRaises((ValueError, IndexError)):
  3800. porcelain.active_branch(self.repo)
  3801. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3802. def test_checkout_bytes_vs_string_target(self) -> None:
  3803. """Test that checkout works with both bytes and string targets."""
  3804. # Test with string target
  3805. porcelain.checkout(self.repo, "feature")
  3806. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3807. # Test with bytes target
  3808. porcelain.checkout(self.repo, b"master")
  3809. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3810. def test_checkout_new_branch_from_commit(self) -> None:
  3811. """Test creating a new branch from a specific commit."""
  3812. # Create new branch from first commit
  3813. porcelain.checkout(self.repo, self._sha1.decode(), new_branch="from-commit")
  3814. self.assertEqual(b"from-commit", porcelain.active_branch(self.repo))
  3815. # Should be at the first commit (no bar file)
  3816. self.assertFalse(os.path.exists(self._bar_path))
  3817. def test_checkout_with_staged_addition(self) -> None:
  3818. """Test checkout behavior with staged file additions."""
  3819. # Create and stage a new file that doesn't exist in target branch
  3820. new_file_path = os.path.join(self.repo.path, "new.txt")
  3821. with open(new_file_path, "w") as f:
  3822. f.write("new file content\n")
  3823. porcelain.add(self.repo, [new_file_path])
  3824. # This should succeed because the file doesn't exist in target branch
  3825. porcelain.checkout(self.repo, "feature")
  3826. # Should be on feature branch
  3827. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3828. # The new file should still exist and be staged
  3829. self.assertTrue(os.path.exists(new_file_path))
  3830. status = porcelain.status(self.repo)
  3831. self.assertIn(b"new.txt", status.staged["add"])
  3832. def test_checkout_with_staged_modification_conflict(self) -> None:
  3833. """Test checkout behavior with staged modifications that would conflict."""
  3834. # Stage changes to a file that exists in both branches
  3835. with open(self._foo_path, "w") as f:
  3836. f.write("modified content\n")
  3837. porcelain.add(self.repo, [self._foo_path])
  3838. # Should prevent checkout due to staged changes to existing file
  3839. with self.assertRaises(porcelain.CheckoutError) as cm:
  3840. porcelain.checkout(self.repo, "feature")
  3841. self.assertIn("local changes", str(cm.exception))
  3842. self.assertIn("foo", str(cm.exception))
  3843. def test_checkout_head_reference(self) -> None:
  3844. """Test checkout of HEAD reference."""
  3845. # Move to feature branch first
  3846. porcelain.checkout(self.repo, "feature")
  3847. # Checkout HEAD creates detached HEAD state
  3848. porcelain.checkout(self.repo, "HEAD")
  3849. # Should be in detached HEAD state
  3850. with self.assertRaises((ValueError, IndexError)):
  3851. porcelain.active_branch(self.repo)
  3852. def test_checkout_error_messages(self) -> None:
  3853. """Test that checkout error messages are helpful."""
  3854. # Create uncommitted changes
  3855. with open(self._foo_path, "w") as f:
  3856. f.write("uncommitted changes\n")
  3857. # Try to checkout
  3858. with self.assertRaises(porcelain.CheckoutError) as cm:
  3859. porcelain.checkout(self.repo, "feature")
  3860. error_msg = str(cm.exception)
  3861. self.assertIn("local changes", error_msg)
  3862. self.assertIn("foo", error_msg)
  3863. self.assertIn("overwritten", error_msg)
  3864. self.assertIn("commit or stash", error_msg)
  3865. class SubmoduleTests(PorcelainTestCase):
  3866. def test_empty(self) -> None:
  3867. porcelain.commit(
  3868. repo=self.repo.path,
  3869. message=b"init",
  3870. author=b"author <email>",
  3871. committer=b"committer <email>",
  3872. )
  3873. self.assertEqual([], list(porcelain.submodule_list(self.repo)))
  3874. def test_add(self) -> None:
  3875. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  3876. with open(f"{self.repo.path}/.gitmodules") as f:
  3877. self.assertEqual(
  3878. """\
  3879. [submodule "bar"]
  3880. \turl = ../bar.git
  3881. \tpath = bar
  3882. """,
  3883. f.read(),
  3884. )
  3885. def test_init(self) -> None:
  3886. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  3887. porcelain.submodule_init(self.repo)
  3888. def test_update(self) -> None:
  3889. # Create a submodule repository
  3890. sub_repo_path = tempfile.mkdtemp()
  3891. self.addCleanup(shutil.rmtree, sub_repo_path)
  3892. sub_repo = Repo.init(sub_repo_path)
  3893. self.addCleanup(sub_repo.close)
  3894. # Add a file to the submodule repo
  3895. sub_file = os.path.join(sub_repo_path, "test.txt")
  3896. with open(sub_file, "w") as f:
  3897. f.write("submodule content")
  3898. porcelain.add(sub_repo, paths=[sub_file])
  3899. sub_commit = porcelain.commit(
  3900. sub_repo,
  3901. message=b"Initial submodule commit",
  3902. author=b"Test Author <test@example.com>",
  3903. committer=b"Test Committer <test@example.com>",
  3904. )
  3905. # Add the submodule to the main repository
  3906. porcelain.submodule_add(self.repo, sub_repo_path, "test_submodule")
  3907. # Manually add the submodule to the index
  3908. from dulwich.index import IndexEntry
  3909. from dulwich.objects import S_IFGITLINK
  3910. index = self.repo.open_index()
  3911. index[b"test_submodule"] = IndexEntry(
  3912. ctime=0,
  3913. mtime=0,
  3914. dev=0,
  3915. ino=0,
  3916. mode=S_IFGITLINK,
  3917. uid=0,
  3918. gid=0,
  3919. size=0,
  3920. sha=sub_commit,
  3921. flags=0,
  3922. )
  3923. index.write()
  3924. porcelain.add(self.repo, paths=[".gitmodules"])
  3925. porcelain.commit(
  3926. self.repo,
  3927. message=b"Add submodule",
  3928. author=b"Test Author <test@example.com>",
  3929. committer=b"Test Committer <test@example.com>",
  3930. )
  3931. # Initialize and update the submodule
  3932. porcelain.submodule_init(self.repo)
  3933. porcelain.submodule_update(self.repo)
  3934. # Check that the submodule directory exists
  3935. submodule_path = os.path.join(self.repo.path, "test_submodule")
  3936. self.assertTrue(os.path.exists(submodule_path))
  3937. # Check that the submodule file exists
  3938. submodule_file = os.path.join(submodule_path, "test.txt")
  3939. self.assertTrue(os.path.exists(submodule_file))
  3940. with open(submodule_file) as f:
  3941. self.assertEqual(f.read(), "submodule content")
  3942. class PushTests(PorcelainTestCase):
  3943. def test_simple(self) -> None:
  3944. """Basic test of porcelain push where self.repo is the remote. First
  3945. clone the remote, commit a file to the clone, then push the changes
  3946. back to the remote.
  3947. """
  3948. outstream = BytesIO()
  3949. errstream = BytesIO()
  3950. porcelain.commit(
  3951. repo=self.repo.path,
  3952. message=b"init",
  3953. author=b"author <email>",
  3954. committer=b"committer <email>",
  3955. )
  3956. # Setup target repo cloned from temp test repo
  3957. clone_path = tempfile.mkdtemp()
  3958. self.addCleanup(shutil.rmtree, clone_path)
  3959. target_repo = porcelain.clone(
  3960. self.repo.path, target=clone_path, errstream=errstream
  3961. )
  3962. self.addCleanup(target_repo.close)
  3963. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  3964. # create a second file to be pushed back to origin
  3965. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3966. os.close(handle)
  3967. porcelain.add(repo=clone_path, paths=[fullpath])
  3968. porcelain.commit(
  3969. repo=clone_path,
  3970. message=b"push",
  3971. author=b"author <email>",
  3972. committer=b"committer <email>",
  3973. )
  3974. # Setup a non-checked out branch in the remote
  3975. refs_path = b"refs/heads/foo"
  3976. new_id = self.repo[b"HEAD"].id
  3977. self.assertNotEqual(new_id, ZERO_SHA)
  3978. self.repo.refs[refs_path] = new_id
  3979. # Push to the remote
  3980. porcelain.push(
  3981. clone_path,
  3982. "origin",
  3983. b"HEAD:" + refs_path,
  3984. outstream=outstream,
  3985. errstream=errstream,
  3986. )
  3987. self.assertEqual(
  3988. target_repo.refs[b"refs/remotes/origin/foo"],
  3989. target_repo.refs[b"HEAD"],
  3990. )
  3991. # Check that the target and source
  3992. with Repo(clone_path) as r_clone:
  3993. self.assertEqual(
  3994. {
  3995. b"HEAD": new_id,
  3996. b"refs/heads/foo": r_clone[b"HEAD"].id,
  3997. b"refs/heads/master": new_id,
  3998. },
  3999. self.repo.get_refs(),
  4000. )
  4001. self.assertEqual(r_clone[b"HEAD"].id, self.repo[refs_path].id)
  4002. # Get the change in the target repo corresponding to the add
  4003. # this will be in the foo branch.
  4004. change = next(
  4005. iter(
  4006. tree_changes(
  4007. self.repo.object_store,
  4008. self.repo[b"HEAD"].tree,
  4009. self.repo[b"refs/heads/foo"].tree,
  4010. )
  4011. )
  4012. )
  4013. self.assertEqual(
  4014. os.path.basename(fullpath), change.new.path.decode("ascii")
  4015. )
  4016. def test_local_missing(self) -> None:
  4017. """Pushing a new branch."""
  4018. outstream = BytesIO()
  4019. errstream = BytesIO()
  4020. # Setup target repo cloned from temp test repo
  4021. clone_path = tempfile.mkdtemp()
  4022. self.addCleanup(shutil.rmtree, clone_path)
  4023. target_repo = porcelain.init(clone_path)
  4024. target_repo.close()
  4025. self.assertRaises(
  4026. porcelain.Error,
  4027. porcelain.push,
  4028. self.repo,
  4029. clone_path,
  4030. b"HEAD:refs/heads/master",
  4031. outstream=outstream,
  4032. errstream=errstream,
  4033. )
  4034. def test_new(self) -> None:
  4035. """Pushing a new branch."""
  4036. outstream = BytesIO()
  4037. errstream = BytesIO()
  4038. # Setup target repo cloned from temp test repo
  4039. clone_path = tempfile.mkdtemp()
  4040. self.addCleanup(shutil.rmtree, clone_path)
  4041. target_repo = porcelain.init(clone_path)
  4042. target_repo.close()
  4043. # create a second file to be pushed back to origin
  4044. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4045. os.close(handle)
  4046. porcelain.add(repo=clone_path, paths=[fullpath])
  4047. new_id = porcelain.commit(
  4048. repo=self.repo,
  4049. message=b"push",
  4050. author=b"author <email>",
  4051. committer=b"committer <email>",
  4052. )
  4053. # Push to the remote
  4054. porcelain.push(
  4055. self.repo,
  4056. clone_path,
  4057. b"HEAD:refs/heads/master",
  4058. outstream=outstream,
  4059. errstream=errstream,
  4060. )
  4061. with Repo(clone_path) as r_clone:
  4062. self.assertEqual(
  4063. {
  4064. b"HEAD": new_id,
  4065. b"refs/heads/master": new_id,
  4066. },
  4067. r_clone.get_refs(),
  4068. )
  4069. def test_delete(self) -> None:
  4070. """Basic test of porcelain push, removing a branch."""
  4071. outstream = BytesIO()
  4072. errstream = BytesIO()
  4073. porcelain.commit(
  4074. repo=self.repo.path,
  4075. message=b"init",
  4076. author=b"author <email>",
  4077. committer=b"committer <email>",
  4078. )
  4079. # Setup target repo cloned from temp test repo
  4080. clone_path = tempfile.mkdtemp()
  4081. self.addCleanup(shutil.rmtree, clone_path)
  4082. target_repo = porcelain.clone(
  4083. self.repo.path, target=clone_path, errstream=errstream
  4084. )
  4085. target_repo.close()
  4086. # Setup a non-checked out branch in the remote
  4087. refs_path = b"refs/heads/foo"
  4088. new_id = self.repo[b"HEAD"].id
  4089. self.assertNotEqual(new_id, ZERO_SHA)
  4090. self.repo.refs[refs_path] = new_id
  4091. # Push to the remote
  4092. porcelain.push(
  4093. clone_path,
  4094. self.repo.path,
  4095. b":" + refs_path,
  4096. outstream=outstream,
  4097. errstream=errstream,
  4098. )
  4099. self.assertEqual(
  4100. {
  4101. b"HEAD": new_id,
  4102. b"refs/heads/master": new_id,
  4103. },
  4104. self.repo.get_refs(),
  4105. )
  4106. def test_diverged(self) -> None:
  4107. outstream = BytesIO()
  4108. errstream = BytesIO()
  4109. porcelain.commit(
  4110. repo=self.repo.path,
  4111. message=b"init",
  4112. author=b"author <email>",
  4113. committer=b"committer <email>",
  4114. )
  4115. # Setup target repo cloned from temp test repo
  4116. clone_path = tempfile.mkdtemp()
  4117. self.addCleanup(shutil.rmtree, clone_path)
  4118. target_repo = porcelain.clone(
  4119. self.repo.path, target=clone_path, errstream=errstream
  4120. )
  4121. target_repo.close()
  4122. remote_id = porcelain.commit(
  4123. repo=self.repo.path,
  4124. message=b"remote change",
  4125. author=b"author <email>",
  4126. committer=b"committer <email>",
  4127. )
  4128. local_id = porcelain.commit(
  4129. repo=clone_path,
  4130. message=b"local change",
  4131. author=b"author <email>",
  4132. committer=b"committer <email>",
  4133. )
  4134. outstream = BytesIO()
  4135. errstream = BytesIO()
  4136. # Push to the remote
  4137. self.assertRaises(
  4138. porcelain.DivergedBranches,
  4139. porcelain.push,
  4140. clone_path,
  4141. self.repo.path,
  4142. b"refs/heads/master",
  4143. outstream=outstream,
  4144. errstream=errstream,
  4145. )
  4146. self.assertEqual(
  4147. {
  4148. b"HEAD": remote_id,
  4149. b"refs/heads/master": remote_id,
  4150. },
  4151. self.repo.get_refs(),
  4152. )
  4153. self.assertEqual(b"", outstream.getvalue())
  4154. self.assertEqual(b"", errstream.getvalue())
  4155. outstream = BytesIO()
  4156. errstream = BytesIO()
  4157. # Push to the remote with --force
  4158. porcelain.push(
  4159. clone_path,
  4160. self.repo.path,
  4161. b"refs/heads/master",
  4162. outstream=outstream,
  4163. errstream=errstream,
  4164. force=True,
  4165. )
  4166. self.assertEqual(
  4167. {
  4168. b"HEAD": local_id,
  4169. b"refs/heads/master": local_id,
  4170. },
  4171. self.repo.get_refs(),
  4172. )
  4173. self.assertEqual(b"", outstream.getvalue())
  4174. self.assertTrue(re.match(b"Push to .* successful.\n", errstream.getvalue()))
  4175. def test_push_returns_sendpackresult(self) -> None:
  4176. """Test that push returns a SendPackResult with per-ref information."""
  4177. outstream = BytesIO()
  4178. errstream = BytesIO()
  4179. # Create initial commit
  4180. porcelain.commit(
  4181. repo=self.repo.path,
  4182. message=b"init",
  4183. author=b"author <email>",
  4184. committer=b"committer <email>",
  4185. )
  4186. # Setup target repo cloned from temp test repo
  4187. clone_path = tempfile.mkdtemp()
  4188. self.addCleanup(shutil.rmtree, clone_path)
  4189. target_repo = porcelain.clone(
  4190. self.repo.path, target=clone_path, errstream=errstream
  4191. )
  4192. target_repo.close()
  4193. # Create a commit in the clone
  4194. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4195. os.close(handle)
  4196. porcelain.add(repo=clone_path, paths=[fullpath])
  4197. porcelain.commit(
  4198. repo=clone_path,
  4199. message=b"push",
  4200. author=b"author <email>",
  4201. committer=b"committer <email>",
  4202. )
  4203. # Push and check the return value
  4204. result = porcelain.push(
  4205. clone_path,
  4206. "origin",
  4207. b"HEAD:refs/heads/new-branch",
  4208. outstream=outstream,
  4209. errstream=errstream,
  4210. )
  4211. # Verify that we get a SendPackResult
  4212. self.assertIsInstance(result, SendPackResult)
  4213. # Verify that it contains refs
  4214. self.assertIsNotNone(result.refs)
  4215. self.assertIn(b"refs/heads/new-branch", result.refs)
  4216. # Verify ref_status - should be None for successful updates
  4217. if result.ref_status:
  4218. self.assertIsNone(result.ref_status.get(b"refs/heads/new-branch"))
  4219. def test_mirror_mode(self) -> None:
  4220. """Test push with remote.<name>.mirror configuration."""
  4221. outstream = BytesIO()
  4222. errstream = BytesIO()
  4223. # Create initial commit
  4224. porcelain.commit(
  4225. repo=self.repo.path,
  4226. message=b"init",
  4227. author=b"author <email>",
  4228. committer=b"committer <email>",
  4229. )
  4230. # Setup target repo cloned from temp test repo
  4231. clone_path = tempfile.mkdtemp()
  4232. self.addCleanup(shutil.rmtree, clone_path)
  4233. target_repo = porcelain.clone(
  4234. self.repo.path, target=clone_path, errstream=errstream
  4235. )
  4236. target_repo.close()
  4237. # Create multiple refs in the clone
  4238. with Repo(clone_path) as r_clone:
  4239. # Create a new branch
  4240. r_clone.refs[b"refs/heads/feature"] = r_clone[b"HEAD"].id
  4241. # Create a tag
  4242. r_clone.refs[b"refs/tags/v1.0"] = r_clone[b"HEAD"].id
  4243. # Create a remote tracking branch
  4244. r_clone.refs[b"refs/remotes/upstream/main"] = r_clone[b"HEAD"].id
  4245. # Create a branch in the remote that doesn't exist in clone
  4246. self.repo.refs[b"refs/heads/to-be-deleted"] = self.repo[b"HEAD"].id
  4247. # Configure mirror mode
  4248. with Repo(clone_path) as r_clone:
  4249. config = r_clone.get_config()
  4250. config.set((b"remote", b"origin"), b"mirror", True)
  4251. config.write_to_path()
  4252. # Push with mirror mode
  4253. porcelain.push(
  4254. clone_path,
  4255. "origin",
  4256. outstream=outstream,
  4257. errstream=errstream,
  4258. )
  4259. # Verify refs were properly mirrored
  4260. with Repo(clone_path) as r_clone:
  4261. # All local branches should be pushed
  4262. self.assertEqual(
  4263. r_clone.refs[b"refs/heads/feature"],
  4264. self.repo.refs[b"refs/heads/feature"],
  4265. )
  4266. # All tags should be pushed
  4267. self.assertEqual(
  4268. r_clone.refs[b"refs/tags/v1.0"], self.repo.refs[b"refs/tags/v1.0"]
  4269. )
  4270. # Remote tracking branches should be pushed
  4271. self.assertEqual(
  4272. r_clone.refs[b"refs/remotes/upstream/main"],
  4273. self.repo.refs[b"refs/remotes/upstream/main"],
  4274. )
  4275. # Verify the extra branch was deleted
  4276. self.assertNotIn(b"refs/heads/to-be-deleted", self.repo.refs)
  4277. def test_mirror_mode_disabled(self) -> None:
  4278. """Test that mirror mode is properly disabled when set to false."""
  4279. outstream = BytesIO()
  4280. errstream = BytesIO()
  4281. # Create initial commit
  4282. porcelain.commit(
  4283. repo=self.repo.path,
  4284. message=b"init",
  4285. author=b"author <email>",
  4286. committer=b"committer <email>",
  4287. )
  4288. # Setup target repo cloned from temp test repo
  4289. clone_path = tempfile.mkdtemp()
  4290. self.addCleanup(shutil.rmtree, clone_path)
  4291. target_repo = porcelain.clone(
  4292. self.repo.path, target=clone_path, errstream=errstream
  4293. )
  4294. target_repo.close()
  4295. # Create a branch in the remote that doesn't exist in clone
  4296. self.repo.refs[b"refs/heads/should-not-be-deleted"] = self.repo[b"HEAD"].id
  4297. # Explicitly set mirror mode to false
  4298. with Repo(clone_path) as r_clone:
  4299. config = r_clone.get_config()
  4300. config.set((b"remote", b"origin"), b"mirror", False)
  4301. config.write_to_path()
  4302. # Push normally (not mirror mode)
  4303. porcelain.push(
  4304. clone_path,
  4305. "origin",
  4306. outstream=outstream,
  4307. errstream=errstream,
  4308. )
  4309. # Verify the extra branch was NOT deleted
  4310. self.assertIn(b"refs/heads/should-not-be-deleted", self.repo.refs)
  4311. class PullTests(PorcelainTestCase):
  4312. def setUp(self) -> None:
  4313. super().setUp()
  4314. # create a file for initial commit
  4315. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4316. os.close(handle)
  4317. porcelain.add(repo=self.repo.path, paths=fullpath)
  4318. porcelain.commit(
  4319. repo=self.repo.path,
  4320. message=b"test",
  4321. author=b"test <email>",
  4322. committer=b"test <email>",
  4323. )
  4324. # Setup target repo
  4325. self.target_path = tempfile.mkdtemp()
  4326. self.addCleanup(shutil.rmtree, self.target_path)
  4327. target_repo = porcelain.clone(
  4328. self.repo.path, target=self.target_path, errstream=BytesIO()
  4329. )
  4330. target_repo.close()
  4331. # create a second file to be pushed
  4332. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4333. os.close(handle)
  4334. porcelain.add(repo=self.repo.path, paths=fullpath)
  4335. porcelain.commit(
  4336. repo=self.repo.path,
  4337. message=b"test2",
  4338. author=b"test2 <email>",
  4339. committer=b"test2 <email>",
  4340. )
  4341. self.assertIn(b"refs/heads/master", self.repo.refs)
  4342. self.assertIn(b"refs/heads/master", target_repo.refs)
  4343. def test_simple(self) -> None:
  4344. outstream = BytesIO()
  4345. errstream = BytesIO()
  4346. # Pull changes into the cloned repo
  4347. porcelain.pull(
  4348. self.target_path,
  4349. self.repo.path,
  4350. b"refs/heads/master",
  4351. outstream=outstream,
  4352. errstream=errstream,
  4353. )
  4354. # Check the target repo for pushed changes
  4355. with Repo(self.target_path) as r:
  4356. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4357. def test_diverged(self) -> None:
  4358. outstream = BytesIO()
  4359. errstream = BytesIO()
  4360. c3a = porcelain.commit(
  4361. repo=self.target_path,
  4362. message=b"test3a",
  4363. author=b"test2 <email>",
  4364. committer=b"test2 <email>",
  4365. )
  4366. porcelain.commit(
  4367. repo=self.repo.path,
  4368. message=b"test3b",
  4369. author=b"test2 <email>",
  4370. committer=b"test2 <email>",
  4371. )
  4372. # Pull changes into the cloned repo
  4373. self.assertRaises(
  4374. porcelain.DivergedBranches,
  4375. porcelain.pull,
  4376. self.target_path,
  4377. self.repo.path,
  4378. b"refs/heads/master",
  4379. outstream=outstream,
  4380. errstream=errstream,
  4381. )
  4382. # Check the target repo for pushed changes
  4383. with Repo(self.target_path) as r:
  4384. self.assertEqual(r[b"refs/heads/master"].id, c3a)
  4385. # Pull with merge should now work
  4386. porcelain.pull(
  4387. self.target_path,
  4388. self.repo.path,
  4389. b"refs/heads/master",
  4390. outstream=outstream,
  4391. errstream=errstream,
  4392. fast_forward=False,
  4393. )
  4394. # Check the target repo for merged changes
  4395. with Repo(self.target_path) as r:
  4396. # HEAD should now be a merge commit
  4397. head = r[b"HEAD"]
  4398. # It should have two parents
  4399. self.assertEqual(len(head.parents), 2)
  4400. # One parent should be the previous HEAD (c3a)
  4401. self.assertIn(c3a, head.parents)
  4402. # The other parent should be from the source repo
  4403. self.assertIn(self.repo[b"HEAD"].id, head.parents)
  4404. def test_no_refspec(self) -> None:
  4405. outstream = BytesIO()
  4406. errstream = BytesIO()
  4407. # Pull changes into the cloned repo
  4408. porcelain.pull(
  4409. self.target_path,
  4410. self.repo.path,
  4411. outstream=outstream,
  4412. errstream=errstream,
  4413. )
  4414. # Check the target repo for pushed changes
  4415. with Repo(self.target_path) as r:
  4416. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4417. def test_no_remote_location(self) -> None:
  4418. outstream = BytesIO()
  4419. errstream = BytesIO()
  4420. # Pull changes into the cloned repo
  4421. porcelain.pull(
  4422. self.target_path,
  4423. refspecs=b"refs/heads/master",
  4424. outstream=outstream,
  4425. errstream=errstream,
  4426. )
  4427. # Check the target repo for pushed changes
  4428. with Repo(self.target_path) as r:
  4429. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4430. def test_pull_updates_working_tree(self) -> None:
  4431. """Test that pull updates the working tree with new files."""
  4432. outstream = BytesIO()
  4433. errstream = BytesIO()
  4434. # Create a new file with content in the source repo
  4435. new_file = os.path.join(self.repo.path, "newfile.txt")
  4436. with open(new_file, "w") as f:
  4437. f.write("This is new content")
  4438. porcelain.add(repo=self.repo.path, paths=[new_file])
  4439. porcelain.commit(
  4440. repo=self.repo.path,
  4441. message=b"Add new file",
  4442. author=b"test <email>",
  4443. committer=b"test <email>",
  4444. )
  4445. # Before pull, the file should not exist in target
  4446. target_file = os.path.join(self.target_path, "newfile.txt")
  4447. self.assertFalse(os.path.exists(target_file))
  4448. # Pull changes into the cloned repo
  4449. porcelain.pull(
  4450. self.target_path,
  4451. self.repo.path,
  4452. b"refs/heads/master",
  4453. outstream=outstream,
  4454. errstream=errstream,
  4455. )
  4456. # After pull, the file should exist with correct content
  4457. self.assertTrue(os.path.exists(target_file))
  4458. with open(target_file) as f:
  4459. self.assertEqual(f.read(), "This is new content")
  4460. # Check the HEAD is updated too
  4461. with Repo(self.target_path) as r:
  4462. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4463. def test_pull_protects_modified_files(self) -> None:
  4464. """Test that pull refuses to overwrite uncommitted changes by default."""
  4465. from dulwich.errors import WorkingTreeModifiedError
  4466. outstream = BytesIO()
  4467. errstream = BytesIO()
  4468. # Create a file with content in the source repo
  4469. test_file = os.path.join(self.repo.path, "testfile.txt")
  4470. with open(test_file, "w") as f:
  4471. f.write("original content")
  4472. porcelain.add(repo=self.repo.path, paths=[test_file])
  4473. porcelain.commit(
  4474. repo=self.repo.path,
  4475. message=b"Add test file",
  4476. author=b"test <email>",
  4477. committer=b"test <email>",
  4478. )
  4479. # Pull this change to target first
  4480. porcelain.pull(
  4481. self.target_path,
  4482. self.repo.path,
  4483. b"refs/heads/master",
  4484. outstream=outstream,
  4485. errstream=errstream,
  4486. )
  4487. # Now modify the file in source repo
  4488. with open(test_file, "w") as f:
  4489. f.write("updated content")
  4490. porcelain.add(repo=self.repo.path, paths=[test_file])
  4491. porcelain.commit(
  4492. repo=self.repo.path,
  4493. message=b"Update test file",
  4494. author=b"test <email>",
  4495. committer=b"test <email>",
  4496. )
  4497. # Modify the same file in target working directory (uncommitted)
  4498. target_file = os.path.join(self.target_path, "testfile.txt")
  4499. with open(target_file, "w") as f:
  4500. f.write("local modifications")
  4501. # Pull should fail because of uncommitted changes
  4502. with self.assertRaises(WorkingTreeModifiedError) as cm:
  4503. porcelain.pull(
  4504. self.target_path,
  4505. self.repo.path,
  4506. b"refs/heads/master",
  4507. outstream=outstream,
  4508. errstream=errstream,
  4509. )
  4510. self.assertIn("Your local changes", str(cm.exception))
  4511. self.assertIn("testfile.txt", str(cm.exception))
  4512. # Verify the file still has local modifications
  4513. with open(target_file) as f:
  4514. self.assertEqual(f.read(), "local modifications")
  4515. def test_pull_force_overwrites_modified_files(self) -> None:
  4516. """Test that pull with force=True overwrites uncommitted changes."""
  4517. outstream = BytesIO()
  4518. errstream = BytesIO()
  4519. # Create a file with content in the source repo
  4520. test_file = os.path.join(self.repo.path, "testfile.txt")
  4521. with open(test_file, "w") as f:
  4522. f.write("original content")
  4523. porcelain.add(repo=self.repo.path, paths=[test_file])
  4524. porcelain.commit(
  4525. repo=self.repo.path,
  4526. message=b"Add test file",
  4527. author=b"test <email>",
  4528. committer=b"test <email>",
  4529. )
  4530. # Pull this change to target first
  4531. porcelain.pull(
  4532. self.target_path,
  4533. self.repo.path,
  4534. b"refs/heads/master",
  4535. outstream=outstream,
  4536. errstream=errstream,
  4537. )
  4538. # Now modify the file in source repo
  4539. with open(test_file, "w") as f:
  4540. f.write("updated content")
  4541. porcelain.add(repo=self.repo.path, paths=[test_file])
  4542. porcelain.commit(
  4543. repo=self.repo.path,
  4544. message=b"Update test file",
  4545. author=b"test <email>",
  4546. committer=b"test <email>",
  4547. )
  4548. # Modify the same file in target working directory (uncommitted)
  4549. target_file = os.path.join(self.target_path, "testfile.txt")
  4550. with open(target_file, "w") as f:
  4551. f.write("local modifications")
  4552. # Pull with force=True should succeed and overwrite local changes
  4553. porcelain.pull(
  4554. self.target_path,
  4555. self.repo.path,
  4556. b"refs/heads/master",
  4557. outstream=outstream,
  4558. errstream=errstream,
  4559. force=True,
  4560. )
  4561. # Verify the file now has the remote content
  4562. with open(target_file) as f:
  4563. self.assertEqual(f.read(), "updated content")
  4564. # Check the HEAD is updated too
  4565. with Repo(self.target_path) as r:
  4566. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4567. def test_pull_allows_unmodified_files(self) -> None:
  4568. """Test that pull allows updating files that haven't been modified locally."""
  4569. outstream = BytesIO()
  4570. errstream = BytesIO()
  4571. # Create a file with content in the source repo
  4572. test_file = os.path.join(self.repo.path, "testfile.txt")
  4573. with open(test_file, "w") as f:
  4574. f.write("original content")
  4575. porcelain.add(repo=self.repo.path, paths=[test_file])
  4576. porcelain.commit(
  4577. repo=self.repo.path,
  4578. message=b"Add test file",
  4579. author=b"test <email>",
  4580. committer=b"test <email>",
  4581. )
  4582. # Pull this change to target first
  4583. porcelain.pull(
  4584. self.target_path,
  4585. self.repo.path,
  4586. b"refs/heads/master",
  4587. outstream=outstream,
  4588. errstream=errstream,
  4589. )
  4590. # Now modify the file in source repo
  4591. with open(test_file, "w") as f:
  4592. f.write("updated content")
  4593. porcelain.add(repo=self.repo.path, paths=[test_file])
  4594. porcelain.commit(
  4595. repo=self.repo.path,
  4596. message=b"Update test file",
  4597. author=b"test <email>",
  4598. committer=b"test <email>",
  4599. )
  4600. # Don't modify the file in target - it should be safe to update
  4601. target_file = os.path.join(self.target_path, "testfile.txt")
  4602. # Pull should succeed since the file wasn't modified locally
  4603. porcelain.pull(
  4604. self.target_path,
  4605. self.repo.path,
  4606. b"refs/heads/master",
  4607. outstream=outstream,
  4608. errstream=errstream,
  4609. )
  4610. # Verify the file now has the remote content
  4611. with open(target_file) as f:
  4612. self.assertEqual(f.read(), "updated content")
  4613. # Check the HEAD is updated too
  4614. with Repo(self.target_path) as r:
  4615. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4616. class StatusTests(PorcelainTestCase):
  4617. def test_empty(self) -> None:
  4618. results = porcelain.status(self.repo)
  4619. self.assertEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4620. self.assertEqual([], results.unstaged)
  4621. def test_status_base(self) -> None:
  4622. """Integration test for `status` functionality."""
  4623. # Commit a dummy file then modify it
  4624. fullpath = os.path.join(self.repo.path, "foo")
  4625. with open(fullpath, "w") as f:
  4626. f.write("origstuff")
  4627. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4628. porcelain.commit(
  4629. repo=self.repo.path,
  4630. message=b"test status",
  4631. author=b"author <email>",
  4632. committer=b"committer <email>",
  4633. )
  4634. # modify access and modify time of path
  4635. os.utime(fullpath, (0, 0))
  4636. with open(fullpath, "wb") as f:
  4637. f.write(b"stuff")
  4638. # Make a dummy file and stage it
  4639. filename_add = "bar"
  4640. fullpath = os.path.join(self.repo.path, filename_add)
  4641. with open(fullpath, "w") as f:
  4642. f.write("stuff")
  4643. porcelain.add(repo=self.repo.path, paths=fullpath)
  4644. results = porcelain.status(self.repo)
  4645. self.assertEqual(results.staged["add"][0], filename_add.encode("ascii"))
  4646. self.assertEqual(results.unstaged, [b"foo"])
  4647. def test_status_all(self) -> None:
  4648. del_path = os.path.join(self.repo.path, "foo")
  4649. mod_path = os.path.join(self.repo.path, "bar")
  4650. add_path = os.path.join(self.repo.path, "baz")
  4651. us_path = os.path.join(self.repo.path, "blye")
  4652. ut_path = os.path.join(self.repo.path, "blyat")
  4653. with open(del_path, "w") as f:
  4654. f.write("origstuff")
  4655. with open(mod_path, "w") as f:
  4656. f.write("origstuff")
  4657. with open(us_path, "w") as f:
  4658. f.write("origstuff")
  4659. porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path])
  4660. porcelain.commit(
  4661. repo=self.repo.path,
  4662. message=b"test status",
  4663. author=b"author <email>",
  4664. committer=b"committer <email>",
  4665. )
  4666. porcelain.remove(self.repo.path, [del_path])
  4667. with open(add_path, "w") as f:
  4668. f.write("origstuff")
  4669. with open(mod_path, "w") as f:
  4670. f.write("more_origstuff")
  4671. with open(us_path, "w") as f:
  4672. f.write("more_origstuff")
  4673. porcelain.add(repo=self.repo.path, paths=[add_path, mod_path])
  4674. with open(us_path, "w") as f:
  4675. f.write("\norigstuff")
  4676. with open(ut_path, "w") as f:
  4677. f.write("origstuff")
  4678. results = porcelain.status(self.repo.path)
  4679. self.assertDictEqual(
  4680. {"add": [b"baz"], "delete": [b"foo"], "modify": [b"bar"]},
  4681. results.staged,
  4682. )
  4683. self.assertListEqual(results.unstaged, [b"blye"])
  4684. results_no_untracked = porcelain.status(self.repo.path, untracked_files="no")
  4685. self.assertListEqual(results_no_untracked.untracked, [])
  4686. def test_status_wrong_untracked_files_value(self) -> None:
  4687. with self.assertRaises(ValueError):
  4688. porcelain.status(self.repo.path, untracked_files="antani")
  4689. def test_status_untracked_path(self) -> None:
  4690. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  4691. os.mkdir(untracked_dir)
  4692. untracked_file = os.path.join(untracked_dir, "untracked_file")
  4693. with open(untracked_file, "w") as fh:
  4694. fh.write("untracked")
  4695. _, _, untracked = porcelain.status(self.repo.path, untracked_files="all")
  4696. self.assertEqual(untracked, ["untracked_dir/untracked_file"])
  4697. def test_status_untracked_path_normal(self) -> None:
  4698. # Create an untracked directory with multiple files
  4699. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  4700. os.mkdir(untracked_dir)
  4701. untracked_file1 = os.path.join(untracked_dir, "file1")
  4702. untracked_file2 = os.path.join(untracked_dir, "file2")
  4703. with open(untracked_file1, "w") as fh:
  4704. fh.write("untracked1")
  4705. with open(untracked_file2, "w") as fh:
  4706. fh.write("untracked2")
  4707. # Create a nested untracked directory
  4708. nested_dir = os.path.join(untracked_dir, "nested")
  4709. os.mkdir(nested_dir)
  4710. nested_file = os.path.join(nested_dir, "file3")
  4711. with open(nested_file, "w") as fh:
  4712. fh.write("untracked3")
  4713. # Test "normal" mode - should only show the directory, not individual files
  4714. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  4715. self.assertEqual(untracked, ["untracked_dir/"])
  4716. # Test "all" mode - should show all files
  4717. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  4718. self.assertEqual(
  4719. sorted(untracked_all),
  4720. [
  4721. "untracked_dir/file1",
  4722. "untracked_dir/file2",
  4723. "untracked_dir/nested/file3",
  4724. ],
  4725. )
  4726. def test_status_mixed_tracked_untracked(self) -> None:
  4727. # Create a directory with both tracked and untracked files
  4728. mixed_dir = os.path.join(self.repo_path, "mixed_dir")
  4729. os.mkdir(mixed_dir)
  4730. # Add a tracked file
  4731. tracked_file = os.path.join(mixed_dir, "tracked.txt")
  4732. with open(tracked_file, "w") as fh:
  4733. fh.write("tracked content")
  4734. porcelain.add(self.repo.path, paths=[tracked_file])
  4735. porcelain.commit(
  4736. repo=self.repo.path,
  4737. message=b"add tracked file",
  4738. author=b"author <email>",
  4739. committer=b"committer <email>",
  4740. )
  4741. # Add untracked files to the same directory
  4742. untracked_file = os.path.join(mixed_dir, "untracked.txt")
  4743. with open(untracked_file, "w") as fh:
  4744. fh.write("untracked content")
  4745. # In "normal" mode, should show individual untracked files in mixed dirs
  4746. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  4747. self.assertEqual(untracked, ["mixed_dir/untracked.txt"])
  4748. # In "all" mode, should be the same for mixed directories
  4749. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  4750. self.assertEqual(untracked_all, ["mixed_dir/untracked.txt"])
  4751. def test_status_crlf_mismatch(self) -> None:
  4752. # First make a commit as if the file has been added on a Linux system
  4753. # or with core.autocrlf=True
  4754. file_path = os.path.join(self.repo.path, "crlf")
  4755. with open(file_path, "wb") as f:
  4756. f.write(b"line1\nline2")
  4757. porcelain.add(repo=self.repo.path, paths=[file_path])
  4758. porcelain.commit(
  4759. repo=self.repo.path,
  4760. message=b"test status",
  4761. author=b"author <email>",
  4762. committer=b"committer <email>",
  4763. )
  4764. # Then update the file as if it was created by CGit on a Windows
  4765. # system with core.autocrlf=true
  4766. with open(file_path, "wb") as f:
  4767. f.write(b"line1\r\nline2")
  4768. results = porcelain.status(self.repo)
  4769. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4770. self.assertListEqual(results.unstaged, [b"crlf"])
  4771. self.assertListEqual(results.untracked, [])
  4772. def test_status_autocrlf_true(self) -> None:
  4773. # First make a commit as if the file has been added on a Linux system
  4774. # or with core.autocrlf=True
  4775. file_path = os.path.join(self.repo.path, "crlf")
  4776. with open(file_path, "wb") as f:
  4777. f.write(b"line1\nline2")
  4778. porcelain.add(repo=self.repo.path, paths=[file_path])
  4779. porcelain.commit(
  4780. repo=self.repo.path,
  4781. message=b"test status",
  4782. author=b"author <email>",
  4783. committer=b"committer <email>",
  4784. )
  4785. # Then update the file as if it was created by CGit on a Windows
  4786. # system with core.autocrlf=true
  4787. with open(file_path, "wb") as f:
  4788. f.write(b"line1\r\nline2")
  4789. # TODO: It should be set automatically by looking at the configuration
  4790. c = self.repo.get_config()
  4791. c.set("core", "autocrlf", True)
  4792. c.write_to_path()
  4793. results = porcelain.status(self.repo)
  4794. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4795. self.assertListEqual(results.unstaged, [])
  4796. self.assertListEqual(results.untracked, [])
  4797. def test_status_autocrlf_input(self) -> None:
  4798. # Commit existing file with CRLF
  4799. file_path = os.path.join(self.repo.path, "crlf-exists")
  4800. with open(file_path, "wb") as f:
  4801. f.write(b"line1\r\nline2")
  4802. porcelain.add(repo=self.repo.path, paths=[file_path])
  4803. porcelain.commit(
  4804. repo=self.repo.path,
  4805. message=b"test status",
  4806. author=b"author <email>",
  4807. committer=b"committer <email>",
  4808. )
  4809. c = self.repo.get_config()
  4810. c.set("core", "autocrlf", "input")
  4811. c.write_to_path()
  4812. # Add new (untracked) file
  4813. file_path = os.path.join(self.repo.path, "crlf-new")
  4814. with open(file_path, "wb") as f:
  4815. f.write(b"line1\r\nline2")
  4816. porcelain.add(repo=self.repo.path, paths=[file_path])
  4817. results = porcelain.status(self.repo)
  4818. self.assertDictEqual(
  4819. {"add": [b"crlf-new"], "delete": [], "modify": []}, results.staged
  4820. )
  4821. self.assertListEqual(results.unstaged, [b"crlf-exists"])
  4822. self.assertListEqual(results.untracked, [])
  4823. def test_get_tree_changes_add(self) -> None:
  4824. """Unit test for get_tree_changes add."""
  4825. # Make a dummy file, stage
  4826. filename = "bar"
  4827. fullpath = os.path.join(self.repo.path, filename)
  4828. with open(fullpath, "w") as f:
  4829. f.write("stuff")
  4830. porcelain.add(repo=self.repo.path, paths=fullpath)
  4831. porcelain.commit(
  4832. repo=self.repo.path,
  4833. message=b"test status",
  4834. author=b"author <email>",
  4835. committer=b"committer <email>",
  4836. )
  4837. filename = "foo"
  4838. fullpath = os.path.join(self.repo.path, filename)
  4839. with open(fullpath, "w") as f:
  4840. f.write("stuff")
  4841. porcelain.add(repo=self.repo.path, paths=fullpath)
  4842. changes = porcelain.get_tree_changes(self.repo.path)
  4843. self.assertEqual(changes["add"][0], filename.encode("ascii"))
  4844. self.assertEqual(len(changes["add"]), 1)
  4845. self.assertEqual(len(changes["modify"]), 0)
  4846. self.assertEqual(len(changes["delete"]), 0)
  4847. def test_get_tree_changes_modify(self) -> None:
  4848. """Unit test for get_tree_changes modify."""
  4849. # Make a dummy file, stage, commit, modify
  4850. filename = "foo"
  4851. fullpath = os.path.join(self.repo.path, filename)
  4852. with open(fullpath, "w") as f:
  4853. f.write("stuff")
  4854. porcelain.add(repo=self.repo.path, paths=fullpath)
  4855. porcelain.commit(
  4856. repo=self.repo.path,
  4857. message=b"test status",
  4858. author=b"author <email>",
  4859. committer=b"committer <email>",
  4860. )
  4861. with open(fullpath, "w") as f:
  4862. f.write("otherstuff")
  4863. porcelain.add(repo=self.repo.path, paths=fullpath)
  4864. changes = porcelain.get_tree_changes(self.repo.path)
  4865. self.assertEqual(changes["modify"][0], filename.encode("ascii"))
  4866. self.assertEqual(len(changes["add"]), 0)
  4867. self.assertEqual(len(changes["modify"]), 1)
  4868. self.assertEqual(len(changes["delete"]), 0)
  4869. def test_get_tree_changes_delete(self) -> None:
  4870. """Unit test for get_tree_changes delete."""
  4871. # Make a dummy file, stage, commit, remove
  4872. filename = "foo"
  4873. fullpath = os.path.join(self.repo.path, filename)
  4874. with open(fullpath, "w") as f:
  4875. f.write("stuff")
  4876. porcelain.add(repo=self.repo.path, paths=fullpath)
  4877. porcelain.commit(
  4878. repo=self.repo.path,
  4879. message=b"test status",
  4880. author=b"author <email>",
  4881. committer=b"committer <email>",
  4882. )
  4883. cwd = os.getcwd()
  4884. self.addCleanup(os.chdir, cwd)
  4885. os.chdir(self.repo.path)
  4886. porcelain.remove(repo=self.repo.path, paths=[filename])
  4887. changes = porcelain.get_tree_changes(self.repo.path)
  4888. self.assertEqual(changes["delete"][0], filename.encode("ascii"))
  4889. self.assertEqual(len(changes["add"]), 0)
  4890. self.assertEqual(len(changes["modify"]), 0)
  4891. self.assertEqual(len(changes["delete"]), 1)
  4892. def test_get_untracked_paths(self) -> None:
  4893. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  4894. f.write("ignored\n")
  4895. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  4896. f.write("blah\n")
  4897. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  4898. f.write("blah\n")
  4899. os.symlink(
  4900. os.path.join(self.repo.path, os.pardir, "external_target"),
  4901. os.path.join(self.repo.path, "link"),
  4902. )
  4903. self.assertEqual(
  4904. {"ignored", "notignored", ".gitignore", "link"},
  4905. set(
  4906. porcelain.get_untracked_paths(
  4907. self.repo.path, self.repo.path, self.repo.open_index()
  4908. )
  4909. ),
  4910. )
  4911. self.assertEqual(
  4912. {".gitignore", "notignored", "link"},
  4913. set(porcelain.status(self.repo).untracked),
  4914. )
  4915. self.assertEqual(
  4916. {".gitignore", "notignored", "ignored", "link"},
  4917. set(porcelain.status(self.repo, ignored=True).untracked),
  4918. )
  4919. def test_get_untracked_paths_subrepo(self) -> None:
  4920. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  4921. f.write("nested/\n")
  4922. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  4923. f.write("blah\n")
  4924. subrepo = Repo.init(os.path.join(self.repo.path, "nested"), mkdir=True)
  4925. with open(os.path.join(subrepo.path, "ignored"), "w") as f:
  4926. f.write("bleep\n")
  4927. with open(os.path.join(subrepo.path, "with"), "w") as f:
  4928. f.write("bloop\n")
  4929. with open(os.path.join(subrepo.path, "manager"), "w") as f:
  4930. f.write("blop\n")
  4931. self.assertEqual(
  4932. {".gitignore", "notignored", os.path.join("nested", "")},
  4933. set(
  4934. porcelain.get_untracked_paths(
  4935. self.repo.path, self.repo.path, self.repo.open_index()
  4936. )
  4937. ),
  4938. )
  4939. self.assertEqual(
  4940. {".gitignore", "notignored"},
  4941. set(
  4942. porcelain.get_untracked_paths(
  4943. self.repo.path,
  4944. self.repo.path,
  4945. self.repo.open_index(),
  4946. exclude_ignored=True,
  4947. )
  4948. ),
  4949. )
  4950. self.assertEqual(
  4951. {"ignored", "with", "manager"},
  4952. set(
  4953. porcelain.get_untracked_paths(
  4954. subrepo.path, subrepo.path, subrepo.open_index()
  4955. )
  4956. ),
  4957. )
  4958. self.assertEqual(
  4959. set(),
  4960. set(
  4961. porcelain.get_untracked_paths(
  4962. subrepo.path,
  4963. self.repo.path,
  4964. self.repo.open_index(),
  4965. )
  4966. ),
  4967. )
  4968. self.assertEqual(
  4969. {
  4970. os.path.join("nested", "ignored"),
  4971. os.path.join("nested", "with"),
  4972. os.path.join("nested", "manager"),
  4973. },
  4974. set(
  4975. porcelain.get_untracked_paths(
  4976. self.repo.path,
  4977. subrepo.path,
  4978. self.repo.open_index(),
  4979. )
  4980. ),
  4981. )
  4982. def test_get_untracked_paths_nested_gitignore(self) -> None:
  4983. """Test directories with nested .gitignore files that ignore all contents."""
  4984. # Create cache directories with .gitignore files that contain "*"
  4985. cache_dirs = [".ruff_cache", ".pytest_cache", "__pycache__"]
  4986. for cache_dir in cache_dirs:
  4987. cache_path = os.path.join(self.repo.path, cache_dir)
  4988. os.mkdir(cache_path)
  4989. # Create .gitignore with * pattern (ignores everything)
  4990. with open(os.path.join(cache_path, ".gitignore"), "w") as f:
  4991. f.write("*\n")
  4992. # Create some files in the cache directory
  4993. with open(os.path.join(cache_path, "somefile.txt"), "w") as f:
  4994. f.write("cached data\n")
  4995. with open(os.path.join(cache_path, "data.json"), "w") as f:
  4996. f.write("{}\n")
  4997. # Create a normal untracked file
  4998. with open(os.path.join(self.repo.path, "untracked.txt"), "w") as f:
  4999. f.write("untracked content\n")
  5000. # Test with exclude_ignored=True (default for status)
  5001. untracked = set(
  5002. porcelain.get_untracked_paths(
  5003. self.repo.path,
  5004. self.repo.path,
  5005. self.repo.open_index(),
  5006. exclude_ignored=True,
  5007. untracked_files="normal",
  5008. )
  5009. )
  5010. # Cache directories should NOT be in untracked since all their contents are ignored
  5011. self.assertEqual({"untracked.txt"}, untracked)
  5012. # Test with exclude_ignored=False
  5013. untracked_with_ignored = set(
  5014. porcelain.get_untracked_paths(
  5015. self.repo.path,
  5016. self.repo.path,
  5017. self.repo.open_index(),
  5018. exclude_ignored=False,
  5019. untracked_files="normal",
  5020. )
  5021. )
  5022. # Cache directories should be included when not excluding ignored
  5023. expected = {"untracked.txt"}
  5024. for cache_dir in cache_dirs:
  5025. expected.add(cache_dir + os.sep)
  5026. self.assertEqual(expected, untracked_with_ignored)
  5027. # Test status() which uses exclude_ignored=True by default
  5028. status = porcelain.status(self.repo)
  5029. self.assertEqual(["untracked.txt"], status.untracked)
  5030. # Test status() with ignored=True which uses exclude_ignored=False
  5031. status_with_ignored = porcelain.status(self.repo, ignored=True)
  5032. # Should include cache directories
  5033. self.assertIn("untracked.txt", status_with_ignored.untracked)
  5034. for cache_dir in cache_dirs:
  5035. self.assertIn(cache_dir + "/", status_with_ignored.untracked)
  5036. def test_get_untracked_paths_mixed_directory(self) -> None:
  5037. """Test directory with both ignored and non-ignored files."""
  5038. # Create a directory with mixed content
  5039. mixed_dir = os.path.join(self.repo.path, "mixed")
  5040. os.mkdir(mixed_dir)
  5041. # Create .gitignore that ignores .log files
  5042. with open(os.path.join(mixed_dir, ".gitignore"), "w") as f:
  5043. f.write("*.log\n")
  5044. # Create ignored and non-ignored files
  5045. with open(os.path.join(mixed_dir, "debug.log"), "w") as f:
  5046. f.write("debug info\n")
  5047. with open(os.path.join(mixed_dir, "readme.txt"), "w") as f:
  5048. f.write("important\n")
  5049. # Test with exclude_ignored=True and normal mode
  5050. untracked = set(
  5051. porcelain.get_untracked_paths(
  5052. self.repo.path,
  5053. self.repo.path,
  5054. self.repo.open_index(),
  5055. exclude_ignored=True,
  5056. untracked_files="normal",
  5057. )
  5058. )
  5059. # In normal mode, should show the directory (matching git behavior)
  5060. self.assertEqual({os.path.join("mixed", "")}, untracked)
  5061. # Test with untracked_files="all"
  5062. untracked_all = set(
  5063. porcelain.get_untracked_paths(
  5064. self.repo.path,
  5065. self.repo.path,
  5066. self.repo.open_index(),
  5067. exclude_ignored=True,
  5068. untracked_files="all",
  5069. )
  5070. )
  5071. # Should list the non-ignored files
  5072. expected = {
  5073. os.path.join("mixed", ".gitignore"),
  5074. os.path.join("mixed", "readme.txt"),
  5075. }
  5076. self.assertEqual(expected, untracked_all)
  5077. def test_get_untracked_paths_specific_ignore_pattern(self) -> None:
  5078. """Test directory with .gitignore that ignores specific files, not all."""
  5079. # Create a directory
  5080. test_dir = os.path.join(self.repo.path, "testdir")
  5081. os.mkdir(test_dir)
  5082. # Create .gitignore that ignores only files named "test"
  5083. with open(os.path.join(test_dir, ".gitignore"), "w") as f:
  5084. f.write("test\n")
  5085. # Create files
  5086. with open(os.path.join(test_dir, "test"), "w") as f:
  5087. f.write("ignored\n")
  5088. with open(os.path.join(test_dir, "other.txt"), "w") as f:
  5089. f.write("not ignored\n")
  5090. # Test with exclude_ignored=True and normal mode
  5091. untracked = set(
  5092. porcelain.get_untracked_paths(
  5093. self.repo.path,
  5094. self.repo.path,
  5095. self.repo.open_index(),
  5096. exclude_ignored=True,
  5097. untracked_files="normal",
  5098. )
  5099. )
  5100. # Directory should be shown because it has non-ignored files
  5101. self.assertEqual({os.path.join("testdir", "")}, untracked)
  5102. def test_get_untracked_paths_nested_subdirs_all_ignored(self) -> None:
  5103. """Test directory containing only subdirectories where all files are ignored."""
  5104. # Create parent directory with .gitignore that ignores everything
  5105. parent_dir = os.path.join(self.repo.path, "parent")
  5106. os.mkdir(parent_dir)
  5107. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5108. f.write("*\n")
  5109. # Create subdirectories with files (all should be ignored by parent's .gitignore)
  5110. sub1 = os.path.join(parent_dir, "sub1")
  5111. sub2 = os.path.join(parent_dir, "sub2")
  5112. os.mkdir(sub1)
  5113. os.mkdir(sub2)
  5114. # Create files in subdirectories
  5115. with open(os.path.join(sub1, "file1.txt"), "w") as f:
  5116. f.write("content1\n")
  5117. with open(os.path.join(sub2, "file2.txt"), "w") as f:
  5118. f.write("content2\n")
  5119. # Create another normal untracked file
  5120. with open(os.path.join(self.repo.path, "normal.txt"), "w") as f:
  5121. f.write("normal\n")
  5122. # Test with exclude_ignored=True
  5123. untracked = set(
  5124. porcelain.get_untracked_paths(
  5125. self.repo.path,
  5126. self.repo.path,
  5127. self.repo.open_index(),
  5128. exclude_ignored=True,
  5129. untracked_files="normal",
  5130. )
  5131. )
  5132. # Parent directory should NOT be shown since all nested files are ignored
  5133. self.assertEqual({"normal.txt"}, untracked)
  5134. def test_get_untracked_paths_nested_subdirs_mixed(self) -> None:
  5135. """Test directory containing only subdirectories where some files are ignored, some aren't."""
  5136. # Create parent directory with .gitignore that ignores .log files
  5137. parent_dir = os.path.join(self.repo.path, "parent")
  5138. os.mkdir(parent_dir)
  5139. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5140. f.write("*.log\n")
  5141. # Create subdirectories
  5142. sub1 = os.path.join(parent_dir, "sub1")
  5143. sub2 = os.path.join(parent_dir, "sub2")
  5144. os.mkdir(sub1)
  5145. os.mkdir(sub2)
  5146. # sub1: only ignored files
  5147. with open(os.path.join(sub1, "debug.log"), "w") as f:
  5148. f.write("log content\n")
  5149. with open(os.path.join(sub1, "error.log"), "w") as f:
  5150. f.write("error log\n")
  5151. # sub2: mix of ignored and non-ignored files
  5152. with open(os.path.join(sub2, "access.log"), "w") as f:
  5153. f.write("access log\n")
  5154. with open(os.path.join(sub2, "readme.txt"), "w") as f:
  5155. f.write("important info\n")
  5156. # Test with exclude_ignored=True
  5157. untracked = set(
  5158. porcelain.get_untracked_paths(
  5159. self.repo.path,
  5160. self.repo.path,
  5161. self.repo.open_index(),
  5162. exclude_ignored=True,
  5163. untracked_files="normal",
  5164. )
  5165. )
  5166. # Parent directory SHOULD be shown since sub2 has non-ignored files
  5167. self.assertEqual({os.path.join("parent", "")}, untracked)
  5168. def test_get_untracked_paths_deeply_nested_all_ignored(self) -> None:
  5169. """Test deeply nested directories where all files are eventually ignored."""
  5170. # Create nested structure: parent/sub/subsub/
  5171. parent_dir = os.path.join(self.repo.path, "parent")
  5172. sub_dir = os.path.join(parent_dir, "sub")
  5173. subsub_dir = os.path.join(sub_dir, "subsub")
  5174. os.makedirs(subsub_dir)
  5175. # Parent has .gitignore that ignores everything
  5176. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5177. f.write("*\n")
  5178. # Create files at different levels
  5179. with open(os.path.join(subsub_dir, "deep_file.txt"), "w") as f:
  5180. f.write("deep content\n")
  5181. with open(os.path.join(sub_dir, "mid_file.txt"), "w") as f:
  5182. f.write("mid content\n")
  5183. # Test with exclude_ignored=True
  5184. untracked = set(
  5185. porcelain.get_untracked_paths(
  5186. self.repo.path,
  5187. self.repo.path,
  5188. self.repo.open_index(),
  5189. exclude_ignored=True,
  5190. untracked_files="normal",
  5191. )
  5192. )
  5193. # Parent directory should NOT be shown since all nested files are ignored
  5194. self.assertEqual(set(), untracked)
  5195. def test_get_untracked_paths_subdir(self) -> None:
  5196. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5197. f.write("subdir/\nignored")
  5198. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5199. f.write("blah\n")
  5200. os.mkdir(os.path.join(self.repo.path, "subdir"))
  5201. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  5202. f.write("foo")
  5203. with open(os.path.join(self.repo.path, "subdir", "ignored"), "w") as f:
  5204. f.write("foo")
  5205. self.assertEqual(
  5206. {
  5207. ".gitignore",
  5208. "notignored",
  5209. "ignored",
  5210. os.path.join("subdir", ""),
  5211. },
  5212. set(
  5213. porcelain.get_untracked_paths(
  5214. self.repo.path,
  5215. self.repo.path,
  5216. self.repo.open_index(),
  5217. )
  5218. ),
  5219. )
  5220. self.assertEqual(
  5221. {".gitignore", "notignored"},
  5222. set(
  5223. porcelain.get_untracked_paths(
  5224. self.repo.path,
  5225. self.repo.path,
  5226. self.repo.open_index(),
  5227. exclude_ignored=True,
  5228. )
  5229. ),
  5230. )
  5231. def test_get_untracked_paths_invalid_untracked_files(self) -> None:
  5232. with self.assertRaises(ValueError):
  5233. list(
  5234. porcelain.get_untracked_paths(
  5235. self.repo.path,
  5236. self.repo.path,
  5237. self.repo.open_index(),
  5238. untracked_files="invalid_value",
  5239. )
  5240. )
  5241. def test_get_untracked_paths_normal(self) -> None:
  5242. # Create an untracked directory with files
  5243. untracked_dir = os.path.join(self.repo.path, "untracked_dir")
  5244. os.mkdir(untracked_dir)
  5245. with open(os.path.join(untracked_dir, "file1.txt"), "w") as f:
  5246. f.write("untracked content")
  5247. with open(os.path.join(untracked_dir, "file2.txt"), "w") as f:
  5248. f.write("more untracked content")
  5249. # Test that "normal" mode works and returns only the directory
  5250. _, _, untracked = porcelain.status(
  5251. repo=self.repo.path, untracked_files="normal"
  5252. )
  5253. self.assertEqual(untracked, ["untracked_dir/"])
  5254. def test_get_untracked_paths_top_level_issue_1247(self) -> None:
  5255. """Test for issue #1247: ensure top-level untracked files are detected."""
  5256. # Create a single top-level untracked file
  5257. with open(os.path.join(self.repo.path, "sample.txt"), "w") as f:
  5258. f.write("test content")
  5259. # Test get_untracked_paths directly
  5260. untracked = list(
  5261. porcelain.get_untracked_paths(
  5262. self.repo.path, self.repo.path, self.repo.open_index()
  5263. )
  5264. )
  5265. self.assertIn(
  5266. "sample.txt",
  5267. untracked,
  5268. "Top-level file 'sample.txt' should be in untracked list",
  5269. )
  5270. # Test via status
  5271. status = porcelain.status(self.repo)
  5272. self.assertIn(
  5273. "sample.txt",
  5274. status.untracked,
  5275. "Top-level file 'sample.txt' should be in status.untracked",
  5276. )
  5277. # TODO(jelmer): Add test for dulwich.porcelain.daemon
  5278. class UploadPackTests(PorcelainTestCase):
  5279. """Tests for upload_pack."""
  5280. def test_upload_pack(self) -> None:
  5281. outf = BytesIO()
  5282. exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf)
  5283. outlines = outf.getvalue().splitlines()
  5284. self.assertEqual([b"0000"], outlines)
  5285. self.assertEqual(0, exitcode)
  5286. class ReceivePackTests(PorcelainTestCase):
  5287. """Tests for receive_pack."""
  5288. def test_receive_pack(self) -> None:
  5289. filename = "foo"
  5290. fullpath = os.path.join(self.repo.path, filename)
  5291. with open(fullpath, "w") as f:
  5292. f.write("stuff")
  5293. porcelain.add(repo=self.repo.path, paths=fullpath)
  5294. self.repo.get_worktree().commit(
  5295. message=b"test status",
  5296. committer=b"committer <email>",
  5297. author=b"author <email>",
  5298. commit_timestamp=1402354300,
  5299. commit_timezone=0,
  5300. author_timestamp=1402354300,
  5301. author_timezone=0,
  5302. )
  5303. outf = BytesIO()
  5304. exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf)
  5305. outlines = outf.getvalue().splitlines()
  5306. self.assertEqual(
  5307. [
  5308. b"0091319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status "
  5309. b"delete-refs quiet ofs-delta side-band-64k "
  5310. b"no-done symref=HEAD:refs/heads/master",
  5311. b"003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master",
  5312. b"0000",
  5313. ],
  5314. outlines,
  5315. )
  5316. self.assertEqual(0, exitcode)
  5317. class BranchListTests(PorcelainTestCase):
  5318. def test_standard(self) -> None:
  5319. self.assertEqual(set(), set(porcelain.branch_list(self.repo)))
  5320. def test_new_branch(self) -> None:
  5321. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5322. self.repo[b"HEAD"] = c1.id
  5323. porcelain.branch_create(self.repo, b"foo")
  5324. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  5325. def test_sort_by_refname(self) -> None:
  5326. """Test branch.sort=refname (default alphabetical)."""
  5327. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5328. self.repo[b"HEAD"] = c1.id
  5329. # Create branches in non-alphabetical order
  5330. porcelain.branch_create(self.repo, b"zebra")
  5331. porcelain.branch_create(self.repo, b"alpha")
  5332. porcelain.branch_create(self.repo, b"beta")
  5333. # Set branch.sort to refname (though it's the default)
  5334. config = self.repo.get_config()
  5335. config.set((b"branch",), b"sort", b"refname")
  5336. config.write_to_path()
  5337. # Should be sorted alphabetically
  5338. branches = porcelain.branch_list(self.repo)
  5339. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5340. def test_sort_by_refname_reverse(self) -> None:
  5341. """Test branch.sort=-refname (reverse alphabetical)."""
  5342. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5343. self.repo[b"HEAD"] = c1.id
  5344. # Create branches
  5345. porcelain.branch_create(self.repo, b"zebra")
  5346. porcelain.branch_create(self.repo, b"alpha")
  5347. porcelain.branch_create(self.repo, b"beta")
  5348. # Set branch.sort to -refname
  5349. config = self.repo.get_config()
  5350. config.set((b"branch",), b"sort", b"-refname")
  5351. config.write_to_path()
  5352. # Should be sorted reverse alphabetically
  5353. branches = porcelain.branch_list(self.repo)
  5354. self.assertEqual([b"zebra", b"master", b"beta", b"alpha"], branches)
  5355. def test_sort_by_committerdate(self) -> None:
  5356. """Test branch.sort=committerdate."""
  5357. # Use build_commit_graph to create proper commits with specific times
  5358. c1, c2, c3 = build_commit_graph(
  5359. self.repo.object_store,
  5360. [[1], [2], [3]],
  5361. attrs={
  5362. 1: {"commit_time": 1000}, # oldest
  5363. 2: {"commit_time": 2000}, # newest
  5364. 3: {"commit_time": 1500}, # middle
  5365. },
  5366. )
  5367. self.repo[b"HEAD"] = c1.id
  5368. # Create branches pointing to different commits
  5369. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  5370. self.repo.refs[b"refs/heads/oldest"] = c1.id
  5371. self.repo.refs[b"refs/heads/newest"] = c2.id
  5372. self.repo.refs[b"refs/heads/middle"] = c3.id
  5373. # Set branch.sort to committerdate
  5374. config = self.repo.get_config()
  5375. config.set((b"branch",), b"sort", b"committerdate")
  5376. config.write_to_path()
  5377. # Should be sorted by commit time (oldest first)
  5378. branches = porcelain.branch_list(self.repo)
  5379. self.assertEqual([b"master", b"oldest", b"middle", b"newest"], branches)
  5380. def test_sort_by_committerdate_reverse(self) -> None:
  5381. """Test branch.sort=-committerdate."""
  5382. # Use build_commit_graph to create proper commits with specific times
  5383. c1, c2, c3 = build_commit_graph(
  5384. self.repo.object_store,
  5385. [[1], [2], [3]],
  5386. attrs={
  5387. 1: {"commit_time": 1000}, # oldest
  5388. 2: {"commit_time": 2000}, # newest
  5389. 3: {"commit_time": 1500}, # middle
  5390. },
  5391. )
  5392. self.repo[b"HEAD"] = c1.id
  5393. # Create branches pointing to different commits
  5394. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  5395. self.repo.refs[b"refs/heads/oldest"] = c1.id
  5396. self.repo.refs[b"refs/heads/newest"] = c2.id
  5397. self.repo.refs[b"refs/heads/middle"] = c3.id
  5398. # Set branch.sort to -committerdate
  5399. config = self.repo.get_config()
  5400. config.set((b"branch",), b"sort", b"-committerdate")
  5401. config.write_to_path()
  5402. # Should be sorted by commit time (newest first)
  5403. branches = porcelain.branch_list(self.repo)
  5404. self.assertEqual([b"newest", b"middle", b"master", b"oldest"], branches)
  5405. def test_sort_default(self) -> None:
  5406. """Test default sorting (no config)."""
  5407. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5408. self.repo[b"HEAD"] = c1.id
  5409. # Create branches in non-alphabetical order
  5410. porcelain.branch_create(self.repo, b"zebra")
  5411. porcelain.branch_create(self.repo, b"alpha")
  5412. porcelain.branch_create(self.repo, b"beta")
  5413. # No config set - should default to alphabetical
  5414. branches = porcelain.branch_list(self.repo)
  5415. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5416. class BranchCreateTests(PorcelainTestCase):
  5417. def test_branch_exists(self) -> None:
  5418. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5419. self.repo[b"HEAD"] = c1.id
  5420. porcelain.branch_create(self.repo, b"foo")
  5421. self.assertRaises(porcelain.Error, porcelain.branch_create, self.repo, b"foo")
  5422. porcelain.branch_create(self.repo, b"foo", force=True)
  5423. def test_new_branch(self) -> None:
  5424. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5425. self.repo[b"HEAD"] = c1.id
  5426. porcelain.branch_create(self.repo, b"foo")
  5427. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  5428. def test_auto_setup_merge_true_from_remote_tracking(self) -> None:
  5429. """Test branch.autoSetupMerge=true sets up tracking from remote-tracking branch."""
  5430. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5431. self.repo[b"HEAD"] = c1.id
  5432. # Create a remote-tracking branch
  5433. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  5434. # Set branch.autoSetupMerge to true (default)
  5435. config = self.repo.get_config()
  5436. config.set((b"branch",), b"autoSetupMerge", b"true")
  5437. config.write_to_path()
  5438. # Create branch from remote-tracking branch
  5439. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  5440. # Verify tracking was set up
  5441. config = self.repo.get_config()
  5442. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  5443. self.assertEqual(
  5444. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  5445. )
  5446. def test_auto_setup_merge_false(self) -> None:
  5447. """Test branch.autoSetupMerge=false disables tracking setup."""
  5448. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5449. self.repo[b"HEAD"] = c1.id
  5450. # Create a remote-tracking branch
  5451. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  5452. # Set branch.autoSetupMerge to false
  5453. config = self.repo.get_config()
  5454. config.set((b"branch",), b"autoSetupMerge", b"false")
  5455. config.write_to_path()
  5456. # Create branch from remote-tracking branch
  5457. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  5458. # Verify tracking was NOT set up
  5459. config = self.repo.get_config()
  5460. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"remote")
  5461. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"merge")
  5462. def test_auto_setup_merge_always(self) -> None:
  5463. """Test branch.autoSetupMerge=always sets up tracking even from local branches."""
  5464. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5465. self.repo[b"HEAD"] = c1.id
  5466. self.repo.refs[b"refs/heads/main"] = c1.id
  5467. # Set branch.autoSetupMerge to always
  5468. config = self.repo.get_config()
  5469. config.set((b"branch",), b"autoSetupMerge", b"always")
  5470. config.write_to_path()
  5471. # Create branch from local branch - normally wouldn't set up tracking
  5472. porcelain.branch_create(self.repo, "feature", "main")
  5473. # With always, tracking should NOT be set up from local branches
  5474. # (Git only sets up tracking from remote-tracking branches even with always)
  5475. config = self.repo.get_config()
  5476. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"remote")
  5477. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"merge")
  5478. def test_auto_setup_merge_always_from_remote(self) -> None:
  5479. """Test branch.autoSetupMerge=always still sets up tracking from remote branches."""
  5480. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5481. self.repo[b"HEAD"] = c1.id
  5482. # Create a remote-tracking branch
  5483. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  5484. # Set branch.autoSetupMerge to always
  5485. config = self.repo.get_config()
  5486. config.set((b"branch",), b"autoSetupMerge", b"always")
  5487. config.write_to_path()
  5488. # Create branch from remote-tracking branch
  5489. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  5490. # Verify tracking was set up
  5491. config = self.repo.get_config()
  5492. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  5493. self.assertEqual(
  5494. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  5495. )
  5496. def test_auto_setup_merge_default(self) -> None:
  5497. """Test default behavior (no config) is same as true."""
  5498. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5499. self.repo[b"HEAD"] = c1.id
  5500. # Create a remote-tracking branch
  5501. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  5502. # Don't set any config - should default to true
  5503. # Create branch from remote-tracking branch
  5504. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  5505. # Verify tracking was set up
  5506. config = self.repo.get_config()
  5507. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  5508. self.assertEqual(
  5509. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  5510. )
  5511. class BranchDeleteTests(PorcelainTestCase):
  5512. def test_simple(self) -> None:
  5513. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5514. self.repo[b"HEAD"] = c1.id
  5515. porcelain.branch_create(self.repo, b"foo")
  5516. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  5517. porcelain.branch_delete(self.repo, b"foo")
  5518. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  5519. def test_simple_unicode(self) -> None:
  5520. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5521. self.repo[b"HEAD"] = c1.id
  5522. porcelain.branch_create(self.repo, "foo")
  5523. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  5524. porcelain.branch_delete(self.repo, "foo")
  5525. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  5526. class FetchTests(PorcelainTestCase):
  5527. def test_simple(self) -> None:
  5528. outstream = BytesIO()
  5529. errstream = BytesIO()
  5530. # create a file for initial commit
  5531. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5532. os.close(handle)
  5533. porcelain.add(repo=self.repo.path, paths=fullpath)
  5534. porcelain.commit(
  5535. repo=self.repo.path,
  5536. message=b"test",
  5537. author=b"test <email>",
  5538. committer=b"test <email>",
  5539. )
  5540. # Setup target repo
  5541. target_path = tempfile.mkdtemp()
  5542. self.addCleanup(shutil.rmtree, target_path)
  5543. target_repo = porcelain.clone(
  5544. self.repo.path, target=target_path, errstream=errstream
  5545. )
  5546. # create a second file to be pushed
  5547. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5548. os.close(handle)
  5549. porcelain.add(repo=self.repo.path, paths=fullpath)
  5550. porcelain.commit(
  5551. repo=self.repo.path,
  5552. message=b"test2",
  5553. author=b"test2 <email>",
  5554. committer=b"test2 <email>",
  5555. )
  5556. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  5557. target_repo.close()
  5558. # Fetch changes into the cloned repo
  5559. porcelain.fetch(target_path, "origin", outstream=outstream, errstream=errstream)
  5560. # Assert that fetch updated the local image of the remote
  5561. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  5562. # Check the target repo for pushed changes
  5563. with Repo(target_path) as r:
  5564. self.assertIn(self.repo[b"HEAD"].id, r)
  5565. def test_with_remote_name(self) -> None:
  5566. remote_name = "origin"
  5567. outstream = BytesIO()
  5568. errstream = BytesIO()
  5569. # create a file for initial commit
  5570. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5571. os.close(handle)
  5572. porcelain.add(repo=self.repo.path, paths=fullpath)
  5573. porcelain.commit(
  5574. repo=self.repo.path,
  5575. message=b"test",
  5576. author=b"test <email>",
  5577. committer=b"test <email>",
  5578. )
  5579. # Setup target repo
  5580. target_path = tempfile.mkdtemp()
  5581. self.addCleanup(shutil.rmtree, target_path)
  5582. target_repo = porcelain.clone(
  5583. self.repo.path, target=target_path, errstream=errstream
  5584. )
  5585. # Capture current refs
  5586. target_refs = target_repo.get_refs()
  5587. # create a second file to be pushed
  5588. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5589. os.close(handle)
  5590. porcelain.add(repo=self.repo.path, paths=fullpath)
  5591. porcelain.commit(
  5592. repo=self.repo.path,
  5593. message=b"test2",
  5594. author=b"test2 <email>",
  5595. committer=b"test2 <email>",
  5596. )
  5597. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  5598. target_config = target_repo.get_config()
  5599. target_config.set(
  5600. (b"remote", remote_name.encode()), b"url", self.repo.path.encode()
  5601. )
  5602. target_repo.close()
  5603. # Fetch changes into the cloned repo
  5604. porcelain.fetch(
  5605. target_path, remote_name, outstream=outstream, errstream=errstream
  5606. )
  5607. # Assert that fetch updated the local image of the remote
  5608. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  5609. # Check the target repo for pushed changes, as well as updates
  5610. # for the refs
  5611. with Repo(target_path) as r:
  5612. self.assertIn(self.repo[b"HEAD"].id, r)
  5613. self.assertNotEqual(self.repo.get_refs(), target_refs)
  5614. def assert_correct_remote_refs(
  5615. self, local_refs, remote_refs, remote_name=b"origin"
  5616. ) -> None:
  5617. """Assert that known remote refs corresponds to actual remote refs."""
  5618. local_ref_prefix = b"refs/heads"
  5619. remote_ref_prefix = b"refs/remotes/" + remote_name
  5620. locally_known_remote_refs = {
  5621. k[len(remote_ref_prefix) + 1 :]: v
  5622. for k, v in local_refs.items()
  5623. if k.startswith(remote_ref_prefix)
  5624. }
  5625. normalized_remote_refs = {
  5626. k[len(local_ref_prefix) + 1 :]: v
  5627. for k, v in remote_refs.items()
  5628. if k.startswith(local_ref_prefix)
  5629. }
  5630. if b"HEAD" in locally_known_remote_refs and b"HEAD" in remote_refs:
  5631. normalized_remote_refs[b"HEAD"] = remote_refs[b"HEAD"]
  5632. self.assertEqual(locally_known_remote_refs, normalized_remote_refs)
  5633. class RepackTests(PorcelainTestCase):
  5634. def test_empty(self) -> None:
  5635. porcelain.repack(self.repo)
  5636. def test_simple(self) -> None:
  5637. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5638. os.close(handle)
  5639. porcelain.add(repo=self.repo.path, paths=fullpath)
  5640. porcelain.repack(self.repo)
  5641. class LsTreeTests(PorcelainTestCase):
  5642. def test_empty(self) -> None:
  5643. porcelain.commit(
  5644. repo=self.repo.path,
  5645. message=b"test status",
  5646. author=b"author <email>",
  5647. committer=b"committer <email>",
  5648. )
  5649. f = StringIO()
  5650. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  5651. self.assertEqual(f.getvalue(), "")
  5652. def test_simple(self) -> None:
  5653. # Commit a dummy file then modify it
  5654. fullpath = os.path.join(self.repo.path, "foo")
  5655. with open(fullpath, "w") as f:
  5656. f.write("origstuff")
  5657. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5658. porcelain.commit(
  5659. repo=self.repo.path,
  5660. message=b"test status",
  5661. author=b"author <email>",
  5662. committer=b"committer <email>",
  5663. )
  5664. output = StringIO()
  5665. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  5666. self.assertEqual(
  5667. output.getvalue(),
  5668. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n",
  5669. )
  5670. def test_recursive(self) -> None:
  5671. # Create a directory then write a dummy file in it
  5672. dirpath = os.path.join(self.repo.path, "adir")
  5673. filepath = os.path.join(dirpath, "afile")
  5674. os.mkdir(dirpath)
  5675. with open(filepath, "w") as f:
  5676. f.write("origstuff")
  5677. porcelain.add(repo=self.repo.path, paths=[filepath])
  5678. porcelain.commit(
  5679. repo=self.repo.path,
  5680. message=b"test status",
  5681. author=b"author <email>",
  5682. committer=b"committer <email>",
  5683. )
  5684. output = StringIO()
  5685. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  5686. self.assertEqual(
  5687. output.getvalue(),
  5688. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n",
  5689. )
  5690. output2 = StringIO()
  5691. porcelain.ls_tree(self.repo, b"HEAD", outstream=output2, recursive=True)
  5692. self.assertEqual(
  5693. output2.getvalue(),
  5694. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n"
  5695. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir"
  5696. "/afile\n",
  5697. )
  5698. class LsRemoteTests(PorcelainTestCase):
  5699. def test_empty(self) -> None:
  5700. result = porcelain.ls_remote(self.repo.path)
  5701. self.assertEqual({}, result.refs)
  5702. self.assertEqual({}, result.symrefs)
  5703. def test_some(self) -> None:
  5704. cid = porcelain.commit(
  5705. repo=self.repo.path,
  5706. message=b"test status",
  5707. author=b"author <email>",
  5708. committer=b"committer <email>",
  5709. )
  5710. result = porcelain.ls_remote(self.repo.path)
  5711. self.assertEqual(
  5712. {b"refs/heads/master": cid, b"HEAD": cid},
  5713. result.refs,
  5714. )
  5715. # HEAD should be a symref to refs/heads/master
  5716. self.assertEqual({b"HEAD": b"refs/heads/master"}, result.symrefs)
  5717. class LsFilesTests(PorcelainTestCase):
  5718. def test_empty(self) -> None:
  5719. self.assertEqual([], list(porcelain.ls_files(self.repo)))
  5720. def test_simple(self) -> None:
  5721. # Commit a dummy file then modify it
  5722. fullpath = os.path.join(self.repo.path, "foo")
  5723. with open(fullpath, "w") as f:
  5724. f.write("origstuff")
  5725. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5726. self.assertEqual([b"foo"], list(porcelain.ls_files(self.repo)))
  5727. class RemoteAddTests(PorcelainTestCase):
  5728. def test_new(self) -> None:
  5729. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  5730. c = self.repo.get_config()
  5731. self.assertEqual(
  5732. c.get((b"remote", b"jelmer"), b"url"),
  5733. b"git://jelmer.uk/code/dulwich",
  5734. )
  5735. def test_exists(self) -> None:
  5736. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  5737. self.assertRaises(
  5738. porcelain.RemoteExists,
  5739. porcelain.remote_add,
  5740. self.repo,
  5741. "jelmer",
  5742. "git://jelmer.uk/code/dulwich",
  5743. )
  5744. class RemoteRemoveTests(PorcelainTestCase):
  5745. def test_remove(self) -> None:
  5746. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  5747. c = self.repo.get_config()
  5748. self.assertEqual(
  5749. c.get((b"remote", b"jelmer"), b"url"),
  5750. b"git://jelmer.uk/code/dulwich",
  5751. )
  5752. porcelain.remote_remove(self.repo, "jelmer")
  5753. self.assertRaises(KeyError, porcelain.remote_remove, self.repo, "jelmer")
  5754. c = self.repo.get_config()
  5755. self.assertRaises(KeyError, c.get, (b"remote", b"jelmer"), b"url")
  5756. class CheckIgnoreTests(PorcelainTestCase):
  5757. def test_check_ignored(self) -> None:
  5758. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5759. f.write("foo")
  5760. foo_path = os.path.join(self.repo.path, "foo")
  5761. with open(foo_path, "w") as f:
  5762. f.write("BAR")
  5763. bar_path = os.path.join(self.repo.path, "bar")
  5764. with open(bar_path, "w") as f:
  5765. f.write("BAR")
  5766. self.assertEqual(["foo"], list(porcelain.check_ignore(self.repo, [foo_path])))
  5767. self.assertEqual([], list(porcelain.check_ignore(self.repo, [bar_path])))
  5768. def test_check_added_abs(self) -> None:
  5769. path = os.path.join(self.repo.path, "foo")
  5770. with open(path, "w") as f:
  5771. f.write("BAR")
  5772. self.repo.get_worktree().stage(["foo"])
  5773. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5774. f.write("foo\n")
  5775. self.assertEqual([], list(porcelain.check_ignore(self.repo, [path])))
  5776. self.assertEqual(
  5777. ["foo"],
  5778. list(porcelain.check_ignore(self.repo, [path], no_index=True)),
  5779. )
  5780. def test_check_added_rel(self) -> None:
  5781. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  5782. f.write("BAR")
  5783. self.repo.get_worktree().stage(["foo"])
  5784. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5785. f.write("foo\n")
  5786. cwd = os.getcwd()
  5787. self.addCleanup(os.chdir, cwd)
  5788. os.mkdir(os.path.join(self.repo.path, "bar"))
  5789. os.chdir(os.path.join(self.repo.path, "bar"))
  5790. self.assertEqual(list(porcelain.check_ignore(self.repo, ["../foo"])), [])
  5791. self.assertEqual(
  5792. ["../foo"],
  5793. list(porcelain.check_ignore(self.repo, ["../foo"], no_index=True)),
  5794. )
  5795. class UpdateHeadTests(PorcelainTestCase):
  5796. def test_set_to_branch(self) -> None:
  5797. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5798. self.repo.refs[b"refs/heads/blah"] = c1.id
  5799. porcelain.update_head(self.repo, "blah")
  5800. self.assertEqual(c1.id, self.repo.head())
  5801. self.assertEqual(b"ref: refs/heads/blah", self.repo.refs.read_ref(b"HEAD"))
  5802. def test_set_to_branch_detached(self) -> None:
  5803. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5804. self.repo.refs[b"refs/heads/blah"] = c1.id
  5805. porcelain.update_head(self.repo, "blah", detached=True)
  5806. self.assertEqual(c1.id, self.repo.head())
  5807. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  5808. def test_set_to_commit_detached(self) -> None:
  5809. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5810. self.repo.refs[b"refs/heads/blah"] = c1.id
  5811. porcelain.update_head(self.repo, c1.id, detached=True)
  5812. self.assertEqual(c1.id, self.repo.head())
  5813. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  5814. def test_set_new_branch(self) -> None:
  5815. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5816. self.repo.refs[b"refs/heads/blah"] = c1.id
  5817. porcelain.update_head(self.repo, "blah", new_branch="bar")
  5818. self.assertEqual(c1.id, self.repo.head())
  5819. self.assertEqual(b"ref: refs/heads/bar", self.repo.refs.read_ref(b"HEAD"))
  5820. class MailmapTests(PorcelainTestCase):
  5821. def test_no_mailmap(self) -> None:
  5822. self.assertEqual(
  5823. b"Jelmer Vernooij <jelmer@samba.org>",
  5824. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  5825. )
  5826. def test_mailmap_lookup(self) -> None:
  5827. with open(os.path.join(self.repo.path, ".mailmap"), "wb") as f:
  5828. f.write(
  5829. b"""\
  5830. Jelmer Vernooij <jelmer@debian.org>
  5831. """
  5832. )
  5833. self.assertEqual(
  5834. b"Jelmer Vernooij <jelmer@debian.org>",
  5835. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  5836. )
  5837. class FsckTests(PorcelainTestCase):
  5838. def test_none(self) -> None:
  5839. self.assertEqual([], list(porcelain.fsck(self.repo)))
  5840. def test_git_dir(self) -> None:
  5841. obj = Tree()
  5842. a = Blob()
  5843. a.data = b"foo"
  5844. obj.add(b".git", 0o100644, a.id)
  5845. self.repo.object_store.add_objects([(a, None), (obj, None)])
  5846. self.assertEqual(
  5847. [(obj.id, "invalid name .git")],
  5848. [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)],
  5849. )
  5850. class DescribeTests(PorcelainTestCase):
  5851. def test_no_commits(self) -> None:
  5852. self.assertRaises(KeyError, porcelain.describe, self.repo.path)
  5853. def test_single_commit(self) -> None:
  5854. fullpath = os.path.join(self.repo.path, "foo")
  5855. with open(fullpath, "w") as f:
  5856. f.write("BAR")
  5857. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5858. sha = porcelain.commit(
  5859. self.repo.path,
  5860. message=b"Some message",
  5861. author=b"Joe <joe@example.com>",
  5862. committer=b"Bob <bob@example.com>",
  5863. )
  5864. self.assertEqual(
  5865. "g{}".format(sha[:7].decode("ascii")),
  5866. porcelain.describe(self.repo.path),
  5867. )
  5868. def test_tag(self) -> None:
  5869. fullpath = os.path.join(self.repo.path, "foo")
  5870. with open(fullpath, "w") as f:
  5871. f.write("BAR")
  5872. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5873. porcelain.commit(
  5874. self.repo.path,
  5875. message=b"Some message",
  5876. author=b"Joe <joe@example.com>",
  5877. committer=b"Bob <bob@example.com>",
  5878. )
  5879. porcelain.tag_create(
  5880. self.repo.path,
  5881. b"tryme",
  5882. b"foo <foo@bar.com>",
  5883. b"bar",
  5884. annotated=True,
  5885. )
  5886. self.assertEqual("tryme", porcelain.describe(self.repo.path))
  5887. def test_tag_and_commit(self) -> None:
  5888. fullpath = os.path.join(self.repo.path, "foo")
  5889. with open(fullpath, "w") as f:
  5890. f.write("BAR")
  5891. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5892. porcelain.commit(
  5893. self.repo.path,
  5894. message=b"Some message",
  5895. author=b"Joe <joe@example.com>",
  5896. committer=b"Bob <bob@example.com>",
  5897. )
  5898. porcelain.tag_create(
  5899. self.repo.path,
  5900. b"tryme",
  5901. b"foo <foo@bar.com>",
  5902. b"bar",
  5903. annotated=True,
  5904. )
  5905. with open(fullpath, "w") as f:
  5906. f.write("BAR2")
  5907. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5908. sha = porcelain.commit(
  5909. self.repo.path,
  5910. message=b"Some message",
  5911. author=b"Joe <joe@example.com>",
  5912. committer=b"Bob <bob@example.com>",
  5913. )
  5914. self.assertEqual(
  5915. "tryme-1-g{}".format(sha[:7].decode("ascii")),
  5916. porcelain.describe(self.repo.path),
  5917. )
  5918. def test_tag_and_commit_full(self) -> None:
  5919. fullpath = os.path.join(self.repo.path, "foo")
  5920. with open(fullpath, "w") as f:
  5921. f.write("BAR")
  5922. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5923. porcelain.commit(
  5924. self.repo.path,
  5925. message=b"Some message",
  5926. author=b"Joe <joe@example.com>",
  5927. committer=b"Bob <bob@example.com>",
  5928. )
  5929. porcelain.tag_create(
  5930. self.repo.path,
  5931. b"tryme",
  5932. b"foo <foo@bar.com>",
  5933. b"bar",
  5934. annotated=True,
  5935. )
  5936. with open(fullpath, "w") as f:
  5937. f.write("BAR2")
  5938. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5939. sha = porcelain.commit(
  5940. self.repo.path,
  5941. message=b"Some message",
  5942. author=b"Joe <joe@example.com>",
  5943. committer=b"Bob <bob@example.com>",
  5944. )
  5945. self.assertEqual(
  5946. "tryme-1-g{}".format(sha.decode("ascii")),
  5947. porcelain.describe(self.repo.path, abbrev=40),
  5948. )
  5949. def test_untagged_commit_abbreviation(self) -> None:
  5950. _, _, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]])
  5951. self.repo.refs[b"HEAD"] = c3.id
  5952. brief_description, complete_description = (
  5953. porcelain.describe(self.repo),
  5954. porcelain.describe(self.repo, abbrev=40),
  5955. )
  5956. self.assertTrue(complete_description.startswith(brief_description))
  5957. self.assertEqual(
  5958. "g{}".format(c3.id.decode("ascii")),
  5959. complete_description,
  5960. )
  5961. def test_hash_length_dynamic(self) -> None:
  5962. """Test that hash length adjusts based on uniqueness."""
  5963. fullpath = os.path.join(self.repo.path, "foo")
  5964. with open(fullpath, "w") as f:
  5965. f.write("content")
  5966. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5967. sha = porcelain.commit(
  5968. self.repo.path,
  5969. message=b"commit",
  5970. author=b"Joe <joe@example.com>",
  5971. committer=b"Bob <bob@example.com>",
  5972. )
  5973. # When abbrev is None, it should use find_unique_abbrev
  5974. result = porcelain.describe(self.repo.path)
  5975. # Should start with 'g' and have at least 7 characters
  5976. self.assertTrue(result.startswith("g"))
  5977. self.assertGreaterEqual(len(result[1:]), 7)
  5978. # Should be a prefix of the full SHA
  5979. self.assertTrue(sha.decode("ascii").startswith(result[1:]))
  5980. class PathToTreeTests(PorcelainTestCase):
  5981. def setUp(self) -> None:
  5982. super().setUp()
  5983. self.fp = os.path.join(self.test_dir, "bar")
  5984. with open(self.fp, "w") as f:
  5985. f.write("something")
  5986. oldcwd = os.getcwd()
  5987. self.addCleanup(os.chdir, oldcwd)
  5988. os.chdir(self.test_dir)
  5989. def test_path_to_tree_path_base(self) -> None:
  5990. self.assertEqual(b"bar", porcelain.path_to_tree_path(self.test_dir, self.fp))
  5991. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  5992. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "bar"))
  5993. cwd = os.getcwd()
  5994. self.assertEqual(
  5995. b"bar", porcelain.path_to_tree_path(".", os.path.join(cwd, "bar"))
  5996. )
  5997. self.assertEqual(b"bar", porcelain.path_to_tree_path(cwd, "bar"))
  5998. def test_path_to_tree_path_syntax(self) -> None:
  5999. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  6000. def test_path_to_tree_path_error(self) -> None:
  6001. with self.assertRaises(ValueError):
  6002. with tempfile.TemporaryDirectory() as od:
  6003. porcelain.path_to_tree_path(od, self.fp)
  6004. def test_path_to_tree_path_rel(self) -> None:
  6005. cwd = os.getcwd()
  6006. self.addCleanup(os.chdir, cwd)
  6007. os.mkdir(os.path.join(self.repo.path, "foo"))
  6008. os.mkdir(os.path.join(self.repo.path, "foo/bar"))
  6009. os.chdir(os.path.join(self.repo.path, "foo/bar"))
  6010. with open("baz", "w") as f:
  6011. f.write("contents")
  6012. self.assertEqual(b"bar/baz", porcelain.path_to_tree_path("..", "baz"))
  6013. self.assertEqual(
  6014. b"bar/baz",
  6015. porcelain.path_to_tree_path(
  6016. os.path.join(os.getcwd(), ".."),
  6017. os.path.join(os.getcwd(), "baz"),
  6018. ),
  6019. )
  6020. self.assertEqual(
  6021. b"bar/baz",
  6022. porcelain.path_to_tree_path("..", os.path.join(os.getcwd(), "baz")),
  6023. )
  6024. self.assertEqual(
  6025. b"bar/baz",
  6026. porcelain.path_to_tree_path(os.path.join(os.getcwd(), ".."), "baz"),
  6027. )
  6028. class GetObjectByPathTests(PorcelainTestCase):
  6029. def test_simple(self) -> None:
  6030. fullpath = os.path.join(self.repo.path, "foo")
  6031. with open(fullpath, "w") as f:
  6032. f.write("BAR")
  6033. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6034. porcelain.commit(
  6035. self.repo.path,
  6036. message=b"Some message",
  6037. author=b"Joe <joe@example.com>",
  6038. committer=b"Bob <bob@example.com>",
  6039. )
  6040. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  6041. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  6042. def test_encoding(self) -> None:
  6043. fullpath = os.path.join(self.repo.path, "foo")
  6044. with open(fullpath, "w") as f:
  6045. f.write("BAR")
  6046. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6047. porcelain.commit(
  6048. self.repo.path,
  6049. message=b"Some message",
  6050. author=b"Joe <joe@example.com>",
  6051. committer=b"Bob <bob@example.com>",
  6052. encoding=b"utf-8",
  6053. )
  6054. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  6055. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  6056. def test_missing(self) -> None:
  6057. self.assertRaises(KeyError, porcelain.get_object_by_path, self.repo, "foo")
  6058. class WriteTreeTests(PorcelainTestCase):
  6059. def test_simple(self) -> None:
  6060. fullpath = os.path.join(self.repo.path, "foo")
  6061. with open(fullpath, "w") as f:
  6062. f.write("BAR")
  6063. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6064. self.assertEqual(
  6065. b"d2092c8a9f311f0311083bf8d177f2ca0ab5b241",
  6066. porcelain.write_tree(self.repo),
  6067. )
  6068. class ActiveBranchTests(PorcelainTestCase):
  6069. def test_simple(self) -> None:
  6070. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  6071. class BranchTrackingTests(PorcelainTestCase):
  6072. def test_get_branch_merge(self) -> None:
  6073. # Set up branch tracking configuration
  6074. config = self.repo.get_config()
  6075. config.set((b"branch", b"master"), b"remote", b"origin")
  6076. config.set((b"branch", b"master"), b"merge", b"refs/heads/main")
  6077. config.write_to_path()
  6078. # Test getting merge ref for current branch
  6079. merge_ref = porcelain.get_branch_merge(self.repo)
  6080. self.assertEqual(b"refs/heads/main", merge_ref)
  6081. # Test getting merge ref for specific branch
  6082. merge_ref = porcelain.get_branch_merge(self.repo, b"master")
  6083. self.assertEqual(b"refs/heads/main", merge_ref)
  6084. # Test branch without merge config
  6085. with self.assertRaises(KeyError):
  6086. porcelain.get_branch_merge(self.repo, b"nonexistent")
  6087. def test_set_branch_tracking(self) -> None:
  6088. # Create a new branch
  6089. sha, _ = _commit_file_with_content(self.repo, "foo", "content\n")
  6090. porcelain.branch_create(self.repo, "feature")
  6091. # Set up tracking
  6092. porcelain.set_branch_tracking(
  6093. self.repo, b"feature", b"upstream", b"refs/heads/main"
  6094. )
  6095. # Verify configuration was written
  6096. config = self.repo.get_config()
  6097. self.assertEqual(b"upstream", config.get((b"branch", b"feature"), b"remote"))
  6098. self.assertEqual(
  6099. b"refs/heads/main", config.get((b"branch", b"feature"), b"merge")
  6100. )
  6101. class FindUniqueAbbrevTests(PorcelainTestCase):
  6102. def test_simple(self) -> None:
  6103. c1, c2, c3 = build_commit_graph(
  6104. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  6105. )
  6106. self.repo.refs[b"HEAD"] = c3.id
  6107. self.assertEqual(
  6108. c1.id.decode("ascii")[:7],
  6109. porcelain.find_unique_abbrev(self.repo.object_store, c1.id),
  6110. )
  6111. class PackRefsTests(PorcelainTestCase):
  6112. def test_all(self) -> None:
  6113. c1, c2, c3 = build_commit_graph(
  6114. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  6115. )
  6116. self.repo.refs[b"HEAD"] = c3.id
  6117. self.repo.refs[b"refs/heads/master"] = c2.id
  6118. self.repo.refs[b"refs/tags/foo"] = c1.id
  6119. porcelain.pack_refs(self.repo, all=True)
  6120. self.assertEqual(
  6121. self.repo.refs.get_packed_refs(),
  6122. {
  6123. b"refs/heads/master": c2.id,
  6124. b"refs/tags/foo": c1.id,
  6125. },
  6126. )
  6127. def test_not_all(self) -> None:
  6128. c1, c2, c3 = build_commit_graph(
  6129. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  6130. )
  6131. self.repo.refs[b"HEAD"] = c3.id
  6132. self.repo.refs[b"refs/heads/master"] = c2.id
  6133. self.repo.refs[b"refs/tags/foo"] = c1.id
  6134. porcelain.pack_refs(self.repo)
  6135. self.assertEqual(
  6136. self.repo.refs.get_packed_refs(),
  6137. {
  6138. b"refs/tags/foo": c1.id,
  6139. },
  6140. )
  6141. class ServerTests(PorcelainTestCase):
  6142. @contextlib.contextmanager
  6143. def _serving(self):
  6144. with make_server("localhost", 0, self.app) as server:
  6145. thread = threading.Thread(target=server.serve_forever, daemon=True)
  6146. thread.start()
  6147. try:
  6148. yield f"http://localhost:{server.server_port}"
  6149. finally:
  6150. server.shutdown()
  6151. thread.join(10)
  6152. def setUp(self) -> None:
  6153. super().setUp()
  6154. self.served_repo_path = os.path.join(self.test_dir, "served_repo.git")
  6155. self.served_repo = Repo.init_bare(self.served_repo_path, mkdir=True)
  6156. self.addCleanup(self.served_repo.close)
  6157. backend = DictBackend({"/": self.served_repo})
  6158. self.app = make_wsgi_chain(backend)
  6159. def test_pull(self) -> None:
  6160. (c1,) = build_commit_graph(self.served_repo.object_store, [[1]])
  6161. self.served_repo.refs[b"refs/heads/master"] = c1.id
  6162. with self._serving() as url:
  6163. porcelain.pull(self.repo, url, "master")
  6164. def test_push(self) -> None:
  6165. (c1,) = build_commit_graph(self.repo.object_store, [[1]])
  6166. self.repo.refs[b"refs/heads/master"] = c1.id
  6167. with self._serving() as url:
  6168. porcelain.push(self.repo, url, "master")
  6169. class ForEachTests(PorcelainTestCase):
  6170. def setUp(self) -> None:
  6171. super().setUp()
  6172. c1, c2, c3, c4 = build_commit_graph(
  6173. self.repo.object_store, [[1], [2, 1], [3, 1, 2], [4]]
  6174. )
  6175. porcelain.tag_create(
  6176. self.repo.path,
  6177. b"v0.1",
  6178. objectish=c1.id,
  6179. annotated=True,
  6180. message=b"0.1",
  6181. )
  6182. porcelain.tag_create(
  6183. self.repo.path,
  6184. b"v1.0",
  6185. objectish=c2.id,
  6186. annotated=True,
  6187. message=b"1.0",
  6188. )
  6189. porcelain.tag_create(self.repo.path, b"simple-tag", objectish=c3.id)
  6190. porcelain.tag_create(
  6191. self.repo.path,
  6192. b"v1.1",
  6193. objectish=c4.id,
  6194. annotated=True,
  6195. message=b"1.1",
  6196. )
  6197. porcelain.branch_create(
  6198. self.repo.path, b"feat", objectish=c2.id.decode("ascii")
  6199. )
  6200. self.repo.refs[b"HEAD"] = c4.id
  6201. def test_for_each_ref(self) -> None:
  6202. refs = porcelain.for_each_ref(self.repo)
  6203. self.assertEqual(
  6204. [(object_type, tag) for _, object_type, tag in refs],
  6205. [
  6206. (b"commit", b"refs/heads/feat"),
  6207. (b"commit", b"refs/heads/master"),
  6208. (b"commit", b"refs/tags/simple-tag"),
  6209. (b"tag", b"refs/tags/v0.1"),
  6210. (b"tag", b"refs/tags/v1.0"),
  6211. (b"tag", b"refs/tags/v1.1"),
  6212. ],
  6213. )
  6214. def test_for_each_ref_pattern(self) -> None:
  6215. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v*")
  6216. self.assertEqual(
  6217. [(object_type, tag) for _, object_type, tag in versions],
  6218. [
  6219. (b"tag", b"refs/tags/v0.1"),
  6220. (b"tag", b"refs/tags/v1.0"),
  6221. (b"tag", b"refs/tags/v1.1"),
  6222. ],
  6223. )
  6224. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v1.?")
  6225. self.assertEqual(
  6226. [(object_type, tag) for _, object_type, tag in versions],
  6227. [
  6228. (b"tag", b"refs/tags/v1.0"),
  6229. (b"tag", b"refs/tags/v1.1"),
  6230. ],
  6231. )
  6232. class SparseCheckoutTests(PorcelainTestCase):
  6233. """Integration tests for Dulwich's sparse checkout feature."""
  6234. # NOTE: We do NOT override `setUp()` here because the parent class
  6235. # (PorcelainTestCase) already:
  6236. # 1) Creates self.test_dir = a unique temp dir
  6237. # 2) Creates a subdir named "repo"
  6238. # 3) Calls Repo.init() on that path
  6239. # Re-initializing again caused FileExistsError.
  6240. #
  6241. # Utility/Placeholder
  6242. #
  6243. def sparse_checkout(self, repo, patterns, force=False):
  6244. """Wrapper around the actual porcelain.sparse_checkout function
  6245. to handle any test-specific setup or logging.
  6246. """
  6247. return porcelain.sparse_checkout(repo, patterns, force=force)
  6248. def _write_file(self, rel_path, content):
  6249. """Helper to write a file in the repository working tree."""
  6250. abs_path = os.path.join(self.repo_path, rel_path)
  6251. os.makedirs(os.path.dirname(abs_path), exist_ok=True)
  6252. with open(abs_path, "w") as f:
  6253. f.write(content)
  6254. return abs_path
  6255. def _commit_file(self, rel_path, content):
  6256. """Helper to write, add, and commit a file."""
  6257. abs_path = self._write_file(rel_path, content)
  6258. add(self.repo_path, paths=[abs_path])
  6259. commit(self.repo_path, message=b"Added " + rel_path.encode("utf-8"))
  6260. def _list_wtree_files(self):
  6261. """Return a set of all files (not dirs) present
  6262. in the working tree, ignoring .git/.
  6263. """
  6264. found_files = set()
  6265. for root, dirs, files in os.walk(self.repo_path):
  6266. # Skip .git in the walk
  6267. if ".git" in dirs:
  6268. dirs.remove(".git")
  6269. for filename in files:
  6270. file_rel = os.path.relpath(os.path.join(root, filename), self.repo_path)
  6271. found_files.add(file_rel)
  6272. return found_files
  6273. def test_only_included_paths_appear_in_wtree(self):
  6274. """Only included paths remain in the working tree, excluded paths are removed.
  6275. Commits two files, "keep_me.txt" and "exclude_me.txt". Then applies a
  6276. sparse-checkout pattern containing only "keep_me.txt". Ensures that
  6277. the latter remains in the working tree, while "exclude_me.txt" is
  6278. removed. This verifies correct application of sparse-checkout patterns
  6279. to remove files not listed.
  6280. """
  6281. self._commit_file("keep_me.txt", "I'll stay\n")
  6282. self._commit_file("exclude_me.txt", "I'll be excluded\n")
  6283. patterns = ["keep_me.txt"]
  6284. self.sparse_checkout(self.repo, patterns)
  6285. actual_files = self._list_wtree_files()
  6286. expected_files = {"keep_me.txt"}
  6287. self.assertEqual(
  6288. expected_files,
  6289. actual_files,
  6290. f"Expected only {expected_files}, but found {actual_files}",
  6291. )
  6292. def test_previously_included_paths_become_excluded(self):
  6293. """Previously included files become excluded after pattern changes.
  6294. Verifies that files initially brought into the working tree (e.g.,
  6295. by including `data/`) can later be excluded by narrowing the
  6296. sparse-checkout pattern to just `data/included_1.txt`. Confirms that
  6297. the file `data/included_2.txt` remains in the index with
  6298. skip-worktree set (rather than being removed entirely), ensuring
  6299. data is not lost and Dulwich correctly updates the index flags.
  6300. """
  6301. self._commit_file("data/included_1.txt", "some content\n")
  6302. self._commit_file("data/included_2.txt", "other content\n")
  6303. initial_patterns = ["data/"]
  6304. self.sparse_checkout(self.repo, initial_patterns)
  6305. updated_patterns = ["data/included_1.txt"]
  6306. self.sparse_checkout(self.repo, updated_patterns)
  6307. actual_files = self._list_wtree_files()
  6308. expected_files = {os.path.join("data", "included_1.txt")}
  6309. self.assertEqual(expected_files, actual_files)
  6310. idx = self.repo.open_index()
  6311. self.assertIn(b"data/included_2.txt", idx)
  6312. entry = idx[b"data/included_2.txt"]
  6313. self.assertTrue(entry.skip_worktree)
  6314. def test_force_removes_local_changes_for_excluded_paths(self):
  6315. """Forced sparse checkout removes local modifications for newly excluded paths.
  6316. Verifies that specifying force=True allows destructive operations
  6317. which discard uncommitted changes. First, we commit "file1.txt" and
  6318. then modify it. Next, we apply a pattern that excludes the file,
  6319. using force=True. The local modifications (and the file) should
  6320. be removed, leaving the working tree empty.
  6321. """
  6322. self._commit_file("file1.txt", "original content\n")
  6323. file1_path = os.path.join(self.repo_path, "file1.txt")
  6324. with open(file1_path, "a") as f:
  6325. f.write("local changes!\n")
  6326. new_patterns = ["some_other_file.txt"]
  6327. self.sparse_checkout(self.repo, new_patterns, force=True)
  6328. actual_files = self._list_wtree_files()
  6329. self.assertEqual(
  6330. set(),
  6331. actual_files,
  6332. "Force-sparse-checkout did not remove file with local changes.",
  6333. )
  6334. def test_destructive_refuse_uncommitted_changes_without_force(self):
  6335. """Fail on uncommitted changes for newly excluded paths without force.
  6336. Ensures that a sparse checkout is blocked if it would remove local
  6337. modifications from the working tree. We commit 'config.yaml', then
  6338. modify it, and finally attempt to exclude it via new patterns without
  6339. using force=True. This should raise a CheckoutError rather than
  6340. discarding the local changes.
  6341. """
  6342. self._commit_file("config.yaml", "initial\n")
  6343. cfg_path = os.path.join(self.repo_path, "config.yaml")
  6344. with open(cfg_path, "a") as f:
  6345. f.write("local modifications\n")
  6346. exclude_patterns = ["docs/"]
  6347. with self.assertRaises(CheckoutError):
  6348. self.sparse_checkout(self.repo, exclude_patterns, force=False)
  6349. def test_fnmatch_gitignore_pattern_expansion(self):
  6350. """Reading/writing patterns align with gitignore/fnmatch expansions.
  6351. Ensures that `sparse_checkout` interprets wildcard patterns (like `*.py`)
  6352. in the same way Git's sparse-checkout would. Multiple files are committed
  6353. to `src/` (e.g. `foo.py`, `foo_test.py`, `foo_helper.py`) and to `docs/`.
  6354. Then the pattern `src/foo*.py` is applied, confirming that only the
  6355. matching Python files remain in the working tree while the Markdown file
  6356. under `docs/` is excluded.
  6357. Finally, verifies that the `.git/info/sparse-checkout` file contains the
  6358. specified wildcard pattern (`src/foo*.py`), ensuring correct round-trip
  6359. of user-supplied patterns.
  6360. """
  6361. self._commit_file("src/foo.py", "print('hello')\n")
  6362. self._commit_file("src/foo_test.py", "print('test')\n")
  6363. self._commit_file("docs/readme.md", "# docs\n")
  6364. self._commit_file("src/foo_helper.py", "print('helper')\n")
  6365. patterns = ["src/foo*.py"]
  6366. self.sparse_checkout(self.repo, patterns)
  6367. actual_files = self._list_wtree_files()
  6368. expected_files = {
  6369. os.path.join("src", "foo.py"),
  6370. os.path.join("src", "foo_test.py"),
  6371. os.path.join("src", "foo_helper.py"),
  6372. }
  6373. self.assertEqual(
  6374. expected_files,
  6375. actual_files,
  6376. "Wildcard pattern not matched as expected. Either too strict or too broad.",
  6377. )
  6378. sc_file = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  6379. self.assertTrue(os.path.isfile(sc_file))
  6380. with open(sc_file) as f:
  6381. lines = f.read().strip().split()
  6382. self.assertIn("src/foo*.py", lines)
  6383. class ConeModeTests(PorcelainTestCase):
  6384. """Provide integration tests for Dulwich's cone mode sparse checkout.
  6385. This test suite verifies the expected behavior for:
  6386. * cone_mode_init
  6387. * cone_mode_set
  6388. * cone_mode_add
  6389. Although Dulwich does not yet implement cone mode, these tests are
  6390. prepared in advance to guide future development.
  6391. """
  6392. def setUp(self):
  6393. """Set up a fresh repository for each test.
  6394. This method creates a new empty repo_path and Repo object
  6395. as provided by the PorcelainTestCase base class.
  6396. """
  6397. super().setUp()
  6398. def _commit_file(self, rel_path, content=b"contents"):
  6399. """Add a file at the given relative path and commit it.
  6400. Creates necessary directories, writes the file content,
  6401. stages, and commits. The commit message and author/committer
  6402. are also provided.
  6403. """
  6404. full_path = os.path.join(self.repo_path, rel_path)
  6405. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  6406. with open(full_path, "wb") as f:
  6407. f.write(content)
  6408. porcelain.add(self.repo_path, paths=[full_path])
  6409. porcelain.commit(
  6410. self.repo_path,
  6411. message=b"Adding " + rel_path.encode("utf-8"),
  6412. author=b"Test Author <author@example.com>",
  6413. committer=b"Test Committer <committer@example.com>",
  6414. )
  6415. def _list_wtree_files(self):
  6416. """Return a set of all file paths relative to the repository root.
  6417. Walks the working tree, skipping the .git directory.
  6418. """
  6419. found_files = set()
  6420. for root, dirs, files in os.walk(self.repo_path):
  6421. if ".git" in dirs:
  6422. dirs.remove(".git")
  6423. for fn in files:
  6424. relp = os.path.relpath(os.path.join(root, fn), self.repo_path)
  6425. found_files.add(relp)
  6426. return found_files
  6427. def test_init_excludes_everything(self):
  6428. """Verify that cone_mode_init writes minimal patterns and empties the working tree.
  6429. Make some dummy files, commit them, then call cone_mode_init. Confirm
  6430. that the working tree is empty, the sparse-checkout file has the
  6431. minimal patterns (/*, !/*/), and the relevant config values are set.
  6432. """
  6433. self._commit_file("docs/readme.md", b"# doc\n")
  6434. self._commit_file("src/main.py", b"print('hello')\n")
  6435. porcelain.cone_mode_init(self.repo)
  6436. actual_files = self._list_wtree_files()
  6437. self.assertEqual(
  6438. set(),
  6439. actual_files,
  6440. "cone_mode_init did not exclude all files from the working tree.",
  6441. )
  6442. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  6443. with open(sp_path) as f:
  6444. lines = [ln.strip() for ln in f if ln.strip()]
  6445. self.assertIn("/*", lines)
  6446. self.assertIn("!/*/", lines)
  6447. config = self.repo.get_config()
  6448. self.assertEqual(config.get((b"core",), b"sparseCheckout"), b"true")
  6449. self.assertEqual(config.get((b"core",), b"sparseCheckoutCone"), b"true")
  6450. def test_set_specific_dirs(self):
  6451. """Verify that cone_mode_set overwrites the included directories to only the specified ones.
  6452. Initializes cone mode, commits some files, then calls cone_mode_set with
  6453. a list of directories. Expects that only those directories remain in the
  6454. working tree.
  6455. """
  6456. porcelain.cone_mode_init(self.repo)
  6457. self._commit_file("docs/readme.md", b"# doc\n")
  6458. self._commit_file("src/main.py", b"print('hello')\n")
  6459. self._commit_file("tests/test_foo.py", b"# tests\n")
  6460. # Everything is still excluded initially by init.
  6461. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  6462. actual_files = self._list_wtree_files()
  6463. expected_files = {
  6464. os.path.join("docs", "readme.md"),
  6465. os.path.join("src", "main.py"),
  6466. }
  6467. self.assertEqual(
  6468. expected_files,
  6469. actual_files,
  6470. "Did not see only the 'docs/' and 'src/' dirs in the working tree.",
  6471. )
  6472. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  6473. with open(sp_path) as f:
  6474. lines = [ln.strip() for ln in f if ln.strip()]
  6475. # For standard cone mode, we'd expect lines like:
  6476. # /* (include top-level files)
  6477. # !/*/ (exclude subdirectories)
  6478. # !/docs/ (re-include docs)
  6479. # !/src/ (re-include src)
  6480. # Instead of the wildcard-based lines the old test used.
  6481. self.assertIn("/*", lines)
  6482. self.assertIn("!/*/", lines)
  6483. self.assertIn("/docs/", lines)
  6484. self.assertIn("/src/", lines)
  6485. self.assertNotIn("/tests/", lines)
  6486. def test_set_overwrites_old_dirs(self):
  6487. """Ensure that calling cone_mode_set again overwrites old includes.
  6488. Initializes cone mode, includes two directories, then calls
  6489. cone_mode_set again with a different directory to confirm the
  6490. new set of includes replaces the old.
  6491. """
  6492. porcelain.cone_mode_init(self.repo)
  6493. self._commit_file("docs/readme.md")
  6494. self._commit_file("src/main.py")
  6495. self._commit_file("tests/test_bar.py")
  6496. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  6497. self.assertEqual(
  6498. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  6499. self._list_wtree_files(),
  6500. )
  6501. # Overwrite includes, now only 'tests'
  6502. porcelain.cone_mode_set(self.repo, dirs=["tests"], force=True)
  6503. actual_files = self._list_wtree_files()
  6504. expected_files = {os.path.join("tests", "test_bar.py")}
  6505. self.assertEqual(expected_files, actual_files)
  6506. def test_force_removal_of_local_mods(self):
  6507. """Confirm that force=True removes local changes in excluded paths.
  6508. cone_mode_init and cone_mode_set are called, a file is locally modified,
  6509. and then cone_mode_set is called again with force=True to exclude that path.
  6510. The excluded file should be removed with no CheckoutError.
  6511. """
  6512. porcelain.cone_mode_init(self.repo)
  6513. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  6514. self._commit_file("docs/readme.md", b"Docs stuff\n")
  6515. self._commit_file("src/main.py", b"print('hello')\n")
  6516. # Modify src/main.py
  6517. with open(os.path.join(self.repo_path, "src/main.py"), "ab") as f:
  6518. f.write(b"extra line\n")
  6519. # Exclude src/ with force=True
  6520. porcelain.cone_mode_set(self.repo, dirs=["docs"], force=True)
  6521. actual_files = self._list_wtree_files()
  6522. expected_files = {os.path.join("docs", "readme.md")}
  6523. self.assertEqual(expected_files, actual_files)
  6524. def test_add_and_merge_dirs(self):
  6525. """Verify that cone_mode_add merges new directories instead of overwriting them.
  6526. After initializing cone mode and including a single directory, call
  6527. cone_mode_add with a new directory. Confirm that both directories
  6528. remain included. Repeat for an additional directory to ensure it
  6529. is merged, not overwritten.
  6530. """
  6531. porcelain.cone_mode_init(self.repo)
  6532. self._commit_file("docs/readme.md", b"# doc\n")
  6533. self._commit_file("src/main.py", b"print('hello')\n")
  6534. self._commit_file("tests/test_bar.py", b"# tests\n")
  6535. # Include "docs" only
  6536. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  6537. self.assertEqual({os.path.join("docs", "readme.md")}, self._list_wtree_files())
  6538. # Add "src"
  6539. porcelain.cone_mode_add(self.repo, dirs=["src"])
  6540. actual_files = self._list_wtree_files()
  6541. self.assertEqual(
  6542. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  6543. actual_files,
  6544. )
  6545. # Add "tests" as well
  6546. porcelain.cone_mode_add(self.repo, dirs=["tests"])
  6547. actual_files = self._list_wtree_files()
  6548. expected_files = {
  6549. os.path.join("docs", "readme.md"),
  6550. os.path.join("src", "main.py"),
  6551. os.path.join("tests", "test_bar.py"),
  6552. }
  6553. self.assertEqual(expected_files, actual_files)
  6554. # Check .git/info/sparse-checkout
  6555. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  6556. with open(sp_path) as f:
  6557. lines = [ln.strip() for ln in f if ln.strip()]
  6558. # Standard cone mode lines:
  6559. # "/*" -> include top-level
  6560. # "!/*/" -> exclude subdirectories
  6561. # "!/docs/", "!/src/", "!/tests/" -> re-include the directories we added
  6562. self.assertIn("/*", lines)
  6563. self.assertIn("!/*/", lines)
  6564. self.assertIn("/docs/", lines)
  6565. self.assertIn("/src/", lines)
  6566. self.assertIn("/tests/", lines)
  6567. class UnpackObjectsTest(PorcelainTestCase):
  6568. def test_unpack_objects(self):
  6569. """Test unpacking objects from a pack file."""
  6570. # Create a test repository with some objects
  6571. b1 = Blob()
  6572. b1.data = b"test content 1"
  6573. b2 = Blob()
  6574. b2.data = b"test content 2"
  6575. # Add objects to the repo
  6576. self.repo.object_store.add_object(b1)
  6577. self.repo.object_store.add_object(b2)
  6578. # Create a pack file with these objects
  6579. pack_path = os.path.join(self.test_dir, "test_pack")
  6580. with (
  6581. open(pack_path + ".pack", "wb") as pack_f,
  6582. open(pack_path + ".idx", "wb") as idx_f,
  6583. ):
  6584. porcelain.pack_objects(
  6585. self.repo,
  6586. [b1.id, b2.id],
  6587. pack_f,
  6588. idx_f,
  6589. )
  6590. # Create a new repository to unpack into
  6591. target_repo_path = os.path.join(self.test_dir, "target_repo")
  6592. target_repo = Repo.init(target_repo_path, mkdir=True)
  6593. self.addCleanup(target_repo.close)
  6594. # Unpack the objects
  6595. count = porcelain.unpack_objects(pack_path + ".pack", target_repo_path)
  6596. # Verify the objects were unpacked
  6597. self.assertEqual(2, count)
  6598. self.assertIn(b1.id, target_repo.object_store)
  6599. self.assertIn(b2.id, target_repo.object_store)
  6600. # Verify the content is correct
  6601. unpacked_b1 = target_repo.object_store[b1.id]
  6602. unpacked_b2 = target_repo.object_store[b2.id]
  6603. self.assertEqual(b1.data, unpacked_b1.data)
  6604. self.assertEqual(b2.data, unpacked_b2.data)
  6605. class CountObjectsTests(PorcelainTestCase):
  6606. def test_count_objects_empty_repo(self):
  6607. """Test counting objects in an empty repository."""
  6608. stats = porcelain.count_objects(self.repo)
  6609. self.assertEqual(0, stats.count)
  6610. self.assertEqual(0, stats.size)
  6611. def test_count_objects_verbose_empty_repo(self):
  6612. """Test verbose counting in an empty repository."""
  6613. stats = porcelain.count_objects(self.repo, verbose=True)
  6614. self.assertEqual(0, stats.count)
  6615. self.assertEqual(0, stats.size)
  6616. self.assertEqual(0, stats.in_pack)
  6617. self.assertEqual(0, stats.packs)
  6618. self.assertEqual(0, stats.size_pack)
  6619. def test_count_objects_with_loose_objects(self):
  6620. """Test counting loose objects."""
  6621. # Create some loose objects
  6622. blob1 = make_object(Blob, data=b"data1")
  6623. blob2 = make_object(Blob, data=b"data2")
  6624. self.repo.object_store.add_object(blob1)
  6625. self.repo.object_store.add_object(blob2)
  6626. stats = porcelain.count_objects(self.repo)
  6627. self.assertEqual(2, stats.count)
  6628. self.assertGreater(stats.size, 0)
  6629. def test_count_objects_verbose_with_objects(self):
  6630. """Test verbose counting with both loose and packed objects."""
  6631. # Add some loose objects
  6632. for i in range(3):
  6633. blob = make_object(Blob, data=f"data{i}".encode())
  6634. self.repo.object_store.add_object(blob)
  6635. # Create a simple commit to have some objects in a pack
  6636. tree = Tree()
  6637. c1 = make_commit(tree=tree.id, message=b"Test commit")
  6638. self.repo.object_store.add_objects([(tree, None), (c1, None)])
  6639. self.repo.refs[b"HEAD"] = c1.id
  6640. # Repack to create a pack file
  6641. porcelain.repack(self.repo)
  6642. stats = porcelain.count_objects(self.repo, verbose=True)
  6643. # After repacking, loose objects might be cleaned up
  6644. self.assertIsInstance(stats.count, int)
  6645. self.assertIsInstance(stats.size, int)
  6646. self.assertGreater(stats.in_pack, 0) # Should have packed objects
  6647. self.assertGreater(stats.packs, 0) # Should have at least one pack
  6648. self.assertGreater(stats.size_pack, 0) # Pack should have size
  6649. # Verify it's the correct dataclass type
  6650. self.assertIsInstance(stats, CountObjectsResult)
  6651. class PruneTests(PorcelainTestCase):
  6652. def test_prune_removes_old_tempfiles(self):
  6653. """Test that prune removes old temporary files."""
  6654. # Create an old temporary file in the objects directory
  6655. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  6656. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_test")
  6657. with open(tmp_pack_path, "wb") as f:
  6658. f.write(b"old temporary data")
  6659. # Make it old
  6660. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  6661. os.utime(tmp_pack_path, (old_time, old_time))
  6662. # Run prune
  6663. porcelain.prune(self.repo.path)
  6664. # Verify the file was removed
  6665. self.assertFalse(os.path.exists(tmp_pack_path))
  6666. def test_prune_keeps_recent_tempfiles(self):
  6667. """Test that prune keeps recent temporary files."""
  6668. # Create a recent temporary file
  6669. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  6670. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_recent")
  6671. with open(tmp_pack_path, "wb") as f:
  6672. f.write(b"recent temporary data")
  6673. self.addCleanup(os.remove, tmp_pack_path)
  6674. # Run prune
  6675. porcelain.prune(self.repo.path)
  6676. # Verify the file was NOT removed
  6677. self.assertTrue(os.path.exists(tmp_pack_path))
  6678. def test_prune_with_custom_grace_period(self):
  6679. """Test prune with custom grace period."""
  6680. # Create a 1-hour-old temporary file
  6681. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  6682. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_1hour")
  6683. with open(tmp_pack_path, "wb") as f:
  6684. f.write(b"1 hour old data")
  6685. # Make it 1 hour old
  6686. old_time = time.time() - 3600
  6687. os.utime(tmp_pack_path, (old_time, old_time))
  6688. # Prune with 30-minute grace period should remove it
  6689. porcelain.prune(self.repo.path, grace_period=1800)
  6690. # Verify the file was removed
  6691. self.assertFalse(os.path.exists(tmp_pack_path))
  6692. def test_prune_dry_run(self):
  6693. """Test prune in dry-run mode."""
  6694. # Create an old temporary file
  6695. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  6696. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_dryrun")
  6697. with open(tmp_pack_path, "wb") as f:
  6698. f.write(b"old temporary data")
  6699. self.addCleanup(os.remove, tmp_pack_path)
  6700. # Make it old
  6701. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  6702. os.utime(tmp_pack_path, (old_time, old_time))
  6703. # Run prune in dry-run mode
  6704. porcelain.prune(self.repo.path, dry_run=True)
  6705. # Verify the file was NOT removed (dry run)
  6706. self.assertTrue(os.path.exists(tmp_pack_path))
  6707. class FilterBranchTests(PorcelainTestCase):
  6708. def setUp(self):
  6709. super().setUp()
  6710. # Create initial commits with different authors
  6711. from dulwich.objects import Commit, Tree
  6712. # Create actual tree and blob objects
  6713. tree = Tree()
  6714. self.repo.object_store.add_object(tree)
  6715. c1 = Commit()
  6716. c1.tree = tree.id
  6717. c1.parents = []
  6718. c1.author = b"Old Author <old@example.com>"
  6719. c1.author_time = 1000
  6720. c1.author_timezone = 0
  6721. c1.committer = b"Old Committer <old@example.com>"
  6722. c1.commit_time = 1000
  6723. c1.commit_timezone = 0
  6724. c1.message = b"Initial commit"
  6725. self.repo.object_store.add_object(c1)
  6726. c2 = Commit()
  6727. c2.tree = tree.id
  6728. c2.parents = [c1.id]
  6729. c2.author = b"Another Author <another@example.com>"
  6730. c2.author_time = 2000
  6731. c2.author_timezone = 0
  6732. c2.committer = b"Another Committer <another@example.com>"
  6733. c2.commit_time = 2000
  6734. c2.commit_timezone = 0
  6735. c2.message = b"Second commit\n\nWith body"
  6736. self.repo.object_store.add_object(c2)
  6737. c3 = Commit()
  6738. c3.tree = tree.id
  6739. c3.parents = [c2.id]
  6740. c3.author = b"Third Author <third@example.com>"
  6741. c3.author_time = 3000
  6742. c3.author_timezone = 0
  6743. c3.committer = b"Third Committer <third@example.com>"
  6744. c3.commit_time = 3000
  6745. c3.commit_timezone = 0
  6746. c3.message = b"Third commit"
  6747. self.repo.object_store.add_object(c3)
  6748. self.repo.refs[b"refs/heads/master"] = c3.id
  6749. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  6750. # Store IDs for test assertions
  6751. self.c1_id = c1.id
  6752. self.c2_id = c2.id
  6753. self.c3_id = c3.id
  6754. def test_filter_branch_author(self):
  6755. """Test filtering branch with author changes."""
  6756. def filter_author(author):
  6757. # Change all authors to "New Author"
  6758. return b"New Author <new@example.com>"
  6759. result = porcelain.filter_branch(
  6760. self.repo_path, "master", filter_author=filter_author
  6761. )
  6762. # Check that we have mappings for all commits
  6763. self.assertEqual(len(result), 3)
  6764. # Verify the branch ref was updated
  6765. new_head = self.repo.refs[b"refs/heads/master"]
  6766. self.assertNotEqual(new_head, self.c3_id)
  6767. # Verify the original ref was saved
  6768. original_ref = self.repo.refs[b"refs/original/refs/heads/master"]
  6769. self.assertEqual(original_ref, self.c3_id)
  6770. # Check that authors were updated
  6771. new_commit = self.repo[new_head]
  6772. self.assertEqual(new_commit.author, b"New Author <new@example.com>")
  6773. # Check parent chain
  6774. parent = self.repo[new_commit.parents[0]]
  6775. self.assertEqual(parent.author, b"New Author <new@example.com>")
  6776. def test_filter_branch_message(self):
  6777. """Test filtering branch with message changes."""
  6778. def filter_message(message):
  6779. # Add prefix to all messages
  6780. return b"[FILTERED] " + message
  6781. porcelain.filter_branch(self.repo_path, "master", filter_message=filter_message)
  6782. # Verify messages were updated
  6783. new_head = self.repo.refs[b"refs/heads/master"]
  6784. new_commit = self.repo[new_head]
  6785. self.assertTrue(new_commit.message.startswith(b"[FILTERED] "))
  6786. def test_filter_branch_custom_filter(self):
  6787. """Test filtering branch with custom filter function."""
  6788. def custom_filter(commit):
  6789. # Change both author and message
  6790. return {
  6791. "author": b"Custom Author <custom@example.com>",
  6792. "message": b"Custom: " + commit.message,
  6793. }
  6794. porcelain.filter_branch(self.repo_path, "master", filter_fn=custom_filter)
  6795. # Verify custom filter was applied
  6796. new_head = self.repo.refs[b"refs/heads/master"]
  6797. new_commit = self.repo[new_head]
  6798. self.assertEqual(new_commit.author, b"Custom Author <custom@example.com>")
  6799. self.assertTrue(new_commit.message.startswith(b"Custom: "))
  6800. def test_filter_branch_no_changes(self):
  6801. """Test filtering branch with no changes."""
  6802. result = porcelain.filter_branch(self.repo_path, "master")
  6803. # All commits should map to themselves
  6804. for old_sha, new_sha in result.items():
  6805. self.assertEqual(old_sha, new_sha)
  6806. # HEAD should be unchanged
  6807. self.assertEqual(self.repo.refs[b"refs/heads/master"], self.c3_id)
  6808. def test_filter_branch_force(self):
  6809. """Test force filtering a previously filtered branch."""
  6810. # First filter
  6811. porcelain.filter_branch(
  6812. self.repo_path, "master", filter_message=lambda m: b"First: " + m
  6813. )
  6814. # Try again without force - should fail
  6815. with self.assertRaises(porcelain.Error):
  6816. porcelain.filter_branch(
  6817. self.repo_path, "master", filter_message=lambda m: b"Second: " + m
  6818. )
  6819. # Try again with force - should succeed
  6820. porcelain.filter_branch(
  6821. self.repo_path,
  6822. "master",
  6823. filter_message=lambda m: b"Second: " + m,
  6824. force=True,
  6825. )
  6826. # Verify second filter was applied
  6827. new_head = self.repo.refs[b"refs/heads/master"]
  6828. new_commit = self.repo[new_head]
  6829. self.assertTrue(new_commit.message.startswith(b"Second: First: "))
  6830. class StashTests(PorcelainTestCase):
  6831. def setUp(self) -> None:
  6832. super().setUp()
  6833. # Create initial commit
  6834. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  6835. f.write(b"initial content")
  6836. porcelain.add(repo=self.repo.path, paths=["initial.txt"])
  6837. porcelain.commit(
  6838. repo=self.repo.path,
  6839. message=b"Initial commit",
  6840. author=b"Test Author <test@example.com>",
  6841. committer=b"Test Committer <test@example.com>",
  6842. )
  6843. def test_stash_push_and_pop(self) -> None:
  6844. # Create a new file and stage it
  6845. new_file = os.path.join(self.repo.path, "new.txt")
  6846. with open(new_file, "wb") as f:
  6847. f.write(b"new file content")
  6848. porcelain.add(repo=self.repo.path, paths=["new.txt"])
  6849. # Modify existing file
  6850. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  6851. f.write(b"modified content")
  6852. # Push to stash
  6853. porcelain.stash_push(self.repo.path)
  6854. # Verify files are reset
  6855. self.assertFalse(os.path.exists(new_file))
  6856. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  6857. self.assertEqual(b"initial content", f.read())
  6858. # Pop the stash
  6859. porcelain.stash_pop(self.repo.path)
  6860. # Verify files are restored
  6861. self.assertTrue(os.path.exists(new_file))
  6862. with open(new_file, "rb") as f:
  6863. self.assertEqual(b"new file content", f.read())
  6864. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  6865. self.assertEqual(b"modified content", f.read())
  6866. # Verify new file is in the index
  6867. from dulwich.index import Index
  6868. index = Index(os.path.join(self.repo.path, ".git", "index"))
  6869. self.assertIn(b"new.txt", index)
  6870. def test_stash_list(self) -> None:
  6871. # Initially no stashes
  6872. stashes = list(porcelain.stash_list(self.repo.path))
  6873. self.assertEqual(0, len(stashes))
  6874. # Create a file and stash it
  6875. test_file = os.path.join(self.repo.path, "test.txt")
  6876. with open(test_file, "wb") as f:
  6877. f.write(b"test content")
  6878. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  6879. # Push first stash
  6880. porcelain.stash_push(self.repo.path)
  6881. # Create another file and stash it
  6882. test_file2 = os.path.join(self.repo.path, "test2.txt")
  6883. with open(test_file2, "wb") as f:
  6884. f.write(b"test content 2")
  6885. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  6886. # Push second stash
  6887. porcelain.stash_push(self.repo.path)
  6888. # Check stash list
  6889. stashes = list(porcelain.stash_list(self.repo.path))
  6890. self.assertEqual(2, len(stashes))
  6891. # Stashes are returned in order (most recent first)
  6892. self.assertEqual(0, stashes[0][0])
  6893. self.assertEqual(1, stashes[1][0])
  6894. def test_stash_drop(self) -> None:
  6895. # Create and stash some changes
  6896. test_file = os.path.join(self.repo.path, "test.txt")
  6897. with open(test_file, "wb") as f:
  6898. f.write(b"test content")
  6899. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  6900. porcelain.stash_push(self.repo.path)
  6901. # Create another stash
  6902. test_file2 = os.path.join(self.repo.path, "test2.txt")
  6903. with open(test_file2, "wb") as f:
  6904. f.write(b"test content 2")
  6905. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  6906. porcelain.stash_push(self.repo.path)
  6907. # Verify we have 2 stashes
  6908. stashes = list(porcelain.stash_list(self.repo.path))
  6909. self.assertEqual(2, len(stashes))
  6910. # Drop the first stash (index 0)
  6911. porcelain.stash_drop(self.repo.path, 0)
  6912. # Verify we have 1 stash left
  6913. stashes = list(porcelain.stash_list(self.repo.path))
  6914. self.assertEqual(1, len(stashes))
  6915. # The remaining stash should be the one we created first
  6916. # Pop it and verify it's the first file
  6917. porcelain.stash_pop(self.repo.path)
  6918. self.assertTrue(os.path.exists(test_file))
  6919. self.assertFalse(os.path.exists(test_file2))
  6920. def test_stash_pop_empty(self) -> None:
  6921. # Attempting to pop from empty stash should raise an error
  6922. with self.assertRaises(IndexError):
  6923. porcelain.stash_pop(self.repo.path)
  6924. def test_stash_with_untracked_files(self) -> None:
  6925. # Create an untracked file
  6926. untracked_file = os.path.join(self.repo.path, "untracked.txt")
  6927. with open(untracked_file, "wb") as f:
  6928. f.write(b"untracked content")
  6929. # Create a tracked change
  6930. tracked_file = os.path.join(self.repo.path, "tracked.txt")
  6931. with open(tracked_file, "wb") as f:
  6932. f.write(b"tracked content")
  6933. porcelain.add(repo=self.repo.path, paths=["tracked.txt"])
  6934. # Stash (by default, untracked files are not included)
  6935. porcelain.stash_push(self.repo.path)
  6936. # Untracked file should still exist
  6937. self.assertTrue(os.path.exists(untracked_file))
  6938. # Tracked file should be gone
  6939. self.assertFalse(os.path.exists(tracked_file))
  6940. # Pop the stash
  6941. porcelain.stash_pop(self.repo.path)
  6942. # Tracked file should be restored
  6943. self.assertTrue(os.path.exists(tracked_file))
  6944. class BisectTests(PorcelainTestCase):
  6945. """Tests for bisect porcelain functions."""
  6946. def test_bisect_start(self):
  6947. """Test starting a bisect session."""
  6948. # Create some commits
  6949. c1, c2, c3 = build_commit_graph(
  6950. self.repo.object_store,
  6951. [[1], [2, 1], [3, 2]],
  6952. attrs={
  6953. 1: {"message": b"initial"},
  6954. 2: {"message": b"second"},
  6955. 3: {"message": b"third"},
  6956. },
  6957. )
  6958. self.repo.refs[b"refs/heads/master"] = c3.id
  6959. self.repo.refs[b"HEAD"] = c3.id
  6960. # Start bisect
  6961. porcelain.bisect_start(self.repo_path)
  6962. # Check that bisect state files exist
  6963. self.assertTrue(
  6964. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  6965. )
  6966. self.assertTrue(
  6967. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_TERMS"))
  6968. )
  6969. self.assertTrue(
  6970. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_NAMES"))
  6971. )
  6972. self.assertTrue(
  6973. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_LOG"))
  6974. )
  6975. def test_bisect_workflow(self):
  6976. """Test a complete bisect workflow."""
  6977. # Create some commits
  6978. c1, c2, c3, c4 = build_commit_graph(
  6979. self.repo.object_store,
  6980. [[1], [2, 1], [3, 2], [4, 3]],
  6981. attrs={
  6982. 1: {"message": b"good commit 1"},
  6983. 2: {"message": b"good commit 2"},
  6984. 3: {"message": b"bad commit"},
  6985. 4: {"message": b"bad commit 2"},
  6986. },
  6987. )
  6988. self.repo.refs[b"refs/heads/master"] = c4.id
  6989. self.repo.refs[b"HEAD"] = c4.id
  6990. # Start bisect with bad and good
  6991. next_sha = porcelain.bisect_start(self.repo_path, bad=c4.id, good=c1.id)
  6992. # Should return the middle commit
  6993. self.assertIsNotNone(next_sha)
  6994. self.assertIn(next_sha, [c2.id, c3.id])
  6995. # Mark the middle commit as good or bad
  6996. if next_sha == c2.id:
  6997. # c2 is good, next should be c3
  6998. next_sha = porcelain.bisect_good(self.repo_path)
  6999. self.assertEqual(next_sha, c3.id)
  7000. # Mark c3 as bad - bisect complete
  7001. next_sha = porcelain.bisect_bad(self.repo_path)
  7002. self.assertIsNone(next_sha)
  7003. else:
  7004. # c3 is bad, next should be c2
  7005. next_sha = porcelain.bisect_bad(self.repo_path)
  7006. self.assertEqual(next_sha, c2.id)
  7007. # Mark c2 as good - bisect complete
  7008. next_sha = porcelain.bisect_good(self.repo_path)
  7009. self.assertIsNone(next_sha)
  7010. def test_bisect_log(self):
  7011. """Test getting bisect log."""
  7012. # Create some commits
  7013. c1, c2, c3 = build_commit_graph(
  7014. self.repo.object_store,
  7015. [[1], [2, 1], [3, 2]],
  7016. attrs={
  7017. 1: {"message": b"initial"},
  7018. 2: {"message": b"second"},
  7019. 3: {"message": b"third"},
  7020. },
  7021. )
  7022. self.repo.refs[b"refs/heads/master"] = c3.id
  7023. self.repo.refs[b"HEAD"] = c3.id
  7024. # Start bisect and mark commits
  7025. porcelain.bisect_start(self.repo_path)
  7026. porcelain.bisect_bad(self.repo_path, c3.id)
  7027. porcelain.bisect_good(self.repo_path, c1.id)
  7028. # Get log
  7029. log = porcelain.bisect_log(self.repo_path)
  7030. self.assertIn("git bisect start", log)
  7031. self.assertIn("git bisect bad", log)
  7032. self.assertIn("git bisect good", log)
  7033. def test_bisect_reset(self):
  7034. """Test resetting bisect state."""
  7035. # Create some commits
  7036. c1, c2, c3 = build_commit_graph(
  7037. self.repo.object_store,
  7038. [[1], [2, 1], [3, 2]],
  7039. attrs={
  7040. 1: {"message": b"initial"},
  7041. 2: {"message": b"second"},
  7042. 3: {"message": b"third"},
  7043. },
  7044. )
  7045. self.repo.refs[b"refs/heads/master"] = c3.id
  7046. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  7047. # Start bisect
  7048. porcelain.bisect_start(self.repo_path)
  7049. porcelain.bisect_bad(self.repo_path)
  7050. porcelain.bisect_good(self.repo_path, c1.id)
  7051. # Reset
  7052. porcelain.bisect_reset(self.repo_path)
  7053. # Check that bisect state files are removed
  7054. self.assertFalse(
  7055. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  7056. )
  7057. self.assertFalse(
  7058. os.path.exists(os.path.join(self.repo.controldir(), "refs", "bisect"))
  7059. )
  7060. # HEAD should be back to being a symbolic ref to master
  7061. head_target, _ = self.repo.refs.follow(b"HEAD")
  7062. self.assertEqual(head_target[-1], b"refs/heads/master")
  7063. def test_bisect_skip(self):
  7064. """Test skipping commits during bisect."""
  7065. # Create some commits
  7066. c1, c2, c3, c4, c5 = build_commit_graph(
  7067. self.repo.object_store,
  7068. [[1], [2, 1], [3, 2], [4, 3], [5, 4]],
  7069. attrs={
  7070. 1: {"message": b"good"},
  7071. 2: {"message": b"skip this"},
  7072. 3: {"message": b"bad"},
  7073. 4: {"message": b"bad"},
  7074. 5: {"message": b"bad"},
  7075. },
  7076. )
  7077. self.repo.refs[b"refs/heads/master"] = c5.id
  7078. self.repo.refs[b"HEAD"] = c5.id
  7079. # Start bisect
  7080. porcelain.bisect_start(self.repo_path, bad=c5.id, good=c1.id)
  7081. # Skip c2 if it's selected
  7082. next_sha = porcelain.bisect_skip(self.repo_path, [c2.id])
  7083. self.assertIsNotNone(next_sha)
  7084. class ReflogTest(PorcelainTestCase):
  7085. def test_reflog_head(self):
  7086. """Test reading HEAD reflog."""
  7087. # Create a commit
  7088. blob = Blob.from_string(b"test content")
  7089. self.repo.object_store.add_object(blob)
  7090. tree = Tree()
  7091. tree.add(b"test", 0o100644, blob.id)
  7092. self.repo.object_store.add_object(tree)
  7093. commit = Commit()
  7094. commit.tree = tree.id
  7095. commit.author = b"Test Author <test@example.com>"
  7096. commit.committer = b"Test Author <test@example.com>"
  7097. commit.commit_time = 1234567890
  7098. commit.commit_timezone = 0
  7099. commit.author_time = 1234567890
  7100. commit.author_timezone = 0
  7101. commit.message = b"Initial commit"
  7102. self.repo.object_store.add_object(commit)
  7103. # Write a reflog entry
  7104. self.repo._write_reflog(
  7105. b"HEAD",
  7106. ZERO_SHA,
  7107. commit.id,
  7108. b"Test Author <test@example.com>",
  7109. 1234567890,
  7110. 0,
  7111. b"commit (initial): Initial commit",
  7112. )
  7113. # Read reflog using porcelain
  7114. entries = list(porcelain.reflog(self.repo_path))
  7115. self.assertEqual(1, len(entries))
  7116. self.assertEqual(ZERO_SHA, entries[0].old_sha)
  7117. self.assertEqual(commit.id, entries[0].new_sha)
  7118. self.assertEqual(b"Test Author <test@example.com>", entries[0].committer)
  7119. self.assertEqual(1234567890, entries[0].timestamp)
  7120. self.assertEqual(0, entries[0].timezone)
  7121. self.assertEqual(b"commit (initial): Initial commit", entries[0].message)
  7122. def test_reflog_with_string_ref(self):
  7123. """Test reading reflog with string reference."""
  7124. # Create a commit
  7125. blob = Blob.from_string(b"test content")
  7126. self.repo.object_store.add_object(blob)
  7127. tree = Tree()
  7128. tree.add(b"test", 0o100644, blob.id)
  7129. self.repo.object_store.add_object(tree)
  7130. commit = Commit()
  7131. commit.tree = tree.id
  7132. commit.author = b"Test Author <test@example.com>"
  7133. commit.committer = b"Test Author <test@example.com>"
  7134. commit.commit_time = 1234567890
  7135. commit.commit_timezone = 0
  7136. commit.author_time = 1234567890
  7137. commit.author_timezone = 0
  7138. commit.message = b"Initial commit"
  7139. self.repo.object_store.add_object(commit)
  7140. # Write a reflog entry
  7141. self.repo._write_reflog(
  7142. b"refs/heads/master",
  7143. ZERO_SHA,
  7144. commit.id,
  7145. b"Test Author <test@example.com>",
  7146. 1234567890,
  7147. 0,
  7148. b"commit (initial): Initial commit",
  7149. )
  7150. # Read reflog using porcelain with string ref
  7151. entries = list(porcelain.reflog(self.repo_path, "refs/heads/master"))
  7152. self.assertEqual(1, len(entries))
  7153. self.assertEqual(commit.id, entries[0].new_sha)
  7154. def test_reflog_all(self):
  7155. """Test reading all reflogs."""
  7156. # Create a commit
  7157. blob = Blob.from_string(b"test content")
  7158. self.repo.object_store.add_object(blob)
  7159. tree = Tree()
  7160. tree.add(b"test", 0o100644, blob.id)
  7161. self.repo.object_store.add_object(tree)
  7162. commit = Commit()
  7163. commit.tree = tree.id
  7164. commit.author = b"Test Author <test@example.com>"
  7165. commit.committer = b"Test Author <test@example.com>"
  7166. commit.commit_time = 1234567890
  7167. commit.commit_timezone = 0
  7168. commit.author_time = 1234567890
  7169. commit.author_timezone = 0
  7170. commit.message = b"Initial commit"
  7171. self.repo.object_store.add_object(commit)
  7172. # Write reflog entries for HEAD and master
  7173. self.repo._write_reflog(
  7174. b"HEAD",
  7175. ZERO_SHA,
  7176. commit.id,
  7177. b"Test Author <test@example.com>",
  7178. 1234567890,
  7179. 0,
  7180. b"commit (initial): Initial commit",
  7181. )
  7182. self.repo._write_reflog(
  7183. b"refs/heads/master",
  7184. ZERO_SHA,
  7185. commit.id,
  7186. b"Test Author <test@example.com>",
  7187. 1234567891,
  7188. 0,
  7189. b"branch: Created from HEAD",
  7190. )
  7191. # Read all reflogs using porcelain
  7192. entries = list(porcelain.reflog(self.repo_path, all=True))
  7193. # Should have at least 2 entries (HEAD and refs/heads/master)
  7194. self.assertGreaterEqual(len(entries), 2)
  7195. # Check that we got entries from different refs
  7196. refs_seen = set()
  7197. for ref, entry in entries:
  7198. refs_seen.add(ref)
  7199. self.assertEqual(commit.id, entry.new_sha)
  7200. # Should have seen at least HEAD and refs/heads/master
  7201. self.assertIn(b"HEAD", refs_seen)
  7202. self.assertIn(b"refs/heads/master", refs_seen)
  7203. class WriteCommitGraphTests(PorcelainTestCase):
  7204. """Tests for the write_commit_graph porcelain function."""
  7205. def test_write_commit_graph_empty_repo(self):
  7206. """Test writing commit graph on empty repository."""
  7207. # Should not fail on empty repo
  7208. porcelain.write_commit_graph(self.repo_path)
  7209. # No commit graph should be created for empty repo
  7210. graph_path = os.path.join(
  7211. self.repo_path, ".git", "objects", "info", "commit-graph"
  7212. )
  7213. self.assertFalse(os.path.exists(graph_path))
  7214. def test_write_commit_graph_with_commits(self):
  7215. """Test writing commit graph with commits."""
  7216. # Create some commits
  7217. c1, c2, c3 = build_commit_graph(
  7218. self.repo.object_store,
  7219. [[1], [2, 1], [3, 1, 2]],
  7220. attrs={
  7221. 1: {"message": b"First commit"},
  7222. 2: {"message": b"Second commit"},
  7223. 3: {"message": b"Merge commit"},
  7224. },
  7225. )
  7226. self.repo.refs[b"refs/heads/master"] = c3.id
  7227. self.repo.refs[b"refs/heads/branch"] = c2.id
  7228. # Write commit graph
  7229. porcelain.write_commit_graph(self.repo_path)
  7230. # Verify commit graph was created
  7231. graph_path = os.path.join(
  7232. self.repo_path, ".git", "objects", "info", "commit-graph"
  7233. )
  7234. self.assertTrue(os.path.exists(graph_path))
  7235. # Load and verify the commit graph
  7236. from dulwich.commit_graph import read_commit_graph
  7237. commit_graph = read_commit_graph(graph_path)
  7238. self.assertIsNotNone(commit_graph)
  7239. self.assertEqual(3, len(commit_graph))
  7240. # Verify all commits are in the graph
  7241. for commit_obj in [c1, c2, c3]:
  7242. entry = commit_graph.get_entry_by_oid(commit_obj.id)
  7243. self.assertIsNotNone(entry)
  7244. def test_write_commit_graph_config_disabled(self):
  7245. """Test that commit graph is not written when disabled by config."""
  7246. # Create a commit
  7247. (c1,) = build_commit_graph(
  7248. self.repo.object_store, [[1]], attrs={1: {"message": b"First commit"}}
  7249. )
  7250. self.repo.refs[b"refs/heads/master"] = c1.id
  7251. # Disable commit graph in config
  7252. config = self.repo.get_config()
  7253. config.set((b"core",), b"commitGraph", b"false")
  7254. config.write_to_path()
  7255. # Write commit graph (should respect config)
  7256. porcelain.write_commit_graph(self.repo_path)
  7257. # Verify commit graph still gets written
  7258. # (porcelain.write_commit_graph explicitly writes regardless of config)
  7259. graph_path = os.path.join(
  7260. self.repo_path, ".git", "objects", "info", "commit-graph"
  7261. )
  7262. self.assertTrue(os.path.exists(graph_path))
  7263. def test_write_commit_graph_reachable_false(self):
  7264. """Test writing commit graph with reachable=False."""
  7265. # Create commits
  7266. c1, c2, c3 = build_commit_graph(
  7267. self.repo.object_store,
  7268. [[1], [2, 1], [3, 2]],
  7269. attrs={
  7270. 1: {"message": b"First commit"},
  7271. 2: {"message": b"Second commit"},
  7272. 3: {"message": b"Third commit"},
  7273. },
  7274. )
  7275. # Only reference the third commit
  7276. self.repo.refs[b"refs/heads/master"] = c3.id
  7277. # Write commit graph with reachable=False
  7278. porcelain.write_commit_graph(self.repo_path, reachable=False)
  7279. # Verify commit graph was created
  7280. graph_path = os.path.join(
  7281. self.repo_path, ".git", "objects", "info", "commit-graph"
  7282. )
  7283. self.assertTrue(os.path.exists(graph_path))
  7284. # Load and verify the commit graph
  7285. from dulwich.commit_graph import read_commit_graph
  7286. commit_graph = read_commit_graph(graph_path)
  7287. self.assertIsNotNone(commit_graph)
  7288. # With reachable=False, only directly referenced commits should be included
  7289. # In this case, only c3 (from refs/heads/master)
  7290. self.assertEqual(1, len(commit_graph))
  7291. entry = commit_graph.get_entry_by_oid(c3.id)
  7292. self.assertIsNotNone(entry)
  7293. class WorktreePorcelainTests(PorcelainTestCase):
  7294. """Tests for porcelain worktree functions."""
  7295. def test_worktree_list_single(self):
  7296. """Test listing worktrees when only main worktree exists."""
  7297. # Create initial commit
  7298. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  7299. f.write("test content")
  7300. porcelain.add(self.repo_path, ["test.txt"])
  7301. porcelain.commit(self.repo_path, message=b"Initial commit")
  7302. # List worktrees
  7303. worktrees = porcelain.worktree_list(self.repo_path)
  7304. self.assertEqual(len(worktrees), 1)
  7305. self.assertEqual(worktrees[0].path, self.repo_path)
  7306. self.assertFalse(worktrees[0].bare)
  7307. self.assertIsNotNone(worktrees[0].head)
  7308. self.assertIsNotNone(worktrees[0].branch)
  7309. def test_worktree_add_branch(self):
  7310. """Test adding a worktree with a new branch."""
  7311. # Create initial commit
  7312. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  7313. f.write("test content")
  7314. porcelain.add(self.repo_path, ["test.txt"])
  7315. porcelain.commit(self.repo_path, message=b"Initial commit")
  7316. # Add worktree
  7317. wt_path = os.path.join(self.test_dir, "worktree1")
  7318. result_path = porcelain.worktree_add(self.repo_path, wt_path, branch=b"feature")
  7319. self.assertEqual(result_path, wt_path)
  7320. self.assertTrue(os.path.exists(wt_path))
  7321. self.assertTrue(os.path.exists(os.path.join(wt_path, ".git")))
  7322. # Check it appears in the list
  7323. worktrees = porcelain.worktree_list(self.repo_path)
  7324. self.assertEqual(len(worktrees), 2)
  7325. # Find the new worktree
  7326. new_wt = None
  7327. for wt in worktrees:
  7328. if wt.path == wt_path:
  7329. new_wt = wt
  7330. break
  7331. self.assertIsNotNone(new_wt)
  7332. self.assertEqual(new_wt.branch, b"refs/heads/feature")
  7333. self.assertFalse(new_wt.detached)
  7334. def test_worktree_add_detached(self):
  7335. """Test adding a detached worktree."""
  7336. # Create initial commit
  7337. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  7338. f.write("test content")
  7339. porcelain.add(self.repo_path, ["test.txt"])
  7340. sha = porcelain.commit(self.repo_path, message=b"Initial commit")
  7341. # Add detached worktree
  7342. wt_path = os.path.join(self.test_dir, "detached")
  7343. porcelain.worktree_add(self.repo_path, wt_path, commit=sha, detach=True)
  7344. # Check it's detached
  7345. worktrees = porcelain.worktree_list(self.repo_path)
  7346. for wt in worktrees:
  7347. if wt.path == wt_path:
  7348. self.assertTrue(wt.detached)
  7349. self.assertIsNone(wt.branch)
  7350. self.assertEqual(wt.head, sha)
  7351. def test_worktree_remove(self):
  7352. """Test removing a worktree."""
  7353. # Create initial commit
  7354. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  7355. f.write("test content")
  7356. porcelain.add(self.repo_path, ["test.txt"])
  7357. porcelain.commit(self.repo_path, message=b"Initial commit")
  7358. # Add and remove worktree
  7359. wt_path = os.path.join(self.test_dir, "to-remove")
  7360. porcelain.worktree_add(self.repo_path, wt_path)
  7361. # Verify it exists
  7362. self.assertTrue(os.path.exists(wt_path))
  7363. self.assertEqual(len(porcelain.worktree_list(self.repo_path)), 2)
  7364. # Remove it
  7365. porcelain.worktree_remove(self.repo_path, wt_path)
  7366. # Verify it's gone
  7367. self.assertFalse(os.path.exists(wt_path))
  7368. self.assertEqual(len(porcelain.worktree_list(self.repo_path)), 1)
  7369. def test_worktree_prune(self):
  7370. """Test pruning worktrees."""
  7371. # Create initial commit
  7372. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  7373. f.write("test content")
  7374. porcelain.add(self.repo_path, ["test.txt"])
  7375. porcelain.commit(self.repo_path, message=b"Initial commit")
  7376. # Add worktree
  7377. wt_path = os.path.join(self.test_dir, "to-prune")
  7378. porcelain.worktree_add(self.repo_path, wt_path)
  7379. # Manually remove directory
  7380. shutil.rmtree(wt_path)
  7381. # Prune should remove the administrative files
  7382. pruned = porcelain.worktree_prune(self.repo_path)
  7383. self.assertEqual(len(pruned), 1)
  7384. # Verify it's gone from the list
  7385. worktrees = porcelain.worktree_list(self.repo_path)
  7386. self.assertEqual(len(worktrees), 1)
  7387. def test_worktree_lock_unlock(self):
  7388. """Test locking and unlocking worktrees."""
  7389. # Create initial commit
  7390. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  7391. f.write("test content")
  7392. porcelain.add(self.repo_path, ["test.txt"])
  7393. porcelain.commit(self.repo_path, message=b"Initial commit")
  7394. # Add worktree
  7395. wt_path = os.path.join(self.test_dir, "lockable")
  7396. porcelain.worktree_add(self.repo_path, wt_path)
  7397. # Lock it
  7398. porcelain.worktree_lock(self.repo_path, wt_path, reason="Testing")
  7399. # Verify it's locked
  7400. worktrees = porcelain.worktree_list(self.repo_path)
  7401. for wt in worktrees:
  7402. if wt.path == wt_path:
  7403. self.assertTrue(wt.locked)
  7404. # Unlock it
  7405. porcelain.worktree_unlock(self.repo_path, wt_path)
  7406. # Verify it's unlocked
  7407. worktrees = porcelain.worktree_list(self.repo_path)
  7408. for wt in worktrees:
  7409. if wt.path == wt_path:
  7410. self.assertFalse(wt.locked)
  7411. def test_worktree_move(self):
  7412. """Test moving a worktree."""
  7413. # Create initial commit
  7414. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  7415. f.write("test content")
  7416. porcelain.add(self.repo_path, ["test.txt"])
  7417. porcelain.commit(self.repo_path, message=b"Initial commit")
  7418. # Add worktree
  7419. old_path = os.path.join(self.test_dir, "old-location")
  7420. porcelain.worktree_add(self.repo_path, old_path)
  7421. # Create a file in the worktree
  7422. test_file = os.path.join(old_path, "workspace.txt")
  7423. with open(test_file, "w") as f:
  7424. f.write("workspace content")
  7425. # Move it
  7426. new_path = os.path.join(self.test_dir, "new-location")
  7427. porcelain.worktree_move(self.repo_path, old_path, new_path)
  7428. # Verify old path doesn't exist, new path does
  7429. self.assertFalse(os.path.exists(old_path))
  7430. self.assertTrue(os.path.exists(new_path))
  7431. self.assertTrue(os.path.exists(os.path.join(new_path, "workspace.txt")))
  7432. # Verify it's in the list at new location
  7433. worktrees = porcelain.worktree_list(self.repo_path)
  7434. paths = [wt.path for wt in worktrees]
  7435. self.assertIn(new_path, paths)
  7436. self.assertNotIn(old_path, paths)