test_porcelain.py 223 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174
  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 public 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, 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. self.test_dir = tempfile.mkdtemp()
  71. self.addCleanup(shutil.rmtree, self.test_dir)
  72. self.repo_path = os.path.join(self.test_dir, "repo")
  73. self.repo = Repo.init(self.repo_path, mkdir=True)
  74. self.addCleanup(self.repo.close)
  75. def assertRecentTimestamp(self, ts) -> None:
  76. # On some slow CIs it does actually take more than 5 seconds to go from
  77. # creating the tag to here.
  78. self.assertLess(time.time() - ts, 50)
  79. @skipIf(gpg is None, "gpg is not available")
  80. class PorcelainGpgTestCase(PorcelainTestCase):
  81. DEFAULT_KEY = """
  82. -----BEGIN PGP PRIVATE KEY BLOCK-----
  83. lQVYBGBjIyIBDADAwydvMPQqeEiK54FG1DHwT5sQejAaJOb+PsOhVa4fLcKsrO3F
  84. g5CxO+/9BHCXAr8xQAtp/gOhDN05fyK3MFyGlL9s+Cd8xf34S3R4rN/qbF0oZmaa
  85. FW0MuGnniq54HINs8KshadVn1Dhi/GYSJ588qNFRl/qxFTYAk+zaGsgX/QgFfy0f
  86. djWXJLypZXu9D6DlyJ0cPSzUlfBkI2Ytx6grzIquRjY0FbkjK3l+iGsQ+ebRMdcP
  87. Sqd5iTN9XuzIUVoBFAZBRjibKV3N2wxlnCbfLlzCyDp7rktzSThzjJ2pVDuLrMAx
  88. 6/L9hIhwmFwdtY4FBFGvMR0b0Ugh3kCsRWr8sgj9I7dUoLHid6ObYhJFhnD3GzRc
  89. U+xX1uy3iTCqJDsG334aQIhC5Giuxln4SUZna2MNbq65ksh38N1aM/t3+Dc/TKVB
  90. rb5KWicRPCQ4DIQkHMDCSPyj+dvRLCPzIaPvHD7IrCfHYHOWuvvPGCpwjo0As3iP
  91. IecoMeguPLVaqgcAEQEAAQAL/i5/pQaUd4G7LDydpbixPS6r9UrfPrU/y5zvBP/p
  92. DCynPDutJ1oq539pZvXQ2VwEJJy7x0UVKkjyMndJLNWly9wHC7o8jkHx/NalVP47
  93. LXR+GWbCdOOcYYbdAWcCNB3zOtzPnWhdAEagkc2G9xRQDIB0dLHLCIUpCbLP/CWM
  94. qlHnDsVMrVTWjgzcpsnyGgw8NeLYJtYGB8dsN+XgCCjo7a9LEvUBKNgdmWBbf14/
  95. iBw7PCugazFcH9QYfZwzhsi3nqRRagTXHbxFRG0LD9Ro9qCEutHYGP2PJ59Nj8+M
  96. zaVkJj/OxWxVOGvn2q16mQBCjKpbWfqXZVVl+G5DGOmiSTZqXy+3j6JCKdOMy6Qd
  97. JBHOHhFZXYmWYaaPzoc33T/C3QhMfY5sOtUDLJmV05Wi4dyBeNBEslYgUuTk/jXb
  98. 5ZAie25eDdrsoqkcnSs2ZguMF7AXhe6il2zVhUUMs/6UZgd6I7I4Is0HXT/pnxEp
  99. uiTRFu4v8E+u+5a8O3pffe5boQYA3TsIxceen20qY+kRaTOkURHMZLn/y6KLW8bZ
  100. rNJyXWS9hBAcbbSGhfOwYfzbDCM17yPQO3E2zo8lcGdRklUdIIaCxQwtu36N5dfx
  101. OLCCQc5LmYdl/EAm91iAhrr7dNntZ18MU09gdzUu+ONZwu4CP3cJT83+qYZULso8
  102. 4Fvd/X8IEfGZ7kM+ylrdqBwtlrn8yYXtom+ows2M2UuNR53B+BUOd73kVLTkTCjE
  103. JH63+nE8BqG7tDLCMws+23SAA3xxBgDfDrr0x7zCozQKVQEqBzQr9Uoo/c/ZjAfi
  104. syzNSrDz+g5gqJYtuL9XpPJVWf6V1GXVyJlSbxR9CjTkBxmlPxpvV25IsbVSsh0o
  105. aqkf2eWpbCL6Qb2E0jd1rvf8sGeTTohzYfiSVVsC2t9ngRO/CmetizwQBvRzLGMZ
  106. 4mtAPiy7ZEDc2dFrPp7zlKISYmJZUx/DJVuZWuOrVMpBP+bSgJXoMTlICxZUqUnE
  107. 2VKVStb/L+Tl8XCwIWdrZb9BaDnHqfcGAM2B4HNPxP88Yj1tEDly/vqeb3vVMhj+
  108. S1lunnLdgxp46YyuTMYAzj88eCGurRtzBsdxxlGAsioEnZGebEqAHQbieKq/DO6I
  109. MOMZHMSVBDqyyIx3assGlxSX8BSFW0lhKyT7i0XqnAgCJ9f/5oq0SbFGq+01VQb7
  110. jIx9PbcYJORxsE0JG/CXXPv27bRtQXsudkWGSYvC0NLOgk4z8+kQpQtyFh16lujq
  111. WRwMeriu0qNDjCa1/eHIKDovhAZ3GyO5/9m1tBlUZXN0IFVzZXIgPHRlc3RAdGVz
  112. dC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAFiEEjrR8
  113. MQ4fJK44PYMvfN2AClLmXiYFAmDcEZEACgkQfN2AClLmXibZzgv/ZfeTpTuqQE1W
  114. C1jT5KpQExnt0BizTX0U7BvSn8Fr6VXTyol6kYc3u71GLUuJyawCLtIzOXqOXJvz
  115. bjcZqymcMADuftKcfMy513FhbF6MhdVd6QoeBP6+7/xXOFJCi+QVYF7SQ2h7K1Qm
  116. +yXOiAMgSxhCZQGPBNJLlDUOd47nSIMANvlumFtmLY/1FD7RpG7WQWjeX1mnxNTw
  117. hUU+Yv7GuFc/JprXCIYqHbhWfvXyVtae2ZK4xuVi5eqwA2RfggOVM7drb+CgPhG0
  118. +9aEDDLOZqVi65wK7J73Puo3rFTbPQMljxw5s27rWqF+vB6hhVdJOPNomWy3naPi
  119. k5MW0mhsacASz1WYndpZz+XaQTq/wJF5HUyyeUWJ0vlOEdwx021PHcqSTyfNnkjD
  120. KncrE21t2sxWRsgGDETxIwkd2b2HNGAvveUD0ffFK/oJHGSXjAERFGc3wuiDj3mQ
  121. BvKm4wt4QF9ZMrCdhMAA6ax5kfEUqQR4ntmrJk/khp/mV7TILaI4nQVYBGBjIyIB
  122. DADghIo9wXnRxzfdDTvwnP8dHpLAIaPokgdpyLswqUCixJWiW2xcV6weUjEWwH6n
  123. eN/t1uZYVehbrotxVPla+MPvzhxp6/cmG+2lhzEBOp6zRwnL1wIB6HoKJfpREhyM
  124. c8rLR0zMso1L1bJTyydvnu07a7BWo3VWKjilb0rEZZUSD/2hidx5HxMOJSoidLWe
  125. d/PPuv6yht3NtA4UThlcfldm9G6PbqCdm1kMEKAkq0wVJvhPJ6gEFRNJimgygfUw
  126. MDFXEIhQtxjgdV5Uoz3O5452VLoRsDlgpi3E0WDGj7WXDaO5uSU0T5aJgVgHCP/f
  127. xZhHuQFk2YYIl5nCBpOZyWWI0IKmscTuEwzpkhICQDQFvcMZ5ibsl7wA2P7YTrQf
  128. FDMjjzuaK80GYPfxDFlyKUyLqFt8w/QzsZLDLX7+jxIEpbRAaMw/JsWqm5BMxxbS
  129. 3CIQiS5S3oSKDsNINelqWFfwvLhvlQra8gIxyNTlek25OdgG66BiiX+seH8A/ql+
  130. F+MAEQEAAQAL/1jrNSLjMt9pwo6qFKClVQZP2vf7+sH7v7LeHIDXr3EnYUnVYnOq
  131. B1FU5PspTp/+J9W25DB9CZLx7Gj8qeslFdiuLSOoIBB4RCToB3kAoeTH0DHqW/Gs
  132. hFTrmJkuDp9zpo/ek6SIXJx5rHAyR9KVw0fizQprH2f6PcgLbTWeM61dJuqowmg3
  133. 7eCOyIKv7VQvFqEhYokLD+JNmrvg+Htg0DXGvdjRjAwPf/NezEXpj67a6cHTp1/C
  134. hwp7pevG+3fTxaCJFesl5/TxxtnaBLE8m2uo/S6Hxgn9l0edonroe1QlTjEqGLy2
  135. 7qi2z5Rem+v6GWNDRgvAWur13v8FNdyduHlioG/NgRsU9mE2MYeFsfi3cfNpJQp/
  136. wC9PSCIXrb/45mkS8KyjZpCrIPB9RV/m0MREq01TPom7rstZc4A1pD0Ot7AtUYS3
  137. e95zLyEmeLziPJ9fV4fgPmEudDr1uItnmV0LOskKlpg5sc0hhdrwYoobfkKt2dx6
  138. DqfMlcM1ZkUbLQYA4jwfpFJG4HmYvjL2xCJxM0ycjvMbqFN+4UjgYWVlRfOrm1V4
  139. Op86FjbRbV6OOCNhznotAg7mul4xtzrrTkK8o3YLBeJseDgl4AWuzXtNa9hE0XpK
  140. 9gJoEHUuBOOsamVh2HpXESFyE5CclOV7JSh541TlZKfnqfZYCg4JSbp0UijkawCL
  141. 5bJJUiGGMD9rZUxIAKQO1DvUEzptS7Jl6S3y5sbIIhilp4KfYWbSk3PPu9CnZD5b
  142. LhEQp0elxnb/IL8PBgD+DpTeC8unkGKXUpbe9x0ISI6V1D6FmJq/FxNg7fMa3QCh
  143. fGiAyoTm80ZETynj+blRaDO3gY4lTLa3Opubof1EqK2QmwXmpyvXEZNYcQfQ2CCS
  144. GOWUCK8jEQamUPf1PWndZXJUmROI1WukhlL71V/ir6zQeVCv1wcwPwclJPnAe87u
  145. pEklnCYpvsEldwHUX9u0BWzoULIEsi+ddtHmT0KTeF/DHRy0W15jIHbjFqhqckj1
  146. /6fmr7l7kIi/kN4vWe0F/0Q8IXX+cVMgbl3aIuaGcvENLGcoAsAtPGx88SfRgmfu
  147. HK64Y7hx1m+Bo215rxJzZRjqHTBPp0BmCi+JKkaavIBrYRbsx20gveI4dzhLcUhB
  148. kiT4Q7oz0/VbGHS1CEf9KFeS/YOGj57s4yHauSVI0XdP9kBRTWmXvBkzsooB2cKH
  149. hwhUN7iiT1k717CiTNUT6Q/pcPFCyNuMoBBGQTU206JEgIjQvI3f8xMUMGmGVVQz
  150. 9/k716ycnhb2JZ/Q/AyQIeHJiQG2BBgBCAAgAhsMFiEEjrR8MQ4fJK44PYMvfN2A
  151. ClLmXiYFAmDcEa4ACgkQfN2AClLmXiZxxQv/XaMN0hPCygtrQMbCsTNb34JbvJzh
  152. hngPuUAfTbRHrR3YeATyQofNbL0DD3fvfzeFF8qESqvzCSZxS6dYsXPd4MCJTzlp
  153. zYBZ2X0sOrgDqZvqCZKN72RKgdk0KvthdzAxsIm2dfcQOxxowXMxhJEXZmsFpusx
  154. jKJxOcrfVRjXJnh9isY0NpCoqMQ+3k3wDJ3VGEHV7G+A+vFkWfbLJF5huQ96uaH9
  155. Uc+jUsREUH9G82ZBqpoioEN8Ith4VXpYnKdTMonK/+ZcyeraJZhXrvbjnEomKdzU
  156. 0pu4bt1HlLR3dcnpjN7b009MBf2xLgEfQk2nPZ4zzY+tDkxygtPllaB4dldFjBpT
  157. j7Q+t49sWMjmlJUbLlHfuJ7nUUK5+cGjBsWVObAEcyfemHWCTVFnEa2BJslGC08X
  158. rFcjRRcMEr9ct4551QFBHsv3O/Wp3/wqczYgE9itSnGT05w+4vLt4smG+dnEHjRJ
  159. brMb2upTHa+kjktjdO96/BgSnKYqmNmPB/qB
  160. =ivA/
  161. -----END PGP PRIVATE KEY BLOCK-----
  162. """
  163. DEFAULT_KEY_ID = "8EB47C310E1F24AE383D832F7CDD800A52E65E26"
  164. NON_DEFAULT_KEY = """
  165. -----BEGIN PGP PRIVATE KEY BLOCK-----
  166. lQVYBGBjI0ABDADGWBRp+t02emfzUlhrc1psqIhhecFm6Em0Kv33cfDpnfoMF1tK
  167. Yy/4eLYIR7FmpdbFPcDThFNHbXJzBi00L1mp0XQE2l50h/2bDAAgREdZ+NVo5a7/
  168. RSZjauNU1PxW6pnXMehEh1tyIQmV78jAukaakwaicrpIenMiFUN3fAKHnLuFffA6
  169. t0f3LqJvTDhUw/o2vPgw5e6UDQhA1C+KTv1KXVrhJNo88a3hZqCZ76z3drKR411Q
  170. zYgT4DUb8lfnbN+z2wfqT9oM5cegh2k86/mxAA3BYOeQrhmQo/7uhezcgbxtdGZr
  171. YlbuaNDTSBrn10ZoaxLPo2dJe2zWxgD6MpvsGU1w3tcRW508qo/+xoWp2/pDzmok
  172. +uhOh1NAj9zB05VWBz1r7oBgCOIKpkD/LD4VKq59etsZ/UnrYDwKdXWZp7uhshkU
  173. M7N35lUJcR76a852dlMdrgpmY18+BP7+o7M+5ElHTiqQbMuE1nHTg8RgVpdV+tUx
  174. dg6GWY/XHf5asm8AEQEAAQAL/A85epOp+GnymmEQfI3+5D178D//Lwu9n86vECB6
  175. xAHCqQtdjZnXpDp/1YUsL59P8nzgYRk7SoMskQDoQ/cB/XFuDOhEdMSgHaTVlnrj
  176. ktCCq6rqGnUosyolbb64vIfVaSqd/5SnCStpAsnaBoBYrAu4ZmV4xfjDQWwn0q5s
  177. u+r56mD0SkjPgbwk/b3qTVagVmf2OFzUgWwm1e/X+bA1oPag1NV8VS4hZPXswT4f
  178. qhiyqUFOgP6vUBcqehkjkIDIl/54xII7/P5tp3LIZawvIXqHKNTqYPCqaCqCj+SL
  179. vMYDIb6acjescfZoM71eAeHAANeFZzr/rwfBT+dEP6qKmPXNcvgE11X44ZCr04nT
  180. zOV/uDUifEvKT5qgtyJpSFEVr7EXubJPKoNNhoYqq9z1pYU7IedX5BloiVXKOKTY
  181. 0pk7JkLqf3g5fYtXh/wol1owemITJy5V5PgaqZvk491LkI6S+kWC7ANYUg+TDPIW
  182. afxW3E5N1CYV6XDAl0ZihbLcoQYAy0Ky/p/wayWKePyuPBLwx9O89GSONK2pQljZ
  183. yaAgxPQ5/i1vx6LIMg7k/722bXR9W3zOjWOin4eatPM3d2hkG96HFvnBqXSmXOPV
  184. 03Xqy1/B5Tj8E9naLKUHE/OBQEc363DgLLG9db5HfPlpAngeppYPdyWkhzXyzkgS
  185. PylaE5eW3zkdjEbYJ6RBTecTZEgBaMvJNPdWbn//frpP7kGvyiCg5Es+WjLInUZ6
  186. 0sdifcNTCewzLXK80v/y5mVOdJhPBgD5zs9cYdyiQJayqAuOr+He1eMHMVUbm9as
  187. qBmPrst398eBW9ZYF7eBfTSlUf6B+WnvyLKEGsUf/7IK0EWDlzoBuWzWiHjUAY1g
  188. m9eTV2MnvCCCefqCErWwfFo2nWOasAZA9sKD+ICIBY4tbtvSl4yfLBzTMwSvs9ZS
  189. K1ocPSYUnhm2miSWZ8RLZPH7roHQasNHpyq/AX7DahFf2S/bJ+46ZGZ8Pigr7hA+
  190. MjmpQ4qVdb5SaViPmZhAKO+PjuCHm+EF/2H0Y3Sl4eXgxZWoQVOUeXdWg9eMfYrj
  191. XDtUMIFppV/QxbeztZKvJdfk64vt/crvLsOp0hOky9cKwY89r4QaHfexU3qR+qDq
  192. UlMvR1rHk7dS5HZAtw0xKsFJNkuDxvBkMqv8Los8zp3nUl+U99dfZOArzNkW38wx
  193. FPa0ixkC9za2BkDrWEA8vTnxw0A2upIFegDUhwOByrSyfPPnG3tKGeqt3Izb/kDk
  194. Q9vmo+HgxBOguMIvlzbBfQZwtbd/gXzlvPqCtCJBbm90aGVyIFRlc3QgVXNlciA8
  195. dGVzdDJAdGVzdC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4B
  196. AheAFiEEapM5P1DF5qzT1vtFuTYhLttOFMAFAmDcEeEACgkQuTYhLttOFMDe0Qv/
  197. Qx/bzXztJ3BCc+CYAVDx7Kr37S68etwwLgcWzhG+CDeMB5F/QE+upKgxy2iaqQFR
  198. mxfOMgf/TIQkUfkbaASzK1LpnesYO85pk7XYjoN1bYEHiXTkeW+bgB6aJIxrRmO2
  199. SrWasdBC/DsI3Mrya8YMt/TiHC6VpRJVxCe5vv7/kZC4CXrgTBnZocXx/YXimbke
  200. poPMVdbvhYh6N0aGeS38jRKgyN10KXmhDTAQDwseVFavBWAjVfx3DEwjtK2Z2GbA
  201. aL8JvAwRtqiPFkDMIKPL4UwxtXFws8SpMt6juroUkNyf6+BxNWYqmwXHPy8zCJAb
  202. xkxIJMlEc+s7qQsP3fILOo8Xn+dVzJ5sa5AoARoXm1GMjsdqaKAzq99Dic/dHnaQ
  203. Civev1PQsdwlYW2C2wNXNeIrxMndbDMFfNuZ6BnGHWJ/wjcp/pFs4YkyyZN8JH7L
  204. hP2FO4Jgham3AuP13kC3Ivea7V6hR8QNcDZRwFPOMIX4tXwQv1T72+7DZGaA25O7
  205. nQVXBGBjI0ABDADJMBYIcG0Yil9YxFs7aYzNbd7alUAr89VbY8eIGPHP3INFPM1w
  206. lBQCu+4j6xdEbhMpppLBZ9A5TEylP4C6qLtPa+oLtPeuSw8gHDE10XE4lbgPs376
  207. rL60XdImSOHhiduACUefYjqpcmFH9Bim1CC+koArYrSQJQx1Jri+OpnTaL/8UID0
  208. KzD/kEgMVGlHIVj9oJmb4+j9pW8I/g0wDSnIaEKFMxqu6SIVJ1GWj+MUMvZigjLC
  209. sNCZd7PnbOC5VeU3SsXj6he74Jx0AmGMPWIHi9M0DjHO5d1cCbXTnud8xxM1bOh4
  210. 7aCTnMK5cVyIr+adihgJpVVhrndSM8aklBPRgtozrGNCgF2CkYU2P1blxfloNr/8
  211. UZpM83o+s1aObBszzRNLxnpNORqoLqjfPtLEPQnagxE+4EapCq0NZ/x6yO5VTwwp
  212. NljdFAEk40uGuKyn1QA3uNMHy5DlpLl+tU7t1KEovdZ+OVYsYKZhVzw0MTpKogk9
  213. JI7AN0q62ronPskAEQEAAQAL+O8BUSt1ZCVjPSIXIsrR+ZOSkszZwgJ1CWIoh0IH
  214. YD2vmcMHGIhFYgBdgerpvhptKhaw7GcXDScEnYkyh5s4GE2hxclik1tbj/x1gYCN
  215. 8BNoyeDdPFxQG73qN12D99QYEctpOsz9xPLIDwmL0j1ehAfhwqHIAPm9Ca+i8JYM
  216. x/F+35S/jnKDXRI+NVlwbiEyXKXxxIqNlpy9i8sDBGexO5H5Sg0zSN/B1duLekGD
  217. biDw6gLc6bCgnS+0JOUpU07Z2fccMOY9ncjKGD2uIb/ePPUaek92GCQyq0eorCIV
  218. brcQsRc5sSsNtnRKQTQtxioROeDg7kf2oWySeHTswlXW/219ihrSXgteHJd+rPm7
  219. DYLEeGLRny8bRKv8rQdAtApHaJE4dAATXeY4RYo4NlXHYaztGYtU6kiM/3zCfWAe
  220. 9Nn+Wh9jMTZrjefUCagS5r6ZqAh7veNo/vgIGaCLh0a1Ypa0Yk9KFrn3LYEM3zgk
  221. 3m3bn+7qgy5cUYXoJ3DGJJEhBgDPonpW0WElqLs5ZMem1ha85SC38F0IkAaSuzuz
  222. v3eORiKWuyJGF32Q2XHa1RHQs1JtUKd8rxFer3b8Oq71zLz6JtVc9dmRudvgcJYX
  223. 0PC11F6WGjZFSSp39dajFp0A5DKUs39F3w7J1yuDM56TDIN810ywufGAHARY1pZb
  224. UJAy/dTqjFnCbNjpAakor3hVzqxcmUG+7Y2X9c2AGncT1MqAQC3M8JZcuZvkK8A9
  225. cMk8B914ryYE7VsZMdMhyTwHmykGAPgNLLa3RDETeGeGCKWI+ZPOoU0ib5JtJZ1d
  226. P3tNwfZKuZBZXKW9gqYqyBa/qhMip84SP30pr/TvulcdAFC759HK8sQZyJ6Vw24P
  227. c+5ssRxrQUEw1rvJPWhmQCmCOZHBMQl5T6eaTOpR5u3aUKTMlxPKhK9eC1dCSTnI
  228. /nyL8An3VKnLy+K/LI42YGphBVLLJmBewuTVDIJviWRdntiG8dElyEJMOywUltk3
  229. 2CEmqgsD9tPO8rXZjnMrMn3gfsiaoQYA6/6/e2utkHr7gAoWBgrBBdqVHsvqh5Ro
  230. 2DjLAOpZItO/EdCJfDAmbTYOa04535sBDP2tcH/vipPOPpbr1Y9Y/mNsKCulNxed
  231. yqAmEkKOcerLUP5UHju0AB6VBjHJFdU2mqT+UjPyBk7WeKXgFomyoYMv3KpNOFWR
  232. xi0Xji4kKHbttA6Hy3UcGPr9acyUAlDYeKmxbSUYIPhw32bbGrX9+F5YriTufRsG
  233. 3jftQVo9zqdcQSD/5pUTMn3EYbEcohYB2YWJAbYEGAEIACACGwwWIQRqkzk/UMXm
  234. rNPW+0W5NiEu204UwAUCYNwR6wAKCRC5NiEu204UwOPnC/92PgB1c3h9FBXH1maz
  235. g29fndHIHH65VLgqMiQ7HAMojwRlT5Xnj5tdkCBmszRkv5vMvdJRa3ZY8Ed/Inqr
  236. hxBFNzpjqX4oj/RYIQLKXWWfkTKYVLJFZFPCSo00jesw2gieu3Ke/Yy4gwhtNodA
  237. v+s6QNMvffTW/K3XNrWDB0E7/LXbdidzhm+MBu8ov2tuC3tp9liLICiE1jv/2xT4
  238. CNSO6yphmk1/1zEYHS/mN9qJ2csBmte2cdmGyOcuVEHk3pyINNMDOamaURBJGRwF
  239. XB5V7gTKUFU4jCp3chywKrBHJHxGGDUmPBmZtDtfWAOgL32drK7/KUyzZL/WO7Fj
  240. akOI0hRDFOcqTYWL20H7+hAiX3oHMP7eou3L5C7wJ9+JMcACklN/WMjG9a536DFJ
  241. 4UgZ6HyKPP+wy837Hbe8b25kNMBwFgiaLR0lcgzxj7NyQWjVCMOEN+M55tRCjvL6
  242. ya6JVZCRbMXfdCy8lVPgtNQ6VlHaj8Wvnn2FLbWWO2n2r3s=
  243. =9zU5
  244. -----END PGP PRIVATE KEY BLOCK-----
  245. """
  246. NON_DEFAULT_KEY_ID = "6A93393F50C5E6ACD3D6FB45B936212EDB4E14C0"
  247. def setUp(self) -> None:
  248. super().setUp()
  249. self.gpg_dir = os.path.join(self.test_dir, "gpg")
  250. os.mkdir(self.gpg_dir, mode=0o700)
  251. # Ignore errors when deleting GNUPGHOME, because of race conditions
  252. # (e.g. the gpg-agent socket having been deleted). See
  253. # https://github.com/jelmer/dulwich/issues/1000
  254. self.addCleanup(shutil.rmtree, self.gpg_dir, ignore_errors=True)
  255. self.overrideEnv("GNUPGHOME", self.gpg_dir)
  256. def import_default_key(self) -> None:
  257. subprocess.run(
  258. ["gpg", "--import"],
  259. stdout=subprocess.DEVNULL,
  260. stderr=subprocess.DEVNULL,
  261. input=PorcelainGpgTestCase.DEFAULT_KEY,
  262. text=True,
  263. )
  264. def import_non_default_key(self) -> None:
  265. subprocess.run(
  266. ["gpg", "--import"],
  267. stdout=subprocess.DEVNULL,
  268. stderr=subprocess.DEVNULL,
  269. input=PorcelainGpgTestCase.NON_DEFAULT_KEY,
  270. text=True,
  271. )
  272. class ArchiveTests(PorcelainTestCase):
  273. """Tests for the archive command."""
  274. def test_simple(self) -> None:
  275. c1, c2, c3 = build_commit_graph(
  276. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  277. )
  278. self.repo.refs[b"refs/heads/master"] = c3.id
  279. out = BytesIO()
  280. err = BytesIO()
  281. porcelain.archive(
  282. self.repo.path, b"refs/heads/master", outstream=out, errstream=err
  283. )
  284. self.assertEqual(b"", err.getvalue())
  285. tf = tarfile.TarFile(fileobj=out)
  286. self.addCleanup(tf.close)
  287. self.assertEqual([], tf.getnames())
  288. class UpdateServerInfoTests(PorcelainTestCase):
  289. def test_simple(self) -> None:
  290. c1, c2, c3 = build_commit_graph(
  291. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  292. )
  293. self.repo.refs[b"refs/heads/foo"] = c3.id
  294. porcelain.update_server_info(self.repo.path)
  295. self.assertTrue(
  296. os.path.exists(os.path.join(self.repo.controldir(), "info", "refs"))
  297. )
  298. class CommitTests(PorcelainTestCase):
  299. def test_custom_author(self) -> None:
  300. c1, c2, c3 = build_commit_graph(
  301. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  302. )
  303. self.repo.refs[b"refs/heads/foo"] = c3.id
  304. sha = porcelain.commit(
  305. self.repo.path,
  306. message=b"Some message",
  307. author=b"Joe <joe@example.com>",
  308. committer=b"Bob <bob@example.com>",
  309. )
  310. self.assertIsInstance(sha, bytes)
  311. self.assertEqual(len(sha), 40)
  312. def test_unicode(self) -> None:
  313. c1, c2, c3 = build_commit_graph(
  314. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  315. )
  316. self.repo.refs[b"refs/heads/foo"] = c3.id
  317. sha = porcelain.commit(
  318. self.repo.path,
  319. message="Some message",
  320. author="Joe <joe@example.com>",
  321. committer="Bob <bob@example.com>",
  322. )
  323. self.assertIsInstance(sha, bytes)
  324. self.assertEqual(len(sha), 40)
  325. def test_no_verify(self) -> None:
  326. if os.name != "posix":
  327. self.skipTest("shell hook tests requires POSIX shell")
  328. self.assertTrue(os.path.exists("/bin/sh"))
  329. hooks_dir = os.path.join(self.repo.controldir(), "hooks")
  330. os.makedirs(hooks_dir, exist_ok=True)
  331. self.addCleanup(shutil.rmtree, hooks_dir)
  332. c1, c2, c3 = build_commit_graph(
  333. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  334. )
  335. hook_fail = "#!/bin/sh\nexit 1"
  336. # hooks are executed in pre-commit, commit-msg order
  337. # test commit-msg failure first, then pre-commit failure, then
  338. # no_verify to skip both hooks
  339. commit_msg = os.path.join(hooks_dir, "commit-msg")
  340. with open(commit_msg, "w") as f:
  341. f.write(hook_fail)
  342. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  343. with self.assertRaises(CommitError):
  344. porcelain.commit(
  345. self.repo.path,
  346. message="Some message",
  347. author="Joe <joe@example.com>",
  348. committer="Bob <bob@example.com>",
  349. )
  350. pre_commit = os.path.join(hooks_dir, "pre-commit")
  351. with open(pre_commit, "w") as f:
  352. f.write(hook_fail)
  353. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  354. with self.assertRaises(CommitError):
  355. porcelain.commit(
  356. self.repo.path,
  357. message="Some message",
  358. author="Joe <joe@example.com>",
  359. committer="Bob <bob@example.com>",
  360. )
  361. sha = porcelain.commit(
  362. self.repo.path,
  363. message="Some message",
  364. author="Joe <joe@example.com>",
  365. committer="Bob <bob@example.com>",
  366. no_verify=True,
  367. )
  368. self.assertIsInstance(sha, bytes)
  369. self.assertEqual(len(sha), 40)
  370. def test_timezone(self) -> None:
  371. c1, c2, c3 = build_commit_graph(
  372. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  373. )
  374. self.repo.refs[b"refs/heads/foo"] = c3.id
  375. sha = porcelain.commit(
  376. self.repo.path,
  377. message="Some message",
  378. author="Joe <joe@example.com>",
  379. author_timezone=18000,
  380. committer="Bob <bob@example.com>",
  381. commit_timezone=18000,
  382. )
  383. self.assertIsInstance(sha, bytes)
  384. self.assertEqual(len(sha), 40)
  385. commit = self.repo.get_object(sha)
  386. self.assertEqual(commit._author_timezone, 18000)
  387. self.assertEqual(commit._commit_timezone, 18000)
  388. self.overrideEnv("GIT_AUTHOR_DATE", "1995-11-20T19:12:08-0501")
  389. self.overrideEnv("GIT_COMMITTER_DATE", "1995-11-20T19:12:08-0501")
  390. sha = porcelain.commit(
  391. self.repo.path,
  392. message="Some message",
  393. author="Joe <joe@example.com>",
  394. committer="Bob <bob@example.com>",
  395. )
  396. self.assertIsInstance(sha, bytes)
  397. self.assertEqual(len(sha), 40)
  398. commit = self.repo.get_object(sha)
  399. self.assertEqual(commit._author_timezone, -18060)
  400. self.assertEqual(commit._commit_timezone, -18060)
  401. self.overrideEnv("GIT_AUTHOR_DATE", None)
  402. self.overrideEnv("GIT_COMMITTER_DATE", None)
  403. local_timezone = time.localtime().tm_gmtoff
  404. sha = porcelain.commit(
  405. self.repo.path,
  406. message="Some message",
  407. author="Joe <joe@example.com>",
  408. committer="Bob <bob@example.com>",
  409. )
  410. self.assertIsInstance(sha, bytes)
  411. self.assertEqual(len(sha), 40)
  412. commit = self.repo.get_object(sha)
  413. self.assertEqual(commit._author_timezone, local_timezone)
  414. self.assertEqual(commit._commit_timezone, local_timezone)
  415. @skipIf(
  416. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  417. "gpgme not easily available or supported on Windows and PyPy",
  418. )
  419. class CommitSignTests(PorcelainGpgTestCase):
  420. def test_default_key(self) -> None:
  421. c1, c2, c3 = build_commit_graph(
  422. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  423. )
  424. self.repo.refs[b"HEAD"] = c3.id
  425. cfg = self.repo.get_config()
  426. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  427. self.import_default_key()
  428. sha = porcelain.commit(
  429. self.repo.path,
  430. message="Some message",
  431. author="Joe <joe@example.com>",
  432. committer="Bob <bob@example.com>",
  433. signoff=True,
  434. )
  435. self.assertIsInstance(sha, bytes)
  436. self.assertEqual(len(sha), 40)
  437. commit = self.repo.get_object(sha)
  438. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  439. commit.verify()
  440. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  441. self.import_non_default_key()
  442. self.assertRaises(
  443. gpg.errors.MissingSignatures,
  444. commit.verify,
  445. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  446. )
  447. commit.committer = b"Alice <alice@example.com>"
  448. self.assertRaises(
  449. gpg.errors.BadSignatures,
  450. commit.verify,
  451. )
  452. def test_non_default_key(self) -> None:
  453. c1, c2, c3 = build_commit_graph(
  454. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  455. )
  456. self.repo.refs[b"HEAD"] = c3.id
  457. cfg = self.repo.get_config()
  458. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  459. self.import_non_default_key()
  460. sha = porcelain.commit(
  461. self.repo.path,
  462. message="Some message",
  463. author="Joe <joe@example.com>",
  464. committer="Bob <bob@example.com>",
  465. signoff=PorcelainGpgTestCase.NON_DEFAULT_KEY_ID,
  466. )
  467. self.assertIsInstance(sha, bytes)
  468. self.assertEqual(len(sha), 40)
  469. commit = self.repo.get_object(sha)
  470. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  471. commit.verify()
  472. class TimezoneTests(PorcelainTestCase):
  473. def put_envs(self, value) -> None:
  474. self.overrideEnv("GIT_AUTHOR_DATE", value)
  475. self.overrideEnv("GIT_COMMITTER_DATE", value)
  476. def fallback(self, value) -> None:
  477. self.put_envs(value)
  478. self.assertRaises(porcelain.TimezoneFormatError, porcelain.get_user_timezones)
  479. def test_internal_format(self) -> None:
  480. self.put_envs("0 +0500")
  481. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  482. def test_rfc_2822(self) -> None:
  483. self.put_envs("Mon, 20 Nov 1995 19:12:08 -0500")
  484. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  485. self.put_envs("Mon, 20 Nov 1995 19:12:08")
  486. self.assertTupleEqual((0, 0), porcelain.get_user_timezones())
  487. def test_iso8601(self) -> None:
  488. self.put_envs("1995-11-20T19:12:08-0501")
  489. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  490. self.put_envs("1995-11-20T19:12:08+0501")
  491. self.assertTupleEqual((18060, 18060), porcelain.get_user_timezones())
  492. self.put_envs("1995-11-20T19:12:08-05:01")
  493. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  494. self.put_envs("1995-11-20 19:12:08-05")
  495. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  496. # https://github.com/git/git/blob/96b2d4fa927c5055adc5b1d08f10a5d7352e2989/t/t6300-for-each-ref.sh#L128
  497. self.put_envs("2006-07-03 17:18:44 +0200")
  498. self.assertTupleEqual((7200, 7200), porcelain.get_user_timezones())
  499. def test_missing_or_malformed(self) -> None:
  500. # TODO: add more here
  501. self.fallback("0 + 0500")
  502. self.fallback("a +0500")
  503. self.fallback("1995-11-20T19:12:08")
  504. self.fallback("1995-11-20T19:12:08-05:")
  505. self.fallback("1995.11.20")
  506. self.fallback("11/20/1995")
  507. self.fallback("20.11.1995")
  508. def test_different_envs(self) -> None:
  509. self.overrideEnv("GIT_AUTHOR_DATE", "0 +0500")
  510. self.overrideEnv("GIT_COMMITTER_DATE", "0 +0501")
  511. self.assertTupleEqual((18000, 18060), porcelain.get_user_timezones())
  512. def test_no_envs(self) -> None:
  513. local_timezone = time.localtime().tm_gmtoff
  514. self.put_envs("0 +0500")
  515. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  516. self.overrideEnv("GIT_COMMITTER_DATE", None)
  517. self.assertTupleEqual((18000, local_timezone), porcelain.get_user_timezones())
  518. self.put_envs("0 +0500")
  519. self.overrideEnv("GIT_AUTHOR_DATE", None)
  520. self.assertTupleEqual((local_timezone, 18000), porcelain.get_user_timezones())
  521. self.put_envs("0 +0500")
  522. self.overrideEnv("GIT_AUTHOR_DATE", None)
  523. self.overrideEnv("GIT_COMMITTER_DATE", None)
  524. self.assertTupleEqual(
  525. (local_timezone, local_timezone), porcelain.get_user_timezones()
  526. )
  527. class CleanTests(PorcelainTestCase):
  528. def put_files(self, tracked, ignored, untracked, empty_dirs) -> None:
  529. """Put the described files in the wd."""
  530. all_files = tracked | ignored | untracked
  531. for file_path in all_files:
  532. abs_path = os.path.join(self.repo.path, file_path)
  533. # File may need to be written in a dir that doesn't exist yet, so
  534. # create the parent dir(s) as necessary
  535. parent_dir = os.path.dirname(abs_path)
  536. try:
  537. os.makedirs(parent_dir)
  538. except FileExistsError:
  539. pass
  540. with open(abs_path, "w") as f:
  541. f.write("")
  542. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  543. f.writelines(ignored)
  544. for dir_path in empty_dirs:
  545. os.mkdir(os.path.join(self.repo.path, "empty_dir"))
  546. files_to_add = [os.path.join(self.repo.path, t) for t in tracked]
  547. porcelain.add(repo=self.repo.path, paths=files_to_add)
  548. porcelain.commit(repo=self.repo.path, message="init commit")
  549. def assert_wd(self, expected_paths) -> None:
  550. """Assert paths of files and dirs in wd are same as expected_paths."""
  551. control_dir_rel = os.path.relpath(self.repo._controldir, self.repo.path)
  552. # normalize paths to simplify comparison across platforms
  553. found_paths = {
  554. os.path.normpath(p)
  555. for p in flat_walk_dir(self.repo.path)
  556. if not p.split(os.sep)[0] == control_dir_rel
  557. }
  558. norm_expected_paths = {os.path.normpath(p) for p in expected_paths}
  559. self.assertEqual(found_paths, norm_expected_paths)
  560. def test_from_root(self) -> None:
  561. self.put_files(
  562. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  563. ignored={"ignored_file"},
  564. untracked={
  565. "untracked_file",
  566. "tracked_dir/untracked_dir/untracked_file",
  567. "untracked_dir/untracked_dir/untracked_file",
  568. },
  569. empty_dirs={"empty_dir"},
  570. )
  571. porcelain.clean(repo=self.repo.path, target_dir=self.repo.path)
  572. self.assert_wd(
  573. {
  574. "tracked_file",
  575. "tracked_dir/tracked_file",
  576. ".gitignore",
  577. "ignored_file",
  578. "tracked_dir",
  579. }
  580. )
  581. def test_from_subdir(self) -> None:
  582. self.put_files(
  583. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  584. ignored={"ignored_file"},
  585. untracked={
  586. "untracked_file",
  587. "tracked_dir/untracked_dir/untracked_file",
  588. "untracked_dir/untracked_dir/untracked_file",
  589. },
  590. empty_dirs={"empty_dir"},
  591. )
  592. porcelain.clean(
  593. repo=self.repo,
  594. target_dir=os.path.join(self.repo.path, "untracked_dir"),
  595. )
  596. self.assert_wd(
  597. {
  598. "tracked_file",
  599. "tracked_dir/tracked_file",
  600. ".gitignore",
  601. "ignored_file",
  602. "untracked_file",
  603. "tracked_dir/untracked_dir/untracked_file",
  604. "empty_dir",
  605. "untracked_dir",
  606. "tracked_dir",
  607. "tracked_dir/untracked_dir",
  608. }
  609. )
  610. class CloneTests(PorcelainTestCase):
  611. def test_simple_local(self) -> None:
  612. f1_1 = make_object(Blob, data=b"f1")
  613. commit_spec = [[1], [2, 1], [3, 1, 2]]
  614. trees = {
  615. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  616. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  617. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  618. }
  619. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  620. self.repo.refs[b"refs/heads/master"] = c3.id
  621. self.repo.refs[b"refs/tags/foo"] = c3.id
  622. target_path = tempfile.mkdtemp()
  623. errstream = BytesIO()
  624. self.addCleanup(shutil.rmtree, target_path)
  625. r = porcelain.clone(
  626. self.repo.path, target_path, checkout=False, errstream=errstream
  627. )
  628. self.addCleanup(r.close)
  629. self.assertEqual(r.path, target_path)
  630. target_repo = Repo(target_path)
  631. self.assertEqual(0, len(target_repo.open_index()))
  632. self.assertEqual(c3.id, target_repo.refs[b"refs/tags/foo"])
  633. self.assertNotIn(b"f1", os.listdir(target_path))
  634. self.assertNotIn(b"f2", os.listdir(target_path))
  635. c = r.get_config()
  636. encoded_path = self.repo.path
  637. if not isinstance(encoded_path, bytes):
  638. encoded_path = encoded_path.encode("utf-8")
  639. self.assertEqual(encoded_path, c.get((b"remote", b"origin"), b"url"))
  640. self.assertEqual(
  641. b"+refs/heads/*:refs/remotes/origin/*",
  642. c.get((b"remote", b"origin"), b"fetch"),
  643. )
  644. def test_simple_local_with_checkout(self) -> None:
  645. f1_1 = make_object(Blob, data=b"f1")
  646. commit_spec = [[1], [2, 1], [3, 1, 2]]
  647. trees = {
  648. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  649. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  650. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  651. }
  652. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  653. self.repo.refs[b"refs/heads/master"] = c3.id
  654. target_path = tempfile.mkdtemp()
  655. errstream = BytesIO()
  656. self.addCleanup(shutil.rmtree, target_path)
  657. with porcelain.clone(
  658. self.repo.path, target_path, checkout=True, errstream=errstream
  659. ) as r:
  660. self.assertEqual(r.path, target_path)
  661. with Repo(target_path) as r:
  662. self.assertEqual(r.head(), c3.id)
  663. self.assertIn("f1", os.listdir(target_path))
  664. self.assertIn("f2", os.listdir(target_path))
  665. def test_bare_local_with_checkout(self) -> None:
  666. f1_1 = make_object(Blob, data=b"f1")
  667. commit_spec = [[1], [2, 1], [3, 1, 2]]
  668. trees = {
  669. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  670. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  671. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  672. }
  673. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  674. self.repo.refs[b"refs/heads/master"] = c3.id
  675. target_path = tempfile.mkdtemp()
  676. errstream = BytesIO()
  677. self.addCleanup(shutil.rmtree, target_path)
  678. with porcelain.clone(
  679. self.repo.path, target_path, bare=True, errstream=errstream
  680. ) as r:
  681. self.assertEqual(r.path, target_path)
  682. with Repo(target_path) as r:
  683. r.head()
  684. self.assertRaises(NoIndexPresent, r.open_index)
  685. self.assertNotIn(b"f1", os.listdir(target_path))
  686. self.assertNotIn(b"f2", os.listdir(target_path))
  687. def test_no_checkout_with_bare(self) -> None:
  688. f1_1 = make_object(Blob, data=b"f1")
  689. commit_spec = [[1]]
  690. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  691. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  692. self.repo.refs[b"refs/heads/master"] = c1.id
  693. self.repo.refs[b"HEAD"] = c1.id
  694. target_path = tempfile.mkdtemp()
  695. errstream = BytesIO()
  696. self.addCleanup(shutil.rmtree, target_path)
  697. self.assertRaises(
  698. porcelain.Error,
  699. porcelain.clone,
  700. self.repo.path,
  701. target_path,
  702. checkout=True,
  703. bare=True,
  704. errstream=errstream,
  705. )
  706. def test_no_head_no_checkout(self) -> None:
  707. f1_1 = make_object(Blob, data=b"f1")
  708. commit_spec = [[1]]
  709. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  710. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  711. self.repo.refs[b"refs/heads/master"] = c1.id
  712. target_path = tempfile.mkdtemp()
  713. self.addCleanup(shutil.rmtree, target_path)
  714. errstream = BytesIO()
  715. r = porcelain.clone(
  716. self.repo.path, target_path, checkout=True, errstream=errstream
  717. )
  718. r.close()
  719. def test_no_head_no_checkout_outstream_errstream_autofallback(self) -> None:
  720. f1_1 = make_object(Blob, data=b"f1")
  721. commit_spec = [[1]]
  722. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  723. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  724. self.repo.refs[b"refs/heads/master"] = c1.id
  725. target_path = tempfile.mkdtemp()
  726. self.addCleanup(shutil.rmtree, target_path)
  727. errstream = porcelain.NoneStream()
  728. r = porcelain.clone(
  729. self.repo.path, target_path, checkout=True, errstream=errstream
  730. )
  731. r.close()
  732. def test_source_broken(self) -> None:
  733. with tempfile.TemporaryDirectory() as parent:
  734. target_path = os.path.join(parent, "target")
  735. self.assertRaises(
  736. Exception, porcelain.clone, "/nonexistent/repo", target_path
  737. )
  738. self.assertFalse(os.path.exists(target_path))
  739. def test_fetch_symref(self) -> None:
  740. f1_1 = make_object(Blob, data=b"f1")
  741. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  742. [c1] = build_commit_graph(self.repo.object_store, [[1]], trees)
  743. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/else")
  744. self.repo.refs[b"refs/heads/else"] = c1.id
  745. target_path = tempfile.mkdtemp()
  746. errstream = BytesIO()
  747. self.addCleanup(shutil.rmtree, target_path)
  748. r = porcelain.clone(
  749. self.repo.path, target_path, checkout=False, errstream=errstream
  750. )
  751. self.addCleanup(r.close)
  752. self.assertEqual(r.path, target_path)
  753. target_repo = Repo(target_path)
  754. self.assertEqual(0, len(target_repo.open_index()))
  755. self.assertEqual(c1.id, target_repo.refs[b"refs/heads/else"])
  756. self.assertEqual(c1.id, target_repo.refs[b"HEAD"])
  757. self.assertEqual(
  758. {
  759. b"HEAD": b"refs/heads/else",
  760. b"refs/remotes/origin/HEAD": b"refs/remotes/origin/else",
  761. },
  762. target_repo.refs.get_symrefs(),
  763. )
  764. def test_detached_head(self) -> None:
  765. f1_1 = make_object(Blob, data=b"f1")
  766. commit_spec = [[1], [2, 1], [3, 1, 2]]
  767. trees = {
  768. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  769. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  770. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  771. }
  772. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  773. self.repo.refs[b"refs/heads/master"] = c2.id
  774. self.repo.refs.remove_if_equals(b"HEAD", None)
  775. self.repo.refs[b"HEAD"] = c3.id
  776. target_path = tempfile.mkdtemp()
  777. self.addCleanup(shutil.rmtree, target_path)
  778. errstream = porcelain.NoneStream()
  779. with porcelain.clone(
  780. self.repo.path, target_path, checkout=True, errstream=errstream
  781. ) as r:
  782. self.assertEqual(c3.id, r.refs[b"HEAD"])
  783. def test_clone_pathlib(self) -> None:
  784. from pathlib import Path
  785. f1_1 = make_object(Blob, data=b"f1")
  786. commit_spec = [[1]]
  787. trees = {1: [(b"f1", f1_1)]}
  788. c1 = build_commit_graph(self.repo.object_store, commit_spec, trees)[0]
  789. self.repo.refs[b"refs/heads/master"] = c1.id
  790. target_dir = tempfile.mkdtemp()
  791. self.addCleanup(shutil.rmtree, target_dir)
  792. target_path = Path(target_dir) / "clone_repo"
  793. errstream = BytesIO()
  794. r = porcelain.clone(
  795. self.repo.path, target_path, checkout=False, errstream=errstream
  796. )
  797. self.addCleanup(r.close)
  798. self.assertEqual(r.path, str(target_path))
  799. self.assertTrue(os.path.exists(str(target_path)))
  800. class InitTests(TestCase):
  801. def test_non_bare(self) -> None:
  802. repo_dir = tempfile.mkdtemp()
  803. self.addCleanup(shutil.rmtree, repo_dir)
  804. porcelain.init(repo_dir)
  805. def test_bare(self) -> None:
  806. repo_dir = tempfile.mkdtemp()
  807. self.addCleanup(shutil.rmtree, repo_dir)
  808. porcelain.init(repo_dir, bare=True)
  809. def test_init_pathlib(self) -> None:
  810. from pathlib import Path
  811. repo_dir = tempfile.mkdtemp()
  812. self.addCleanup(shutil.rmtree, repo_dir)
  813. repo_path = Path(repo_dir)
  814. # Test non-bare repo with pathlib
  815. repo = porcelain.init(repo_path)
  816. self.assertTrue(os.path.exists(os.path.join(repo_dir, ".git")))
  817. repo.close()
  818. def test_init_bare_pathlib(self) -> None:
  819. from pathlib import Path
  820. repo_dir = tempfile.mkdtemp()
  821. self.addCleanup(shutil.rmtree, repo_dir)
  822. repo_path = Path(repo_dir)
  823. # Test bare repo with pathlib
  824. repo = porcelain.init(repo_path, bare=True)
  825. self.assertTrue(os.path.exists(os.path.join(repo_dir, "refs")))
  826. repo.close()
  827. class AddTests(PorcelainTestCase):
  828. def test_add_default_paths(self) -> None:
  829. # create a file for initial commit
  830. fullpath = os.path.join(self.repo.path, "blah")
  831. with open(fullpath, "w") as f:
  832. f.write("\n")
  833. porcelain.add(repo=self.repo.path, paths=[fullpath])
  834. porcelain.commit(
  835. repo=self.repo.path,
  836. message=b"test",
  837. author=b"test <email>",
  838. committer=b"test <email>",
  839. )
  840. # Add a second test file and a file in a directory
  841. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  842. f.write("\n")
  843. os.mkdir(os.path.join(self.repo.path, "adir"))
  844. with open(os.path.join(self.repo.path, "adir", "afile"), "w") as f:
  845. f.write("\n")
  846. cwd = os.getcwd()
  847. try:
  848. os.chdir(self.repo.path)
  849. self.assertEqual({"foo", "blah", "adir", ".git"}, set(os.listdir(".")))
  850. added, ignored = porcelain.add(self.repo.path)
  851. # Normalize paths to use forward slashes for comparison
  852. added_normalized = [path.replace(os.sep, "/") for path in added]
  853. self.assertEqual(
  854. (added_normalized, ignored),
  855. (["foo", "adir/afile"], set()),
  856. )
  857. finally:
  858. os.chdir(cwd)
  859. # Check that foo was added and nothing in .git was modified
  860. index = self.repo.open_index()
  861. self.assertEqual(sorted(index), [b"adir/afile", b"blah", b"foo"])
  862. def test_add_default_paths_subdir(self) -> None:
  863. os.mkdir(os.path.join(self.repo.path, "foo"))
  864. with open(os.path.join(self.repo.path, "blah"), "w") as f:
  865. f.write("\n")
  866. with open(os.path.join(self.repo.path, "foo", "blie"), "w") as f:
  867. f.write("\n")
  868. cwd = os.getcwd()
  869. try:
  870. os.chdir(os.path.join(self.repo.path, "foo"))
  871. porcelain.add(repo=self.repo.path)
  872. porcelain.commit(
  873. repo=self.repo.path,
  874. message=b"test",
  875. author=b"test <email>",
  876. committer=b"test <email>",
  877. )
  878. finally:
  879. os.chdir(cwd)
  880. index = self.repo.open_index()
  881. # After fix: add() with no paths should behave like git add -A (add everything)
  882. self.assertEqual(sorted(index), [b"blah", b"foo/blie"])
  883. def test_add_file(self) -> None:
  884. fullpath = os.path.join(self.repo.path, "foo")
  885. with open(fullpath, "w") as f:
  886. f.write("BAR")
  887. porcelain.add(self.repo.path, paths=[fullpath])
  888. self.assertIn(b"foo", self.repo.open_index())
  889. def test_add_ignored(self) -> None:
  890. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  891. f.write("foo\nsubdir/")
  892. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  893. f.write("BAR")
  894. with open(os.path.join(self.repo.path, "bar"), "w") as f:
  895. f.write("BAR")
  896. os.mkdir(os.path.join(self.repo.path, "subdir"))
  897. with open(os.path.join(self.repo.path, "subdir", "baz"), "w") as f:
  898. f.write("BAZ")
  899. (added, ignored) = porcelain.add(
  900. self.repo.path,
  901. paths=[
  902. os.path.join(self.repo.path, "foo"),
  903. os.path.join(self.repo.path, "bar"),
  904. os.path.join(self.repo.path, "subdir"),
  905. ],
  906. )
  907. self.assertIn(b"bar", self.repo.open_index())
  908. self.assertEqual({"bar"}, set(added))
  909. self.assertEqual({"foo", "subdir/"}, ignored)
  910. def test_add_file_absolute_path(self) -> None:
  911. # Absolute paths are (not yet) supported
  912. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  913. f.write("BAR")
  914. porcelain.add(self.repo, paths=[os.path.join(self.repo.path, "foo")])
  915. self.assertIn(b"foo", self.repo.open_index())
  916. def test_add_not_in_repo(self) -> None:
  917. with open(os.path.join(self.test_dir, "foo"), "w") as f:
  918. f.write("BAR")
  919. self.assertRaises(
  920. ValueError,
  921. porcelain.add,
  922. self.repo,
  923. paths=[os.path.join(self.test_dir, "foo")],
  924. )
  925. self.assertRaises(
  926. (ValueError, FileNotFoundError),
  927. porcelain.add,
  928. self.repo,
  929. paths=["../foo"],
  930. )
  931. self.assertEqual([], list(self.repo.open_index()))
  932. def test_add_file_clrf_conversion(self) -> None:
  933. # Set the right configuration to the repo
  934. c = self.repo.get_config()
  935. c.set("core", "autocrlf", "input")
  936. c.write_to_path()
  937. # Add a file with CRLF line-ending
  938. fullpath = os.path.join(self.repo.path, "foo")
  939. with open(fullpath, "wb") as f:
  940. f.write(b"line1\r\nline2")
  941. porcelain.add(self.repo.path, paths=[fullpath])
  942. # The line-endings should have been converted to LF
  943. index = self.repo.open_index()
  944. self.assertIn(b"foo", index)
  945. entry = index[b"foo"]
  946. blob = self.repo[entry.sha]
  947. self.assertEqual(blob.data, b"line1\nline2")
  948. def test_add_symlink_outside_repo(self) -> None:
  949. """Test adding a symlink that points outside the repository."""
  950. # Create a symlink pointing outside the repository
  951. symlink_path = os.path.join(self.repo.path, "symlink_to_nowhere")
  952. os.symlink("/nonexistent/path", symlink_path)
  953. # Adding the symlink should succeed (matching Git's behavior)
  954. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  955. # Should successfully add the symlink
  956. self.assertIn("symlink_to_nowhere", added)
  957. self.assertEqual(len(ignored), 0)
  958. # Verify symlink is actually staged
  959. index = self.repo.open_index()
  960. self.assertIn(b"symlink_to_nowhere", index)
  961. def test_add_symlink_to_file_inside_repo(self) -> None:
  962. """Test adding a symlink that points to a file inside the repository."""
  963. # Create a regular file
  964. target_file = os.path.join(self.repo.path, "target.txt")
  965. with open(target_file, "w") as f:
  966. f.write("target content")
  967. # Create a symlink to the file
  968. symlink_path = os.path.join(self.repo.path, "link_to_target")
  969. os.symlink("target.txt", symlink_path)
  970. # Add both the target and the symlink
  971. added, ignored = porcelain.add(
  972. self.repo.path, paths=[target_file, symlink_path]
  973. )
  974. # Both should be added successfully
  975. self.assertIn("target.txt", added)
  976. self.assertIn("link_to_target", added)
  977. self.assertEqual(len(ignored), 0)
  978. # Verify both are in the index
  979. index = self.repo.open_index()
  980. self.assertIn(b"target.txt", index)
  981. self.assertIn(b"link_to_target", index)
  982. def test_add_symlink_to_directory_inside_repo(self) -> None:
  983. """Test adding a symlink that points to a directory inside the repository."""
  984. # Create a directory with some files
  985. target_dir = os.path.join(self.repo.path, "target_dir")
  986. os.mkdir(target_dir)
  987. with open(os.path.join(target_dir, "file1.txt"), "w") as f:
  988. f.write("content1")
  989. with open(os.path.join(target_dir, "file2.txt"), "w") as f:
  990. f.write("content2")
  991. # Create a symlink to the directory
  992. symlink_path = os.path.join(self.repo.path, "link_to_dir")
  993. os.symlink("target_dir", symlink_path)
  994. # Add the symlink
  995. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  996. # When adding a symlink to a directory, it follows the symlink and adds contents
  997. self.assertEqual(len(added), 2)
  998. self.assertIn("link_to_dir/file1.txt", added)
  999. self.assertIn("link_to_dir/file2.txt", added)
  1000. self.assertEqual(len(ignored), 0)
  1001. # Verify files are added through the symlink path
  1002. index = self.repo.open_index()
  1003. self.assertIn(b"link_to_dir/file1.txt", index)
  1004. self.assertIn(b"link_to_dir/file2.txt", index)
  1005. # The original target directory files are not added
  1006. self.assertNotIn(b"target_dir/file1.txt", index)
  1007. self.assertNotIn(b"target_dir/file2.txt", index)
  1008. def test_add_symlink_chain(self) -> None:
  1009. """Test adding a chain of symlinks (symlink to symlink)."""
  1010. # Create a regular file
  1011. target_file = os.path.join(self.repo.path, "original.txt")
  1012. with open(target_file, "w") as f:
  1013. f.write("original content")
  1014. # Create first symlink
  1015. first_link = os.path.join(self.repo.path, "link1")
  1016. os.symlink("original.txt", first_link)
  1017. # Create second symlink pointing to first
  1018. second_link = os.path.join(self.repo.path, "link2")
  1019. os.symlink("link1", second_link)
  1020. # Add all files
  1021. added, ignored = porcelain.add(
  1022. self.repo.path, paths=[target_file, first_link, second_link]
  1023. )
  1024. # All should be added
  1025. self.assertEqual(len(added), 3)
  1026. self.assertIn("original.txt", added)
  1027. self.assertIn("link1", added)
  1028. self.assertIn("link2", added)
  1029. # Verify all are in the index
  1030. index = self.repo.open_index()
  1031. self.assertIn(b"original.txt", index)
  1032. self.assertIn(b"link1", index)
  1033. self.assertIn(b"link2", index)
  1034. def test_add_broken_symlink(self) -> None:
  1035. """Test adding a broken symlink (points to non-existent target)."""
  1036. # Create a symlink to a non-existent file
  1037. broken_link = os.path.join(self.repo.path, "broken_link")
  1038. os.symlink("does_not_exist.txt", broken_link)
  1039. # Add the broken symlink
  1040. added, ignored = porcelain.add(self.repo.path, paths=[broken_link])
  1041. # Should be added successfully (Git tracks the symlink, not its target)
  1042. self.assertIn("broken_link", added)
  1043. self.assertEqual(len(ignored), 0)
  1044. # Verify it's in the index
  1045. index = self.repo.open_index()
  1046. self.assertIn(b"broken_link", index)
  1047. def test_add_symlink_relative_outside_repo(self) -> None:
  1048. """Test adding a symlink that uses '..' to point outside the repository."""
  1049. # Create a file outside the repo
  1050. outside_file = os.path.join(self.test_dir, "outside.txt")
  1051. with open(outside_file, "w") as f:
  1052. f.write("outside content")
  1053. # Create a symlink using relative path to go outside
  1054. symlink_path = os.path.join(self.repo.path, "link_outside")
  1055. os.symlink("../outside.txt", symlink_path)
  1056. # Add the symlink
  1057. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1058. # Should be added successfully
  1059. self.assertIn("link_outside", added)
  1060. self.assertEqual(len(ignored), 0)
  1061. # Verify it's in the index
  1062. index = self.repo.open_index()
  1063. self.assertIn(b"link_outside", index)
  1064. def test_add_symlink_absolute_to_system(self) -> None:
  1065. """Test adding a symlink with absolute path to system directory."""
  1066. # Create a symlink to a system directory
  1067. symlink_path = os.path.join(self.repo.path, "link_to_tmp")
  1068. if os.name == "nt":
  1069. # On Windows, use a system directory like TEMP
  1070. symlink_target = os.environ["TEMP"]
  1071. else:
  1072. # On Unix-like systems, use /tmp
  1073. symlink_target = "/tmp"
  1074. os.symlink(symlink_target, symlink_path)
  1075. # Adding a symlink to a directory outside the repo should raise ValueError
  1076. with self.assertRaises(ValueError) as cm:
  1077. porcelain.add(self.repo.path, paths=[symlink_path])
  1078. # Check that the error indicates the path is outside the repository
  1079. self.assertIn("is not in the subpath of", str(cm.exception))
  1080. def test_add_file_through_symlink(self) -> None:
  1081. """Test adding a file through a symlinked directory."""
  1082. # Create a directory with a file
  1083. real_dir = os.path.join(self.repo.path, "real_dir")
  1084. os.mkdir(real_dir)
  1085. real_file = os.path.join(real_dir, "file.txt")
  1086. with open(real_file, "w") as f:
  1087. f.write("content")
  1088. # Create a symlink to the directory
  1089. link_dir = os.path.join(self.repo.path, "link_dir")
  1090. os.symlink("real_dir", link_dir)
  1091. # Try to add the file through the symlink path
  1092. symlink_file_path = os.path.join(link_dir, "file.txt")
  1093. # This should add the real file, not create a new entry
  1094. added, ignored = porcelain.add(self.repo.path, paths=[symlink_file_path])
  1095. # The real file should be added
  1096. self.assertIn("real_dir/file.txt", added)
  1097. self.assertEqual(len(added), 1)
  1098. # Verify correct path in index
  1099. index = self.repo.open_index()
  1100. self.assertIn(b"real_dir/file.txt", index)
  1101. # Should not create a separate entry for the symlink path
  1102. self.assertNotIn(b"link_dir/file.txt", index)
  1103. def test_add_repo_path(self) -> None:
  1104. """Test adding the repository path itself should add all untracked files."""
  1105. # Create some untracked files
  1106. with open(os.path.join(self.repo.path, "file1.txt"), "w") as f:
  1107. f.write("content1")
  1108. with open(os.path.join(self.repo.path, "file2.txt"), "w") as f:
  1109. f.write("content2")
  1110. # Add the repository path itself
  1111. added, ignored = porcelain.add(self.repo.path, paths=[self.repo.path])
  1112. # Should add all untracked files, not stage './'
  1113. self.assertIn("file1.txt", added)
  1114. self.assertIn("file2.txt", added)
  1115. self.assertNotIn("./", added)
  1116. # Verify files are actually staged
  1117. index = self.repo.open_index()
  1118. self.assertIn(b"file1.txt", index)
  1119. self.assertIn(b"file2.txt", index)
  1120. def test_add_directory_contents(self) -> None:
  1121. """Test adding a directory adds all files within it."""
  1122. # Create a subdirectory with multiple files
  1123. subdir = os.path.join(self.repo.path, "subdir")
  1124. os.mkdir(subdir)
  1125. with open(os.path.join(subdir, "file1.txt"), "w") as f:
  1126. f.write("content1")
  1127. with open(os.path.join(subdir, "file2.txt"), "w") as f:
  1128. f.write("content2")
  1129. with open(os.path.join(subdir, "file3.txt"), "w") as f:
  1130. f.write("content3")
  1131. # Add the directory
  1132. added, ignored = porcelain.add(self.repo.path, paths=["subdir"])
  1133. # Should add all files in the directory
  1134. self.assertEqual(len(added), 3)
  1135. # Normalize paths to use forward slashes for comparison
  1136. added_normalized = [path.replace(os.sep, "/") for path in added]
  1137. self.assertIn("subdir/file1.txt", added_normalized)
  1138. self.assertIn("subdir/file2.txt", added_normalized)
  1139. self.assertIn("subdir/file3.txt", added_normalized)
  1140. # Verify files are actually staged
  1141. index = self.repo.open_index()
  1142. self.assertIn(b"subdir/file1.txt", index)
  1143. self.assertIn(b"subdir/file2.txt", index)
  1144. self.assertIn(b"subdir/file3.txt", index)
  1145. def test_add_nested_directories(self) -> None:
  1146. """Test adding a directory with nested subdirectories."""
  1147. # Create nested directory structure
  1148. dir1 = os.path.join(self.repo.path, "dir1")
  1149. dir2 = os.path.join(dir1, "dir2")
  1150. dir3 = os.path.join(dir2, "dir3")
  1151. os.makedirs(dir3)
  1152. # Add files at each level
  1153. with open(os.path.join(dir1, "file1.txt"), "w") as f:
  1154. f.write("level1")
  1155. with open(os.path.join(dir2, "file2.txt"), "w") as f:
  1156. f.write("level2")
  1157. with open(os.path.join(dir3, "file3.txt"), "w") as f:
  1158. f.write("level3")
  1159. # Add the top-level directory
  1160. added, ignored = porcelain.add(self.repo.path, paths=["dir1"])
  1161. # Should add all files recursively
  1162. self.assertEqual(len(added), 3)
  1163. # Normalize paths to use forward slashes for comparison
  1164. added_normalized = [path.replace(os.sep, "/") for path in added]
  1165. self.assertIn("dir1/file1.txt", added_normalized)
  1166. self.assertIn("dir1/dir2/file2.txt", added_normalized)
  1167. self.assertIn("dir1/dir2/dir3/file3.txt", added_normalized)
  1168. # Verify files are actually staged
  1169. index = self.repo.open_index()
  1170. self.assertIn(b"dir1/file1.txt", index)
  1171. self.assertIn(b"dir1/dir2/file2.txt", index)
  1172. self.assertIn(b"dir1/dir2/dir3/file3.txt", index)
  1173. def test_add_directory_with_tracked_files(self) -> None:
  1174. """Test adding a directory with some files already tracked."""
  1175. # Create a subdirectory with files
  1176. subdir = os.path.join(self.repo.path, "mixed")
  1177. os.mkdir(subdir)
  1178. # Create and commit one file
  1179. tracked_file = os.path.join(subdir, "tracked.txt")
  1180. with open(tracked_file, "w") as f:
  1181. f.write("already tracked")
  1182. porcelain.add(self.repo.path, paths=[tracked_file])
  1183. porcelain.commit(
  1184. repo=self.repo.path,
  1185. message=b"Add tracked file",
  1186. author=b"test <email>",
  1187. committer=b"test <email>",
  1188. )
  1189. # Add more untracked files
  1190. with open(os.path.join(subdir, "untracked1.txt"), "w") as f:
  1191. f.write("new file 1")
  1192. with open(os.path.join(subdir, "untracked2.txt"), "w") as f:
  1193. f.write("new file 2")
  1194. # Add the directory
  1195. added, ignored = porcelain.add(self.repo.path, paths=["mixed"])
  1196. # Should only add the untracked files
  1197. self.assertEqual(len(added), 2)
  1198. # Normalize paths to use forward slashes for comparison
  1199. added_normalized = [path.replace(os.sep, "/") for path in added]
  1200. self.assertIn("mixed/untracked1.txt", added_normalized)
  1201. self.assertIn("mixed/untracked2.txt", added_normalized)
  1202. self.assertNotIn("mixed/tracked.txt", added)
  1203. # Verify the index contains all files
  1204. index = self.repo.open_index()
  1205. self.assertIn(b"mixed/tracked.txt", index)
  1206. self.assertIn(b"mixed/untracked1.txt", index)
  1207. self.assertIn(b"mixed/untracked2.txt", index)
  1208. def test_add_directory_with_gitignore(self) -> None:
  1209. """Test adding a directory respects .gitignore patterns."""
  1210. # Create .gitignore
  1211. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1212. f.write("*.log\n*.tmp\nbuild/\n")
  1213. # Create directory with mixed files
  1214. testdir = os.path.join(self.repo.path, "testdir")
  1215. os.mkdir(testdir)
  1216. # Create various files
  1217. with open(os.path.join(testdir, "important.txt"), "w") as f:
  1218. f.write("keep this")
  1219. with open(os.path.join(testdir, "debug.log"), "w") as f:
  1220. f.write("ignore this")
  1221. with open(os.path.join(testdir, "temp.tmp"), "w") as f:
  1222. f.write("ignore this too")
  1223. with open(os.path.join(testdir, "readme.md"), "w") as f:
  1224. f.write("keep this too")
  1225. # Create a build directory that should be ignored
  1226. builddir = os.path.join(testdir, "build")
  1227. os.mkdir(builddir)
  1228. with open(os.path.join(builddir, "output.txt"), "w") as f:
  1229. f.write("ignore entire directory")
  1230. # Add the directory
  1231. added, ignored = porcelain.add(self.repo.path, paths=["testdir"])
  1232. # Should only add non-ignored files
  1233. # Normalize paths to use forward slashes for comparison
  1234. added_normalized = {path.replace(os.sep, "/") for path in added}
  1235. self.assertEqual(
  1236. added_normalized, {"testdir/important.txt", "testdir/readme.md"}
  1237. )
  1238. # Check ignored files
  1239. # Normalize paths to use forward slashes for comparison
  1240. ignored_normalized = {path.replace(os.sep, "/") for path in ignored}
  1241. self.assertIn("testdir/debug.log", ignored_normalized)
  1242. self.assertIn("testdir/temp.tmp", ignored_normalized)
  1243. self.assertIn("testdir/build/", ignored_normalized)
  1244. def test_add_multiple_directories(self) -> None:
  1245. """Test adding multiple directories in one call."""
  1246. # Create multiple directories
  1247. for dirname in ["dir1", "dir2", "dir3"]:
  1248. dirpath = os.path.join(self.repo.path, dirname)
  1249. os.mkdir(dirpath)
  1250. # Add files to each directory
  1251. for i in range(2):
  1252. with open(os.path.join(dirpath, f"file{i}.txt"), "w") as f:
  1253. f.write(f"content {dirname} {i}")
  1254. # Add all directories at once
  1255. added, ignored = porcelain.add(self.repo.path, paths=["dir1", "dir2", "dir3"])
  1256. # Should add all files from all directories
  1257. self.assertEqual(len(added), 6)
  1258. # Normalize paths to use forward slashes for comparison
  1259. added_normalized = [path.replace(os.sep, "/") for path in added]
  1260. for dirname in ["dir1", "dir2", "dir3"]:
  1261. for i in range(2):
  1262. self.assertIn(f"{dirname}/file{i}.txt", added_normalized)
  1263. # Verify all files are staged
  1264. index = self.repo.open_index()
  1265. self.assertEqual(len(index), 6)
  1266. def test_add_default_paths_includes_modified_files(self) -> None:
  1267. """Test that add() with no paths includes both untracked and modified files."""
  1268. # Create and commit initial file
  1269. initial_file = os.path.join(self.repo.path, "existing.txt")
  1270. with open(initial_file, "w") as f:
  1271. f.write("initial content\n")
  1272. porcelain.add(repo=self.repo.path, paths=[initial_file])
  1273. porcelain.commit(
  1274. repo=self.repo.path,
  1275. message=b"initial commit",
  1276. author=b"test <email>",
  1277. committer=b"test <email>",
  1278. )
  1279. # Modify the existing file (this creates an unstaged change)
  1280. with open(initial_file, "w") as f:
  1281. f.write("modified content\n")
  1282. # Create a new untracked file
  1283. new_file = os.path.join(self.repo.path, "new.txt")
  1284. with open(new_file, "w") as f:
  1285. f.write("new file content\n")
  1286. # Call add() with no paths - should stage both modified and untracked files
  1287. added_files, ignored_files = porcelain.add(repo=self.repo.path)
  1288. # Verify both files were added
  1289. self.assertIn("existing.txt", added_files)
  1290. self.assertIn("new.txt", added_files)
  1291. self.assertEqual(len(ignored_files), 0)
  1292. # Verify both files are now staged
  1293. index = self.repo.open_index()
  1294. self.assertIn(b"existing.txt", index)
  1295. self.assertIn(b"new.txt", index)
  1296. class RemoveTests(PorcelainTestCase):
  1297. def test_remove_file(self) -> None:
  1298. fullpath = os.path.join(self.repo.path, "foo")
  1299. with open(fullpath, "w") as f:
  1300. f.write("BAR")
  1301. porcelain.add(self.repo.path, paths=[fullpath])
  1302. porcelain.commit(
  1303. repo=self.repo,
  1304. message=b"test",
  1305. author=b"test <email>",
  1306. committer=b"test <email>",
  1307. )
  1308. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "foo")))
  1309. cwd = os.getcwd()
  1310. try:
  1311. os.chdir(self.repo.path)
  1312. porcelain.remove(self.repo.path, paths=["foo"])
  1313. finally:
  1314. os.chdir(cwd)
  1315. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1316. def test_remove_file_staged(self) -> None:
  1317. fullpath = os.path.join(self.repo.path, "foo")
  1318. with open(fullpath, "w") as f:
  1319. f.write("BAR")
  1320. cwd = os.getcwd()
  1321. try:
  1322. os.chdir(self.repo.path)
  1323. porcelain.add(self.repo.path, paths=[fullpath])
  1324. self.assertRaises(Exception, porcelain.rm, self.repo.path, paths=["foo"])
  1325. finally:
  1326. os.chdir(cwd)
  1327. def test_remove_file_removed_on_disk(self) -> None:
  1328. fullpath = os.path.join(self.repo.path, "foo")
  1329. with open(fullpath, "w") as f:
  1330. f.write("BAR")
  1331. porcelain.add(self.repo.path, paths=[fullpath])
  1332. cwd = os.getcwd()
  1333. try:
  1334. os.chdir(self.repo.path)
  1335. os.remove(fullpath)
  1336. porcelain.remove(self.repo.path, paths=["foo"])
  1337. finally:
  1338. os.chdir(cwd)
  1339. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1340. def test_remove_from_different_directory(self) -> None:
  1341. # Create a subdirectory with a file
  1342. subdir = os.path.join(self.repo.path, "mydir")
  1343. os.makedirs(subdir)
  1344. fullpath = os.path.join(subdir, "myfile")
  1345. with open(fullpath, "w") as f:
  1346. f.write("BAR")
  1347. # Add and commit the file
  1348. porcelain.add(self.repo.path, paths=[fullpath])
  1349. porcelain.commit(
  1350. repo=self.repo,
  1351. message=b"test",
  1352. author=b"test <email>",
  1353. committer=b"test <email>",
  1354. )
  1355. # Change to a different directory
  1356. cwd = os.getcwd()
  1357. tempdir = tempfile.mkdtemp()
  1358. try:
  1359. os.chdir(tempdir)
  1360. # Remove the file using relative path from repository root
  1361. porcelain.remove(self.repo.path, paths=["mydir/myfile"])
  1362. finally:
  1363. os.chdir(cwd)
  1364. os.rmdir(tempdir)
  1365. # Verify file was removed
  1366. self.assertFalse(os.path.exists(fullpath))
  1367. def test_remove_with_absolute_path(self) -> None:
  1368. # Create a file
  1369. fullpath = os.path.join(self.repo.path, "foo")
  1370. with open(fullpath, "w") as f:
  1371. f.write("BAR")
  1372. # Add and commit the file
  1373. porcelain.add(self.repo.path, paths=[fullpath])
  1374. porcelain.commit(
  1375. repo=self.repo,
  1376. message=b"test",
  1377. author=b"test <email>",
  1378. committer=b"test <email>",
  1379. )
  1380. # Change to a different directory
  1381. cwd = os.getcwd()
  1382. tempdir = tempfile.mkdtemp()
  1383. try:
  1384. os.chdir(tempdir)
  1385. # Remove the file using absolute path
  1386. porcelain.remove(self.repo.path, paths=[fullpath])
  1387. finally:
  1388. os.chdir(cwd)
  1389. os.rmdir(tempdir)
  1390. # Verify file was removed
  1391. self.assertFalse(os.path.exists(fullpath))
  1392. class MvTests(PorcelainTestCase):
  1393. def test_mv_file(self) -> None:
  1394. # Create a file
  1395. fullpath = os.path.join(self.repo.path, "foo")
  1396. with open(fullpath, "w") as f:
  1397. f.write("BAR")
  1398. # Add and commit the file
  1399. porcelain.add(self.repo.path, paths=[fullpath])
  1400. porcelain.commit(
  1401. repo=self.repo,
  1402. message=b"test",
  1403. author=b"test <email>",
  1404. committer=b"test <email>",
  1405. )
  1406. # Move the file
  1407. porcelain.mv(self.repo.path, "foo", "bar")
  1408. # Verify old path doesn't exist and new path does
  1409. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1410. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "bar")))
  1411. # Verify index was updated
  1412. index = self.repo.open_index()
  1413. self.assertNotIn(b"foo", index)
  1414. self.assertIn(b"bar", index)
  1415. def test_mv_file_to_existing_directory(self) -> None:
  1416. # Create a file and a directory
  1417. fullpath = os.path.join(self.repo.path, "foo")
  1418. with open(fullpath, "w") as f:
  1419. f.write("BAR")
  1420. dirpath = os.path.join(self.repo.path, "mydir")
  1421. os.makedirs(dirpath)
  1422. # Add and commit the file
  1423. porcelain.add(self.repo.path, paths=[fullpath])
  1424. porcelain.commit(
  1425. repo=self.repo,
  1426. message=b"test",
  1427. author=b"test <email>",
  1428. committer=b"test <email>",
  1429. )
  1430. # Move the file into the directory
  1431. porcelain.mv(self.repo.path, "foo", "mydir")
  1432. # Verify file moved into directory
  1433. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1434. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "mydir", "foo")))
  1435. # Verify index was updated
  1436. index = self.repo.open_index()
  1437. self.assertNotIn(b"foo", index)
  1438. self.assertIn(b"mydir/foo", index)
  1439. def test_mv_file_force_overwrite(self) -> None:
  1440. # Create two files
  1441. fullpath1 = os.path.join(self.repo.path, "foo")
  1442. with open(fullpath1, "w") as f:
  1443. f.write("FOO")
  1444. fullpath2 = os.path.join(self.repo.path, "bar")
  1445. with open(fullpath2, "w") as f:
  1446. f.write("BAR")
  1447. # Add and commit both files
  1448. porcelain.add(self.repo.path, paths=[fullpath1, fullpath2])
  1449. porcelain.commit(
  1450. repo=self.repo,
  1451. message=b"test",
  1452. author=b"test <email>",
  1453. committer=b"test <email>",
  1454. )
  1455. # Try to move without force (should fail)
  1456. self.assertRaises(porcelain.Error, porcelain.mv, self.repo.path, "foo", "bar")
  1457. # Move with force
  1458. porcelain.mv(self.repo.path, "foo", "bar", force=True)
  1459. # Verify foo doesn't exist and bar has foo's content
  1460. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1461. with open(os.path.join(self.repo.path, "bar")) as f:
  1462. self.assertEqual(f.read(), "FOO")
  1463. def test_mv_file_not_tracked(self) -> None:
  1464. # Create an untracked file
  1465. fullpath = os.path.join(self.repo.path, "untracked")
  1466. with open(fullpath, "w") as f:
  1467. f.write("UNTRACKED")
  1468. # Try to move it (should fail)
  1469. self.assertRaises(
  1470. porcelain.Error, porcelain.mv, self.repo.path, "untracked", "tracked"
  1471. )
  1472. def test_mv_file_not_exists(self) -> None:
  1473. # Try to move a non-existent file
  1474. self.assertRaises(
  1475. porcelain.Error, porcelain.mv, self.repo.path, "nonexistent", "destination"
  1476. )
  1477. def test_mv_absolute_paths(self) -> None:
  1478. # Create a file
  1479. fullpath = os.path.join(self.repo.path, "foo")
  1480. with open(fullpath, "w") as f:
  1481. f.write("BAR")
  1482. # Add and commit the file
  1483. porcelain.add(self.repo.path, paths=[fullpath])
  1484. porcelain.commit(
  1485. repo=self.repo,
  1486. message=b"test",
  1487. author=b"test <email>",
  1488. committer=b"test <email>",
  1489. )
  1490. # Move using absolute paths
  1491. dest_path = os.path.join(self.repo.path, "bar")
  1492. porcelain.mv(self.repo.path, fullpath, dest_path)
  1493. # Verify file moved
  1494. self.assertFalse(os.path.exists(fullpath))
  1495. self.assertTrue(os.path.exists(dest_path))
  1496. def test_mv_from_different_directory(self) -> None:
  1497. # Create a subdirectory with a file
  1498. subdir = os.path.join(self.repo.path, "mydir")
  1499. os.makedirs(subdir)
  1500. fullpath = os.path.join(subdir, "myfile")
  1501. with open(fullpath, "w") as f:
  1502. f.write("BAR")
  1503. # Add and commit the file
  1504. porcelain.add(self.repo.path, paths=[fullpath])
  1505. porcelain.commit(
  1506. repo=self.repo,
  1507. message=b"test",
  1508. author=b"test <email>",
  1509. committer=b"test <email>",
  1510. )
  1511. # Change to a different directory and move the file
  1512. cwd = os.getcwd()
  1513. tempdir = tempfile.mkdtemp()
  1514. try:
  1515. os.chdir(tempdir)
  1516. # Move the file using relative path from repository root
  1517. porcelain.mv(self.repo.path, "mydir/myfile", "renamed")
  1518. finally:
  1519. os.chdir(cwd)
  1520. os.rmdir(tempdir)
  1521. # Verify file was moved
  1522. self.assertFalse(os.path.exists(fullpath))
  1523. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "renamed")))
  1524. class LogTests(PorcelainTestCase):
  1525. def test_simple(self) -> None:
  1526. c1, c2, c3 = build_commit_graph(
  1527. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1528. )
  1529. self.repo.refs[b"HEAD"] = c3.id
  1530. self.maxDiff = None
  1531. outstream = StringIO()
  1532. porcelain.log(self.repo.path, outstream=outstream)
  1533. self.assertEqual(
  1534. outstream.getvalue(),
  1535. """\
  1536. --------------------------------------------------
  1537. commit: 4a3b887baa9ecb2d054d2469b628aef84e2d74f0
  1538. merge: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  1539. Author: Test Author <test@nodomain.com>
  1540. Committer: Test Committer <test@nodomain.com>
  1541. Date: Fri Jan 01 2010 00:00:00 +0000
  1542. Commit 3
  1543. --------------------------------------------------
  1544. commit: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  1545. Author: Test Author <test@nodomain.com>
  1546. Committer: Test Committer <test@nodomain.com>
  1547. Date: Fri Jan 01 2010 00:00:00 +0000
  1548. Commit 2
  1549. --------------------------------------------------
  1550. commit: 11d3cf672a19366435c1983c7340b008ec6b8bf3
  1551. Author: Test Author <test@nodomain.com>
  1552. Committer: Test Committer <test@nodomain.com>
  1553. Date: Fri Jan 01 2010 00:00:00 +0000
  1554. Commit 1
  1555. """,
  1556. )
  1557. def test_max_entries(self) -> None:
  1558. c1, c2, c3 = build_commit_graph(
  1559. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1560. )
  1561. self.repo.refs[b"HEAD"] = c3.id
  1562. outstream = StringIO()
  1563. porcelain.log(self.repo.path, outstream=outstream, max_entries=1)
  1564. self.assertEqual(1, outstream.getvalue().count("-" * 50))
  1565. def test_no_revisions(self) -> None:
  1566. outstream = StringIO()
  1567. porcelain.log(self.repo.path, outstream=outstream)
  1568. self.assertEqual("", outstream.getvalue())
  1569. def test_empty_message(self) -> None:
  1570. c1 = make_commit(message="")
  1571. self.repo.object_store.add_object(c1)
  1572. self.repo.refs[b"HEAD"] = c1.id
  1573. outstream = StringIO()
  1574. porcelain.log(self.repo.path, outstream=outstream)
  1575. self.assertEqual(
  1576. outstream.getvalue(),
  1577. """\
  1578. --------------------------------------------------
  1579. commit: 4a7ad5552fad70647a81fb9a4a923ccefcca4b76
  1580. Author: Test Author <test@nodomain.com>
  1581. Committer: Test Committer <test@nodomain.com>
  1582. Date: Fri Jan 01 2010 00:00:00 +0000
  1583. """,
  1584. )
  1585. class ShowTests(PorcelainTestCase):
  1586. def test_nolist(self) -> None:
  1587. c1, c2, c3 = build_commit_graph(
  1588. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1589. )
  1590. self.repo.refs[b"HEAD"] = c3.id
  1591. outstream = StringIO()
  1592. porcelain.show(self.repo.path, objects=c3.id, outstream=outstream)
  1593. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  1594. def test_simple(self) -> None:
  1595. c1, c2, c3 = build_commit_graph(
  1596. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1597. )
  1598. self.repo.refs[b"HEAD"] = c3.id
  1599. outstream = StringIO()
  1600. porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream)
  1601. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  1602. def test_blob(self) -> None:
  1603. b = Blob.from_string(b"The Foo\n")
  1604. self.repo.object_store.add_object(b)
  1605. outstream = StringIO()
  1606. porcelain.show(self.repo.path, objects=[b.id], outstream=outstream)
  1607. self.assertEqual(outstream.getvalue(), "The Foo\n")
  1608. def test_commit_no_parent(self) -> None:
  1609. a = Blob.from_string(b"The Foo\n")
  1610. ta = Tree()
  1611. ta.add(b"somename", 0o100644, a.id)
  1612. ca = make_commit(tree=ta.id)
  1613. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  1614. outstream = StringIO()
  1615. porcelain.show(self.repo.path, objects=[ca.id], outstream=outstream)
  1616. self.assertMultiLineEqual(
  1617. outstream.getvalue(),
  1618. """\
  1619. --------------------------------------------------
  1620. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  1621. Author: Test Author <test@nodomain.com>
  1622. Committer: Test Committer <test@nodomain.com>
  1623. Date: Fri Jan 01 2010 00:00:00 +0000
  1624. Test message.
  1625. diff --git a/somename b/somename
  1626. new file mode 100644
  1627. index 0000000..ea5c7bf
  1628. --- /dev/null
  1629. +++ b/somename
  1630. @@ -0,0 +1 @@
  1631. +The Foo
  1632. """,
  1633. )
  1634. def test_tag(self) -> None:
  1635. a = Blob.from_string(b"The Foo\n")
  1636. ta = Tree()
  1637. ta.add(b"somename", 0o100644, a.id)
  1638. ca = make_commit(tree=ta.id)
  1639. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  1640. porcelain.tag_create(
  1641. self.repo.path,
  1642. b"tryme",
  1643. b"foo <foo@bar.com>",
  1644. b"bar",
  1645. annotated=True,
  1646. objectish=ca.id,
  1647. tag_time=1552854211,
  1648. tag_timezone=0,
  1649. )
  1650. outstream = StringIO()
  1651. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  1652. self.maxDiff = None
  1653. self.assertMultiLineEqual(
  1654. outstream.getvalue(),
  1655. """\
  1656. Tagger: foo <foo@bar.com>
  1657. Date: Sun Mar 17 2019 20:23:31 +0000
  1658. bar
  1659. --------------------------------------------------
  1660. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  1661. Author: Test Author <test@nodomain.com>
  1662. Committer: Test Committer <test@nodomain.com>
  1663. Date: Fri Jan 01 2010 00:00:00 +0000
  1664. Test message.
  1665. diff --git a/somename b/somename
  1666. new file mode 100644
  1667. index 0000000..ea5c7bf
  1668. --- /dev/null
  1669. +++ b/somename
  1670. @@ -0,0 +1 @@
  1671. +The Foo
  1672. """,
  1673. )
  1674. def test_tag_unicode(self) -> None:
  1675. a = Blob.from_string(b"The Foo\n")
  1676. ta = Tree()
  1677. ta.add(b"somename", 0o100644, a.id)
  1678. ca = make_commit(tree=ta.id)
  1679. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  1680. porcelain.tag_create(
  1681. self.repo.path,
  1682. "tryme",
  1683. "foo <foo@bar.com>",
  1684. "bar",
  1685. annotated=True,
  1686. objectish=ca.id,
  1687. tag_time=1552854211,
  1688. tag_timezone=0,
  1689. )
  1690. outstream = StringIO()
  1691. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  1692. self.maxDiff = None
  1693. self.assertMultiLineEqual(
  1694. outstream.getvalue(),
  1695. """\
  1696. Tagger: foo <foo@bar.com>
  1697. Date: Sun Mar 17 2019 20:23:31 +0000
  1698. bar
  1699. --------------------------------------------------
  1700. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  1701. Author: Test Author <test@nodomain.com>
  1702. Committer: Test Committer <test@nodomain.com>
  1703. Date: Fri Jan 01 2010 00:00:00 +0000
  1704. Test message.
  1705. diff --git a/somename b/somename
  1706. new file mode 100644
  1707. index 0000000..ea5c7bf
  1708. --- /dev/null
  1709. +++ b/somename
  1710. @@ -0,0 +1 @@
  1711. +The Foo
  1712. """,
  1713. )
  1714. def test_commit_with_change(self) -> None:
  1715. a = Blob.from_string(b"The Foo\n")
  1716. ta = Tree()
  1717. ta.add(b"somename", 0o100644, a.id)
  1718. ca = make_commit(tree=ta.id)
  1719. b = Blob.from_string(b"The Bar\n")
  1720. tb = Tree()
  1721. tb.add(b"somename", 0o100644, b.id)
  1722. cb = make_commit(tree=tb.id, parents=[ca.id])
  1723. self.repo.object_store.add_objects(
  1724. [
  1725. (a, None),
  1726. (b, None),
  1727. (ta, None),
  1728. (tb, None),
  1729. (ca, None),
  1730. (cb, None),
  1731. ]
  1732. )
  1733. outstream = StringIO()
  1734. porcelain.show(self.repo.path, objects=[cb.id], outstream=outstream)
  1735. self.assertMultiLineEqual(
  1736. outstream.getvalue(),
  1737. """\
  1738. --------------------------------------------------
  1739. commit: 2c6b6c9cb72c130956657e1fdae58e5b103744fa
  1740. Author: Test Author <test@nodomain.com>
  1741. Committer: Test Committer <test@nodomain.com>
  1742. Date: Fri Jan 01 2010 00:00:00 +0000
  1743. Test message.
  1744. diff --git a/somename b/somename
  1745. index ea5c7bf..fd38bcb 100644
  1746. --- a/somename
  1747. +++ b/somename
  1748. @@ -1 +1 @@
  1749. -The Foo
  1750. +The Bar
  1751. """,
  1752. )
  1753. class SymbolicRefTests(PorcelainTestCase):
  1754. def test_set_wrong_symbolic_ref(self) -> None:
  1755. c1, c2, c3 = build_commit_graph(
  1756. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1757. )
  1758. self.repo.refs[b"HEAD"] = c3.id
  1759. self.assertRaises(
  1760. porcelain.Error, porcelain.symbolic_ref, self.repo.path, b"foobar"
  1761. )
  1762. def test_set_force_wrong_symbolic_ref(self) -> None:
  1763. c1, c2, c3 = build_commit_graph(
  1764. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1765. )
  1766. self.repo.refs[b"HEAD"] = c3.id
  1767. porcelain.symbolic_ref(self.repo.path, b"force_foobar", force=True)
  1768. # test if we actually changed the file
  1769. with self.repo.get_named_file("HEAD") as f:
  1770. new_ref = f.read()
  1771. self.assertEqual(new_ref, b"ref: refs/heads/force_foobar\n")
  1772. def test_set_symbolic_ref(self) -> None:
  1773. c1, c2, c3 = build_commit_graph(
  1774. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1775. )
  1776. self.repo.refs[b"HEAD"] = c3.id
  1777. porcelain.symbolic_ref(self.repo.path, b"master")
  1778. def test_set_symbolic_ref_other_than_master(self) -> None:
  1779. c1, c2, c3 = build_commit_graph(
  1780. self.repo.object_store,
  1781. [[1], [2, 1], [3, 1, 2]],
  1782. attrs=dict(refs="develop"),
  1783. )
  1784. self.repo.refs[b"HEAD"] = c3.id
  1785. self.repo.refs[b"refs/heads/develop"] = c3.id
  1786. porcelain.symbolic_ref(self.repo.path, b"develop")
  1787. # test if we actually changed the file
  1788. with self.repo.get_named_file("HEAD") as f:
  1789. new_ref = f.read()
  1790. self.assertEqual(new_ref, b"ref: refs/heads/develop\n")
  1791. class DiffTreeTests(PorcelainTestCase):
  1792. def test_empty(self) -> None:
  1793. c1, c2, c3 = build_commit_graph(
  1794. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1795. )
  1796. self.repo.refs[b"HEAD"] = c3.id
  1797. outstream = BytesIO()
  1798. porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream)
  1799. self.assertEqual(outstream.getvalue(), b"")
  1800. class CommitTreeTests(PorcelainTestCase):
  1801. def test_simple(self) -> None:
  1802. c1, c2, c3 = build_commit_graph(
  1803. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1804. )
  1805. b = Blob()
  1806. b.data = b"foo the bar"
  1807. t = Tree()
  1808. t.add(b"somename", 0o100644, b.id)
  1809. self.repo.object_store.add_object(t)
  1810. self.repo.object_store.add_object(b)
  1811. sha = porcelain.commit_tree(
  1812. self.repo.path,
  1813. t.id,
  1814. message=b"Withcommit.",
  1815. author=b"Joe <joe@example.com>",
  1816. committer=b"Jane <jane@example.com>",
  1817. )
  1818. self.assertIsInstance(sha, bytes)
  1819. self.assertEqual(len(sha), 40)
  1820. class RevListTests(PorcelainTestCase):
  1821. def test_simple(self) -> None:
  1822. c1, c2, c3 = build_commit_graph(
  1823. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1824. )
  1825. outstream = BytesIO()
  1826. porcelain.rev_list(self.repo.path, [c3.id], outstream=outstream)
  1827. self.assertEqual(
  1828. c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue()
  1829. )
  1830. @skipIf(
  1831. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  1832. "gpgme not easily available or supported on Windows and PyPy",
  1833. )
  1834. class TagCreateSignTests(PorcelainGpgTestCase):
  1835. def test_default_key(self) -> None:
  1836. c1, c2, c3 = build_commit_graph(
  1837. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1838. )
  1839. self.repo.refs[b"HEAD"] = c3.id
  1840. cfg = self.repo.get_config()
  1841. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  1842. self.import_default_key()
  1843. porcelain.tag_create(
  1844. self.repo.path,
  1845. b"tryme",
  1846. b"foo <foo@bar.com>",
  1847. b"bar",
  1848. annotated=True,
  1849. sign=True,
  1850. )
  1851. tags = self.repo.refs.as_dict(b"refs/tags")
  1852. self.assertEqual(list(tags.keys()), [b"tryme"])
  1853. tag = self.repo[b"refs/tags/tryme"]
  1854. self.assertIsInstance(tag, Tag)
  1855. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  1856. self.assertEqual(b"bar\n", tag.message)
  1857. self.assertRecentTimestamp(tag.tag_time)
  1858. tag = self.repo[b"refs/tags/tryme"]
  1859. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  1860. tag.verify()
  1861. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  1862. self.import_non_default_key()
  1863. self.assertRaises(
  1864. gpg.errors.MissingSignatures,
  1865. tag.verify,
  1866. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  1867. )
  1868. tag._chunked_text = [b"bad data", tag._signature]
  1869. self.assertRaises(
  1870. gpg.errors.BadSignatures,
  1871. tag.verify,
  1872. )
  1873. def test_non_default_key(self) -> None:
  1874. c1, c2, c3 = build_commit_graph(
  1875. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1876. )
  1877. self.repo.refs[b"HEAD"] = c3.id
  1878. cfg = self.repo.get_config()
  1879. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  1880. self.import_non_default_key()
  1881. porcelain.tag_create(
  1882. self.repo.path,
  1883. b"tryme",
  1884. b"foo <foo@bar.com>",
  1885. b"bar",
  1886. annotated=True,
  1887. sign=PorcelainGpgTestCase.NON_DEFAULT_KEY_ID,
  1888. )
  1889. tags = self.repo.refs.as_dict(b"refs/tags")
  1890. self.assertEqual(list(tags.keys()), [b"tryme"])
  1891. tag = self.repo[b"refs/tags/tryme"]
  1892. self.assertIsInstance(tag, Tag)
  1893. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  1894. self.assertEqual(b"bar\n", tag.message)
  1895. self.assertRecentTimestamp(tag.tag_time)
  1896. tag = self.repo[b"refs/tags/tryme"]
  1897. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  1898. tag.verify()
  1899. class TagCreateTests(PorcelainTestCase):
  1900. def test_annotated(self) -> None:
  1901. c1, c2, c3 = build_commit_graph(
  1902. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1903. )
  1904. self.repo.refs[b"HEAD"] = c3.id
  1905. porcelain.tag_create(
  1906. self.repo.path,
  1907. b"tryme",
  1908. b"foo <foo@bar.com>",
  1909. b"bar",
  1910. annotated=True,
  1911. )
  1912. tags = self.repo.refs.as_dict(b"refs/tags")
  1913. self.assertEqual(list(tags.keys()), [b"tryme"])
  1914. tag = self.repo[b"refs/tags/tryme"]
  1915. self.assertIsInstance(tag, Tag)
  1916. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  1917. self.assertEqual(b"bar\n", tag.message)
  1918. self.assertRecentTimestamp(tag.tag_time)
  1919. def test_unannotated(self) -> None:
  1920. c1, c2, c3 = build_commit_graph(
  1921. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1922. )
  1923. self.repo.refs[b"HEAD"] = c3.id
  1924. porcelain.tag_create(self.repo.path, b"tryme", annotated=False)
  1925. tags = self.repo.refs.as_dict(b"refs/tags")
  1926. self.assertEqual(list(tags.keys()), [b"tryme"])
  1927. self.repo[b"refs/tags/tryme"]
  1928. self.assertEqual(list(tags.values()), [self.repo.head()])
  1929. def test_unannotated_unicode(self) -> None:
  1930. c1, c2, c3 = build_commit_graph(
  1931. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1932. )
  1933. self.repo.refs[b"HEAD"] = c3.id
  1934. porcelain.tag_create(self.repo.path, "tryme", annotated=False)
  1935. tags = self.repo.refs.as_dict(b"refs/tags")
  1936. self.assertEqual(list(tags.keys()), [b"tryme"])
  1937. self.repo[b"refs/tags/tryme"]
  1938. self.assertEqual(list(tags.values()), [self.repo.head()])
  1939. class TagListTests(PorcelainTestCase):
  1940. def test_empty(self) -> None:
  1941. tags = porcelain.tag_list(self.repo.path)
  1942. self.assertEqual([], tags)
  1943. def test_simple(self) -> None:
  1944. self.repo.refs[b"refs/tags/foo"] = b"aa" * 20
  1945. self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20
  1946. tags = porcelain.tag_list(self.repo.path)
  1947. self.assertEqual([b"bar/bla", b"foo"], tags)
  1948. class TagDeleteTests(PorcelainTestCase):
  1949. def test_simple(self) -> None:
  1950. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  1951. self.repo[b"HEAD"] = c1.id
  1952. porcelain.tag_create(self.repo, b"foo")
  1953. self.assertIn(b"foo", porcelain.tag_list(self.repo))
  1954. porcelain.tag_delete(self.repo, b"foo")
  1955. self.assertNotIn(b"foo", porcelain.tag_list(self.repo))
  1956. class ResetTests(PorcelainTestCase):
  1957. def test_hard_head(self) -> None:
  1958. fullpath = os.path.join(self.repo.path, "foo")
  1959. with open(fullpath, "w") as f:
  1960. f.write("BAR")
  1961. porcelain.add(self.repo.path, paths=[fullpath])
  1962. porcelain.commit(
  1963. self.repo.path,
  1964. message=b"Some message",
  1965. committer=b"Jane <jane@example.com>",
  1966. author=b"John <john@example.com>",
  1967. )
  1968. with open(os.path.join(self.repo.path, "foo"), "wb") as f:
  1969. f.write(b"OOH")
  1970. porcelain.reset(self.repo, "hard", b"HEAD")
  1971. index = self.repo.open_index()
  1972. changes = list(
  1973. tree_changes(
  1974. self.repo,
  1975. index.commit(self.repo.object_store),
  1976. self.repo[b"HEAD"].tree,
  1977. )
  1978. )
  1979. self.assertEqual([], changes)
  1980. def test_hard_commit(self) -> None:
  1981. fullpath = os.path.join(self.repo.path, "foo")
  1982. with open(fullpath, "w") as f:
  1983. f.write("BAR")
  1984. porcelain.add(self.repo.path, paths=[fullpath])
  1985. sha = porcelain.commit(
  1986. self.repo.path,
  1987. message=b"Some message",
  1988. committer=b"Jane <jane@example.com>",
  1989. author=b"John <john@example.com>",
  1990. )
  1991. with open(fullpath, "wb") as f:
  1992. f.write(b"BAZ")
  1993. porcelain.add(self.repo.path, paths=[fullpath])
  1994. porcelain.commit(
  1995. self.repo.path,
  1996. message=b"Some other message",
  1997. committer=b"Jane <jane@example.com>",
  1998. author=b"John <john@example.com>",
  1999. )
  2000. porcelain.reset(self.repo, "hard", sha)
  2001. index = self.repo.open_index()
  2002. changes = list(
  2003. tree_changes(
  2004. self.repo,
  2005. index.commit(self.repo.object_store),
  2006. self.repo[sha].tree,
  2007. )
  2008. )
  2009. self.assertEqual([], changes)
  2010. def test_hard_commit_short_hash(self) -> None:
  2011. fullpath = os.path.join(self.repo.path, "foo")
  2012. with open(fullpath, "w") as f:
  2013. f.write("BAR")
  2014. porcelain.add(self.repo.path, paths=[fullpath])
  2015. sha = porcelain.commit(
  2016. self.repo.path,
  2017. message=b"Some message",
  2018. committer=b"Jane <jane@example.com>",
  2019. author=b"John <john@example.com>",
  2020. )
  2021. with open(fullpath, "wb") as f:
  2022. f.write(b"BAZ")
  2023. porcelain.add(self.repo.path, paths=[fullpath])
  2024. porcelain.commit(
  2025. self.repo.path,
  2026. message=b"Some other message",
  2027. committer=b"Jane <jane@example.com>",
  2028. author=b"John <john@example.com>",
  2029. )
  2030. # Test with short hash (7 characters)
  2031. short_sha = sha[:7].decode("ascii")
  2032. porcelain.reset(self.repo, "hard", short_sha)
  2033. index = self.repo.open_index()
  2034. changes = list(
  2035. tree_changes(
  2036. self.repo,
  2037. index.commit(self.repo.object_store),
  2038. self.repo[sha].tree,
  2039. )
  2040. )
  2041. self.assertEqual([], changes)
  2042. def test_hard_deletes_untracked_files(self) -> None:
  2043. """Test that reset --hard deletes files that don't exist in target tree."""
  2044. # Create and commit a file
  2045. fullpath = os.path.join(self.repo.path, "foo")
  2046. with open(fullpath, "w") as f:
  2047. f.write("BAR")
  2048. porcelain.add(self.repo.path, paths=[fullpath])
  2049. sha1 = porcelain.commit(
  2050. self.repo.path,
  2051. message=b"First commit",
  2052. committer=b"Jane <jane@example.com>",
  2053. author=b"John <john@example.com>",
  2054. )
  2055. # Create another file and commit
  2056. fullpath2 = os.path.join(self.repo.path, "bar")
  2057. with open(fullpath2, "w") as f:
  2058. f.write("BAZ")
  2059. porcelain.add(self.repo.path, paths=[fullpath2])
  2060. porcelain.commit(
  2061. self.repo.path,
  2062. message=b"Second commit",
  2063. committer=b"Jane <jane@example.com>",
  2064. author=b"John <john@example.com>",
  2065. )
  2066. # Reset hard to first commit - this should delete 'bar'
  2067. porcelain.reset(self.repo, "hard", sha1)
  2068. # Check that 'foo' still exists and 'bar' is deleted
  2069. self.assertTrue(os.path.exists(fullpath))
  2070. self.assertFalse(os.path.exists(fullpath2))
  2071. # Check index matches first commit
  2072. index = self.repo.open_index()
  2073. self.assertIn(b"foo", index)
  2074. self.assertNotIn(b"bar", index)
  2075. def test_hard_deletes_files_in_subdirs(self) -> None:
  2076. """Test that reset --hard deletes files in subdirectories."""
  2077. # Create and commit files in subdirectory
  2078. subdir = os.path.join(self.repo.path, "subdir")
  2079. os.makedirs(subdir)
  2080. file1 = os.path.join(subdir, "file1")
  2081. file2 = os.path.join(subdir, "file2")
  2082. with open(file1, "w") as f:
  2083. f.write("content1")
  2084. with open(file2, "w") as f:
  2085. f.write("content2")
  2086. porcelain.add(self.repo.path, paths=[file1, file2])
  2087. porcelain.commit(
  2088. self.repo.path,
  2089. message=b"First commit",
  2090. committer=b"Jane <jane@example.com>",
  2091. author=b"John <john@example.com>",
  2092. )
  2093. # Remove one file from subdirectory and commit
  2094. porcelain.rm(self.repo.path, paths=[file2])
  2095. sha2 = porcelain.commit(
  2096. self.repo.path,
  2097. message=b"Remove file2",
  2098. committer=b"Jane <jane@example.com>",
  2099. author=b"John <john@example.com>",
  2100. )
  2101. # Create file2 again (untracked)
  2102. with open(file2, "w") as f:
  2103. f.write("new content")
  2104. # Reset to commit that has file2 removed - should delete untracked file2
  2105. porcelain.reset(self.repo, "hard", sha2)
  2106. self.assertTrue(os.path.exists(file1))
  2107. self.assertFalse(os.path.exists(file2))
  2108. def test_hard_reset_to_remote_branch(self) -> None:
  2109. """Test reset --hard to remote branch deletes local files not in remote."""
  2110. # Create a file and commit
  2111. file1 = os.path.join(self.repo.path, "file1")
  2112. with open(file1, "w") as f:
  2113. f.write("content1")
  2114. porcelain.add(self.repo.path, paths=[file1])
  2115. sha1 = porcelain.commit(
  2116. self.repo.path,
  2117. message=b"Initial commit",
  2118. committer=b"Jane <jane@example.com>",
  2119. author=b"John <john@example.com>",
  2120. )
  2121. # Create a "remote" ref that doesn't have additional files
  2122. self.repo.refs[b"refs/remotes/origin/master"] = sha1
  2123. # Add another file locally and commit
  2124. file2 = os.path.join(self.repo.path, "file2")
  2125. with open(file2, "w") as f:
  2126. f.write("content2")
  2127. porcelain.add(self.repo.path, paths=[file2])
  2128. porcelain.commit(
  2129. self.repo.path,
  2130. message=b"Add file2",
  2131. committer=b"Jane <jane@example.com>",
  2132. author=b"John <john@example.com>",
  2133. )
  2134. # Both files should exist
  2135. self.assertTrue(os.path.exists(file1))
  2136. self.assertTrue(os.path.exists(file2))
  2137. # Reset to remote branch - should delete file2
  2138. porcelain.reset(self.repo, "hard", b"refs/remotes/origin/master")
  2139. # file1 should exist, file2 should be deleted
  2140. self.assertTrue(os.path.exists(file1))
  2141. self.assertFalse(os.path.exists(file2))
  2142. def test_mixed_reset(self) -> None:
  2143. # Create initial commit
  2144. fullpath = os.path.join(self.repo.path, "foo")
  2145. with open(fullpath, "w") as f:
  2146. f.write("BAR")
  2147. porcelain.add(self.repo.path, paths=[fullpath])
  2148. first_sha = porcelain.commit(
  2149. self.repo.path,
  2150. message=b"First commit",
  2151. committer=b"Jane <jane@example.com>",
  2152. author=b"John <john@example.com>",
  2153. )
  2154. # Make second commit with modified content
  2155. with open(fullpath, "w") as f:
  2156. f.write("BAZ")
  2157. porcelain.add(self.repo.path, paths=[fullpath])
  2158. porcelain.commit(
  2159. self.repo.path,
  2160. message=b"Second commit",
  2161. committer=b"Jane <jane@example.com>",
  2162. author=b"John <john@example.com>",
  2163. )
  2164. # Modify working tree without staging
  2165. with open(fullpath, "w") as f:
  2166. f.write("MODIFIED")
  2167. # Mixed reset to first commit
  2168. porcelain.reset(self.repo, "mixed", first_sha)
  2169. # Check that HEAD points to first commit
  2170. self.assertEqual(self.repo.head(), first_sha)
  2171. # Check that index matches first commit
  2172. index = self.repo.open_index()
  2173. changes = list(
  2174. tree_changes(
  2175. self.repo,
  2176. index.commit(self.repo.object_store),
  2177. self.repo[first_sha].tree,
  2178. )
  2179. )
  2180. self.assertEqual([], changes)
  2181. # Check that working tree is unchanged (still has "MODIFIED")
  2182. with open(fullpath) as f:
  2183. self.assertEqual(f.read(), "MODIFIED")
  2184. def test_soft_reset(self) -> None:
  2185. # Create initial commit
  2186. fullpath = os.path.join(self.repo.path, "foo")
  2187. with open(fullpath, "w") as f:
  2188. f.write("BAR")
  2189. porcelain.add(self.repo.path, paths=[fullpath])
  2190. first_sha = porcelain.commit(
  2191. self.repo.path,
  2192. message=b"First commit",
  2193. committer=b"Jane <jane@example.com>",
  2194. author=b"John <john@example.com>",
  2195. )
  2196. # Make second commit with modified content
  2197. with open(fullpath, "w") as f:
  2198. f.write("BAZ")
  2199. porcelain.add(self.repo.path, paths=[fullpath])
  2200. porcelain.commit(
  2201. self.repo.path,
  2202. message=b"Second commit",
  2203. committer=b"Jane <jane@example.com>",
  2204. author=b"John <john@example.com>",
  2205. )
  2206. # Stage a new change
  2207. with open(fullpath, "w") as f:
  2208. f.write("STAGED")
  2209. porcelain.add(self.repo.path, paths=[fullpath])
  2210. # Soft reset to first commit
  2211. porcelain.reset(self.repo, "soft", first_sha)
  2212. # Check that HEAD points to first commit
  2213. self.assertEqual(self.repo.head(), first_sha)
  2214. # Check that index still has the staged change (not reset)
  2215. index = self.repo.open_index()
  2216. # The index should still contain the staged content, not the first commit's content
  2217. self.assertIn(b"foo", index)
  2218. # Check that working tree is unchanged
  2219. with open(fullpath) as f:
  2220. self.assertEqual(f.read(), "STAGED")
  2221. class ResetFileTests(PorcelainTestCase):
  2222. def test_reset_modify_file_to_commit(self) -> None:
  2223. file = "foo"
  2224. full_path = os.path.join(self.repo.path, file)
  2225. with open(full_path, "w") as f:
  2226. f.write("hello")
  2227. porcelain.add(self.repo, paths=[full_path])
  2228. sha = porcelain.commit(
  2229. self.repo,
  2230. message=b"unitest",
  2231. committer=b"Jane <jane@example.com>",
  2232. author=b"John <john@example.com>",
  2233. )
  2234. with open(full_path, "a") as f:
  2235. f.write("something new")
  2236. porcelain.reset_file(self.repo, file, target=sha)
  2237. with open(full_path) as f:
  2238. self.assertEqual("hello", f.read())
  2239. def test_reset_remove_file_to_commit(self) -> None:
  2240. file = "foo"
  2241. full_path = os.path.join(self.repo.path, file)
  2242. with open(full_path, "w") as f:
  2243. f.write("hello")
  2244. porcelain.add(self.repo, paths=[full_path])
  2245. sha = porcelain.commit(
  2246. self.repo,
  2247. message=b"unitest",
  2248. committer=b"Jane <jane@example.com>",
  2249. author=b"John <john@example.com>",
  2250. )
  2251. os.remove(full_path)
  2252. porcelain.reset_file(self.repo, file, target=sha)
  2253. with open(full_path) as f:
  2254. self.assertEqual("hello", f.read())
  2255. def test_resetfile_with_dir(self) -> None:
  2256. os.mkdir(os.path.join(self.repo.path, "new_dir"))
  2257. full_path = os.path.join(self.repo.path, "new_dir", "foo")
  2258. with open(full_path, "w") as f:
  2259. f.write("hello")
  2260. porcelain.add(self.repo, paths=[full_path])
  2261. sha = porcelain.commit(
  2262. self.repo,
  2263. message=b"unitest",
  2264. committer=b"Jane <jane@example.com>",
  2265. author=b"John <john@example.com>",
  2266. )
  2267. with open(full_path, "a") as f:
  2268. f.write("something new")
  2269. porcelain.commit(
  2270. self.repo,
  2271. message=b"unitest 2",
  2272. committer=b"Jane <jane@example.com>",
  2273. author=b"John <john@example.com>",
  2274. )
  2275. porcelain.reset_file(self.repo, os.path.join("new_dir", "foo"), target=sha)
  2276. with open(full_path) as f:
  2277. self.assertEqual("hello", f.read())
  2278. def _commit_file_with_content(repo, filename, content):
  2279. file_path = os.path.join(repo.path, filename)
  2280. with open(file_path, "w") as f:
  2281. f.write(content)
  2282. porcelain.add(repo, paths=[file_path])
  2283. sha = porcelain.commit(
  2284. repo,
  2285. message=b"add " + filename.encode(),
  2286. committer=b"Jane <jane@example.com>",
  2287. author=b"John <john@example.com>",
  2288. )
  2289. return sha, file_path
  2290. class RevertTests(PorcelainTestCase):
  2291. def test_revert_simple(self) -> None:
  2292. # Create initial commit
  2293. fullpath = os.path.join(self.repo.path, "foo")
  2294. with open(fullpath, "w") as f:
  2295. f.write("initial content\n")
  2296. porcelain.add(self.repo.path, paths=[fullpath])
  2297. porcelain.commit(
  2298. self.repo.path,
  2299. message=b"Initial commit",
  2300. committer=b"Jane <jane@example.com>",
  2301. author=b"John <john@example.com>",
  2302. )
  2303. # Make a change
  2304. with open(fullpath, "w") as f:
  2305. f.write("modified content\n")
  2306. porcelain.add(self.repo.path, paths=[fullpath])
  2307. change_sha = porcelain.commit(
  2308. self.repo.path,
  2309. message=b"Change content",
  2310. committer=b"Jane <jane@example.com>",
  2311. author=b"John <john@example.com>",
  2312. )
  2313. # Revert the change
  2314. revert_sha = porcelain.revert(self.repo.path, commits=[change_sha])
  2315. # Check the file content is back to initial
  2316. with open(fullpath) as f:
  2317. self.assertEqual("initial content\n", f.read())
  2318. # Check the revert commit message
  2319. revert_commit = self.repo[revert_sha]
  2320. self.assertIn(b'Revert "Change content"', revert_commit.message)
  2321. self.assertIn(change_sha[:7], revert_commit.message)
  2322. def test_revert_multiple(self) -> None:
  2323. # Create initial commit
  2324. fullpath = os.path.join(self.repo.path, "foo")
  2325. with open(fullpath, "w") as f:
  2326. f.write("line1\n")
  2327. porcelain.add(self.repo.path, paths=[fullpath])
  2328. porcelain.commit(
  2329. self.repo.path,
  2330. message=b"Initial commit",
  2331. committer=b"Jane <jane@example.com>",
  2332. author=b"John <john@example.com>",
  2333. )
  2334. # Add line2
  2335. with open(fullpath, "a") as f:
  2336. f.write("line2\n")
  2337. porcelain.add(self.repo.path, paths=[fullpath])
  2338. commit1 = porcelain.commit(
  2339. self.repo.path,
  2340. message=b"Add line2",
  2341. committer=b"Jane <jane@example.com>",
  2342. author=b"John <john@example.com>",
  2343. )
  2344. # Add line3
  2345. with open(fullpath, "a") as f:
  2346. f.write("line3\n")
  2347. porcelain.add(self.repo.path, paths=[fullpath])
  2348. commit2 = porcelain.commit(
  2349. self.repo.path,
  2350. message=b"Add line3",
  2351. committer=b"Jane <jane@example.com>",
  2352. author=b"John <john@example.com>",
  2353. )
  2354. # Revert both commits (in reverse order)
  2355. porcelain.revert(self.repo.path, commits=[commit2, commit1])
  2356. # Check file is back to initial state
  2357. with open(fullpath) as f:
  2358. self.assertEqual("line1\n", f.read())
  2359. def test_revert_no_commit(self) -> None:
  2360. # Create initial commit
  2361. fullpath = os.path.join(self.repo.path, "foo")
  2362. with open(fullpath, "w") as f:
  2363. f.write("initial\n")
  2364. porcelain.add(self.repo.path, paths=[fullpath])
  2365. porcelain.commit(
  2366. self.repo.path,
  2367. message=b"Initial",
  2368. committer=b"Jane <jane@example.com>",
  2369. author=b"John <john@example.com>",
  2370. )
  2371. # Make a change
  2372. with open(fullpath, "w") as f:
  2373. f.write("changed\n")
  2374. porcelain.add(self.repo.path, paths=[fullpath])
  2375. change_sha = porcelain.commit(
  2376. self.repo.path,
  2377. message=b"Change",
  2378. committer=b"Jane <jane@example.com>",
  2379. author=b"John <john@example.com>",
  2380. )
  2381. # Revert with no_commit
  2382. result = porcelain.revert(self.repo.path, commits=[change_sha], no_commit=True)
  2383. # Should return None
  2384. self.assertIsNone(result)
  2385. # File should be reverted
  2386. with open(fullpath) as f:
  2387. self.assertEqual("initial\n", f.read())
  2388. # HEAD should still point to the change commit
  2389. self.assertEqual(self.repo.refs[b"HEAD"], change_sha)
  2390. def test_revert_custom_message(self) -> None:
  2391. # Create commits
  2392. fullpath = os.path.join(self.repo.path, "foo")
  2393. with open(fullpath, "w") as f:
  2394. f.write("initial\n")
  2395. porcelain.add(self.repo.path, paths=[fullpath])
  2396. porcelain.commit(
  2397. self.repo.path,
  2398. message=b"Initial",
  2399. committer=b"Jane <jane@example.com>",
  2400. author=b"John <john@example.com>",
  2401. )
  2402. with open(fullpath, "w") as f:
  2403. f.write("changed\n")
  2404. porcelain.add(self.repo.path, paths=[fullpath])
  2405. change_sha = porcelain.commit(
  2406. self.repo.path,
  2407. message=b"Change",
  2408. committer=b"Jane <jane@example.com>",
  2409. author=b"John <john@example.com>",
  2410. )
  2411. # Revert with custom message
  2412. custom_msg = "Custom revert message"
  2413. revert_sha = porcelain.revert(
  2414. self.repo.path, commits=[change_sha], message=custom_msg
  2415. )
  2416. # Check the message
  2417. revert_commit = self.repo[revert_sha]
  2418. self.assertEqual(custom_msg.encode("utf-8"), revert_commit.message)
  2419. def test_revert_no_parent(self) -> None:
  2420. # Try to revert the initial commit (no parent)
  2421. fullpath = os.path.join(self.repo.path, "foo")
  2422. with open(fullpath, "w") as f:
  2423. f.write("content\n")
  2424. porcelain.add(self.repo.path, paths=[fullpath])
  2425. initial_sha = porcelain.commit(
  2426. self.repo.path,
  2427. message=b"Initial",
  2428. committer=b"Jane <jane@example.com>",
  2429. author=b"John <john@example.com>",
  2430. )
  2431. # Should raise an error
  2432. with self.assertRaises(porcelain.Error) as cm:
  2433. porcelain.revert(self.repo.path, commits=[initial_sha])
  2434. self.assertIn("no parents", str(cm.exception))
  2435. class CheckoutTests(PorcelainTestCase):
  2436. def setUp(self) -> None:
  2437. super().setUp()
  2438. self._sha, self._foo_path = _commit_file_with_content(
  2439. self.repo, "foo", "hello\n"
  2440. )
  2441. porcelain.branch_create(self.repo, "uni")
  2442. def test_checkout_to_existing_branch(self) -> None:
  2443. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2444. porcelain.checkout(self.repo, b"uni")
  2445. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2446. def test_checkout_to_non_existing_branch(self) -> None:
  2447. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2448. with self.assertRaises(KeyError):
  2449. porcelain.checkout(self.repo, b"bob")
  2450. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2451. def test_checkout_to_branch_with_modified_files(self) -> None:
  2452. with open(self._foo_path, "a") as f:
  2453. f.write("new message\n")
  2454. porcelain.add(self.repo, paths=[self._foo_path])
  2455. status = list(porcelain.status(self.repo))
  2456. self.assertEqual(
  2457. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  2458. )
  2459. # The new checkout behavior prevents switching with staged changes
  2460. with self.assertRaises(porcelain.CheckoutError):
  2461. porcelain.checkout(self.repo, b"uni")
  2462. # Should still be on master
  2463. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2464. # Force checkout should work
  2465. porcelain.checkout(self.repo, b"uni", force=True)
  2466. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2467. def test_checkout_with_deleted_files(self) -> None:
  2468. porcelain.remove(self.repo.path, [os.path.join(self.repo.path, "foo")])
  2469. status = list(porcelain.status(self.repo))
  2470. self.assertEqual(
  2471. [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status
  2472. )
  2473. # The new checkout behavior prevents switching with staged deletions
  2474. with self.assertRaises(porcelain.CheckoutError):
  2475. porcelain.checkout(self.repo, b"uni")
  2476. # Should still be on master
  2477. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2478. # Force checkout should work
  2479. porcelain.checkout(self.repo, b"uni", force=True)
  2480. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2481. def test_checkout_to_branch_with_added_files(self) -> None:
  2482. file_path = os.path.join(self.repo.path, "bar")
  2483. with open(file_path, "w") as f:
  2484. f.write("bar content\n")
  2485. porcelain.add(self.repo, paths=[file_path])
  2486. status = list(porcelain.status(self.repo))
  2487. self.assertEqual(
  2488. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  2489. )
  2490. # Both branches have file 'foo' checkout should be fine.
  2491. porcelain.checkout(self.repo, b"uni")
  2492. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2493. status = list(porcelain.status(self.repo))
  2494. self.assertEqual(
  2495. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  2496. )
  2497. def test_checkout_to_branch_with_modified_file_not_present(self) -> None:
  2498. # Commit a new file that the other branch doesn't have.
  2499. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  2500. # Modify the file the other branch doesn't have.
  2501. with open(nee_path, "a") as f:
  2502. f.write("bar content\n")
  2503. porcelain.add(self.repo, paths=[nee_path])
  2504. status = list(porcelain.status(self.repo))
  2505. self.assertEqual(
  2506. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  2507. )
  2508. # The new checkout behavior allows switching if the file doesn't exist in target branch
  2509. # (changes can be preserved)
  2510. porcelain.checkout(self.repo, b"uni")
  2511. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2512. # The staged changes are lost and the file is removed from working tree
  2513. # because it doesn't exist in the target branch
  2514. status = list(porcelain.status(self.repo))
  2515. # File 'nee' is gone completely
  2516. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2517. self.assertFalse(os.path.exists(nee_path))
  2518. def test_checkout_to_branch_with_modified_file_not_present_forced(self) -> None:
  2519. # Commit a new file that the other branch doesn't have.
  2520. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  2521. # Modify the file the other branch doesn't have.
  2522. with open(nee_path, "a") as f:
  2523. f.write("bar content\n")
  2524. porcelain.add(self.repo, paths=[nee_path])
  2525. status = list(porcelain.status(self.repo))
  2526. self.assertEqual(
  2527. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  2528. )
  2529. # 'uni' branch doesn't have 'nee' and it has been modified, but we force to reset the entire index.
  2530. porcelain.checkout(self.repo, b"uni", force=True)
  2531. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2532. status = list(porcelain.status(self.repo))
  2533. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2534. def test_checkout_to_branch_with_unstaged_files(self) -> None:
  2535. # Edit `foo`.
  2536. with open(self._foo_path, "a") as f:
  2537. f.write("new message")
  2538. status = list(porcelain.status(self.repo))
  2539. self.assertEqual(
  2540. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  2541. )
  2542. # The new checkout behavior prevents switching with unstaged changes
  2543. with self.assertRaises(porcelain.CheckoutError):
  2544. porcelain.checkout(self.repo, b"uni")
  2545. # Should still be on master
  2546. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2547. # Force checkout should work
  2548. porcelain.checkout(self.repo, b"uni", force=True)
  2549. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2550. def test_checkout_to_branch_with_untracked_files(self) -> None:
  2551. with open(os.path.join(self.repo.path, "neu"), "a") as f:
  2552. f.write("new message\n")
  2553. status = list(porcelain.status(self.repo))
  2554. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  2555. porcelain.checkout(self.repo, b"uni")
  2556. status = list(porcelain.status(self.repo))
  2557. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  2558. def test_checkout_to_branch_with_new_files(self) -> None:
  2559. porcelain.checkout(self.repo, b"uni")
  2560. sub_directory = os.path.join(self.repo.path, "sub1")
  2561. os.mkdir(sub_directory)
  2562. for index in range(5):
  2563. _commit_file_with_content(
  2564. self.repo, "new_file_" + str(index + 1), "Some content\n"
  2565. )
  2566. _commit_file_with_content(
  2567. self.repo,
  2568. os.path.join("sub1", "new_file_" + str(index + 10)),
  2569. "Good content\n",
  2570. )
  2571. status = list(porcelain.status(self.repo))
  2572. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2573. porcelain.checkout(self.repo, b"master")
  2574. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2575. status = list(porcelain.status(self.repo))
  2576. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2577. porcelain.checkout(self.repo, b"uni")
  2578. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2579. status = list(porcelain.status(self.repo))
  2580. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2581. def test_checkout_to_branch_with_file_in_sub_directory(self) -> None:
  2582. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  2583. os.makedirs(sub_directory)
  2584. sub_directory_file = os.path.join(sub_directory, "neu")
  2585. with open(sub_directory_file, "w") as f:
  2586. f.write("new message\n")
  2587. porcelain.add(self.repo, paths=[sub_directory_file])
  2588. porcelain.commit(
  2589. self.repo,
  2590. message=b"add " + sub_directory_file.encode(),
  2591. committer=b"Jane <jane@example.com>",
  2592. author=b"John <john@example.com>",
  2593. )
  2594. status = list(porcelain.status(self.repo))
  2595. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2596. self.assertTrue(os.path.isdir(sub_directory))
  2597. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  2598. porcelain.checkout(self.repo, b"uni")
  2599. status = list(porcelain.status(self.repo))
  2600. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2601. self.assertFalse(os.path.isdir(sub_directory))
  2602. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  2603. porcelain.checkout(self.repo, b"master")
  2604. self.assertTrue(os.path.isdir(sub_directory))
  2605. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  2606. def test_checkout_to_branch_with_multiple_files_in_sub_directory(self) -> None:
  2607. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  2608. os.makedirs(sub_directory)
  2609. sub_directory_file_1 = os.path.join(sub_directory, "neu")
  2610. with open(sub_directory_file_1, "w") as f:
  2611. f.write("new message\n")
  2612. sub_directory_file_2 = os.path.join(sub_directory, "gus")
  2613. with open(sub_directory_file_2, "w") as f:
  2614. f.write("alternative message\n")
  2615. porcelain.add(self.repo, paths=[sub_directory_file_1, sub_directory_file_2])
  2616. porcelain.commit(
  2617. self.repo,
  2618. message=b"add files neu and gus.",
  2619. committer=b"Jane <jane@example.com>",
  2620. author=b"John <john@example.com>",
  2621. )
  2622. status = list(porcelain.status(self.repo))
  2623. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2624. self.assertTrue(os.path.isdir(sub_directory))
  2625. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  2626. porcelain.checkout(self.repo, b"uni")
  2627. status = list(porcelain.status(self.repo))
  2628. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2629. self.assertFalse(os.path.isdir(sub_directory))
  2630. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  2631. def _commit_something_wrong(self):
  2632. with open(self._foo_path, "a") as f:
  2633. f.write("something wrong")
  2634. porcelain.add(self.repo, paths=[self._foo_path])
  2635. return porcelain.commit(
  2636. self.repo,
  2637. message=b"I may added something wrong",
  2638. committer=b"Jane <jane@example.com>",
  2639. author=b"John <john@example.com>",
  2640. )
  2641. def test_checkout_to_commit_sha(self) -> None:
  2642. self._commit_something_wrong()
  2643. porcelain.checkout(self.repo, self._sha)
  2644. self.assertEqual(self._sha, self.repo.head())
  2645. def test_checkout_to_head(self) -> None:
  2646. new_sha = self._commit_something_wrong()
  2647. porcelain.checkout(self.repo, b"HEAD")
  2648. self.assertEqual(new_sha, self.repo.head())
  2649. def _checkout_remote_branch(self):
  2650. errstream = BytesIO()
  2651. outstream = BytesIO()
  2652. porcelain.commit(
  2653. repo=self.repo.path,
  2654. message=b"init",
  2655. author=b"author <email>",
  2656. committer=b"committer <email>",
  2657. )
  2658. # Setup target repo cloned from temp test repo
  2659. clone_path = tempfile.mkdtemp()
  2660. self.addCleanup(shutil.rmtree, clone_path)
  2661. target_repo = porcelain.clone(
  2662. self.repo.path, target=clone_path, errstream=errstream
  2663. )
  2664. try:
  2665. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  2666. finally:
  2667. target_repo.close()
  2668. # create a second file to be pushed back to origin
  2669. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  2670. os.close(handle)
  2671. porcelain.add(repo=clone_path, paths=[fullpath])
  2672. porcelain.commit(
  2673. repo=clone_path,
  2674. message=b"push",
  2675. author=b"author <email>",
  2676. committer=b"committer <email>",
  2677. )
  2678. # Setup a non-checked out branch in the remote
  2679. refs_path = b"refs/heads/foo"
  2680. new_id = self.repo[b"HEAD"].id
  2681. self.assertNotEqual(new_id, ZERO_SHA)
  2682. self.repo.refs[refs_path] = new_id
  2683. # Push to the remote
  2684. porcelain.push(
  2685. clone_path,
  2686. "origin",
  2687. b"HEAD:" + refs_path,
  2688. outstream=outstream,
  2689. errstream=errstream,
  2690. )
  2691. self.assertEqual(
  2692. target_repo.refs[b"refs/remotes/origin/foo"],
  2693. target_repo.refs[b"HEAD"],
  2694. )
  2695. # The new checkout behavior treats origin/foo as a ref and creates detached HEAD
  2696. porcelain.checkout(target_repo, b"origin/foo")
  2697. original_id = target_repo[b"HEAD"].id
  2698. uni_id = target_repo[b"refs/remotes/origin/uni"].id
  2699. # Should be in detached HEAD state
  2700. with self.assertRaises((ValueError, IndexError)):
  2701. porcelain.active_branch(target_repo)
  2702. expected_refs = {
  2703. b"HEAD": original_id,
  2704. b"refs/heads/master": original_id,
  2705. # No local foo branch is created anymore
  2706. b"refs/remotes/origin/foo": original_id,
  2707. b"refs/remotes/origin/uni": uni_id,
  2708. b"refs/remotes/origin/HEAD": new_id,
  2709. b"refs/remotes/origin/master": new_id,
  2710. }
  2711. self.assertEqual(expected_refs, target_repo.get_refs())
  2712. return target_repo
  2713. def test_checkout_remote_branch(self) -> None:
  2714. repo = self._checkout_remote_branch()
  2715. repo.close()
  2716. def test_checkout_remote_branch_then_master_then_remote_branch_again(self) -> None:
  2717. target_repo = self._checkout_remote_branch()
  2718. # Should be in detached HEAD state
  2719. with self.assertRaises((ValueError, IndexError)):
  2720. porcelain.active_branch(target_repo)
  2721. # Save the commit SHA before adding bar
  2722. detached_commit_sha, _ = _commit_file_with_content(
  2723. target_repo, "bar", "something\n"
  2724. )
  2725. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  2726. porcelain.checkout(target_repo, b"master")
  2727. self.assertEqual(b"master", porcelain.active_branch(target_repo))
  2728. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  2729. # Going back to origin/foo won't have bar because the commit was made in detached state
  2730. porcelain.checkout(target_repo, b"origin/foo")
  2731. # Should be in detached HEAD state again
  2732. with self.assertRaises((ValueError, IndexError)):
  2733. porcelain.active_branch(target_repo)
  2734. # bar is NOT there because we're back at the original origin/foo commit
  2735. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  2736. # But we can checkout the specific commit to get bar back
  2737. porcelain.checkout(target_repo, detached_commit_sha.decode())
  2738. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  2739. target_repo.close()
  2740. def test_checkout_new_branch_from_remote_sets_tracking(self) -> None:
  2741. # Create a "remote" repository
  2742. remote_path = tempfile.mkdtemp()
  2743. self.addCleanup(shutil.rmtree, remote_path)
  2744. remote_repo = porcelain.init(remote_path)
  2745. # Add a commit to the remote
  2746. remote_sha, _ = _commit_file_with_content(
  2747. remote_repo, "bar", "remote content\n"
  2748. )
  2749. # Clone the remote repository
  2750. target_path = tempfile.mkdtemp()
  2751. self.addCleanup(shutil.rmtree, target_path)
  2752. target_repo = porcelain.clone(remote_path, target_path)
  2753. # Create a remote tracking branch reference
  2754. remote_branch_ref = b"refs/remotes/origin/feature"
  2755. target_repo.refs[remote_branch_ref] = remote_sha
  2756. # Checkout a new branch from the remote branch
  2757. porcelain.checkout(target_repo, remote_branch_ref, new_branch=b"local-feature")
  2758. # Verify the branch was created and is active
  2759. self.assertEqual(b"local-feature", porcelain.active_branch(target_repo))
  2760. # Verify tracking configuration was set
  2761. config = target_repo.get_config()
  2762. self.assertEqual(
  2763. b"origin", config.get((b"branch", b"local-feature"), b"remote")
  2764. )
  2765. self.assertEqual(
  2766. b"refs/heads/feature", config.get((b"branch", b"local-feature"), b"merge")
  2767. )
  2768. target_repo.close()
  2769. remote_repo.close()
  2770. class GeneralCheckoutTests(PorcelainTestCase):
  2771. """Tests for the general checkout function that handles branches, tags, and commits."""
  2772. def setUp(self) -> None:
  2773. super().setUp()
  2774. # Create initial commit
  2775. self._sha1, self._foo_path = _commit_file_with_content(
  2776. self.repo, "foo", "initial content\n"
  2777. )
  2778. # Create a branch
  2779. porcelain.branch_create(self.repo, "feature")
  2780. # Create another commit on master
  2781. self._sha2, self._bar_path = _commit_file_with_content(
  2782. self.repo, "bar", "bar content\n"
  2783. )
  2784. # Create a tag
  2785. porcelain.tag_create(self.repo, "v1.0", objectish=self._sha1)
  2786. def test_checkout_branch(self) -> None:
  2787. """Test checking out a branch."""
  2788. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2789. # Checkout feature branch
  2790. porcelain.checkout(self.repo, "feature")
  2791. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2792. # File 'bar' should not exist in feature branch
  2793. self.assertFalse(os.path.exists(self._bar_path))
  2794. # Go back to master
  2795. porcelain.checkout(self.repo, "master")
  2796. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2797. # File 'bar' should exist again
  2798. self.assertTrue(os.path.exists(self._bar_path))
  2799. def test_checkout_commit(self) -> None:
  2800. """Test checking out a specific commit (detached HEAD)."""
  2801. # Checkout first commit by SHA
  2802. porcelain.checkout(self.repo, self._sha1.decode("ascii"))
  2803. # Should be in detached HEAD state - active_branch raises IndexError
  2804. with self.assertRaises((ValueError, IndexError)):
  2805. porcelain.active_branch(self.repo)
  2806. # File 'bar' should not exist
  2807. self.assertFalse(os.path.exists(self._bar_path))
  2808. # HEAD should point to the commit
  2809. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  2810. def test_checkout_tag(self) -> None:
  2811. """Test checking out a tag (detached HEAD)."""
  2812. # Checkout tag
  2813. porcelain.checkout(self.repo, "v1.0")
  2814. # Should be in detached HEAD state - active_branch raises IndexError
  2815. with self.assertRaises((ValueError, IndexError)):
  2816. porcelain.active_branch(self.repo)
  2817. # File 'bar' should not exist (tag points to first commit)
  2818. self.assertFalse(os.path.exists(self._bar_path))
  2819. # HEAD should point to the tagged commit
  2820. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  2821. def test_checkout_new_branch(self) -> None:
  2822. """Test creating a new branch during checkout (like git checkout -b)."""
  2823. # Create and checkout new branch from current HEAD
  2824. porcelain.checkout(self.repo, "master", new_branch="new-feature")
  2825. self.assertEqual(b"new-feature", porcelain.active_branch(self.repo))
  2826. self.assertTrue(os.path.exists(self._bar_path))
  2827. # Create and checkout new branch from specific commit
  2828. porcelain.checkout(self.repo, self._sha1.decode("ascii"), new_branch="from-old")
  2829. self.assertEqual(b"from-old", porcelain.active_branch(self.repo))
  2830. self.assertFalse(os.path.exists(self._bar_path))
  2831. def test_checkout_with_uncommitted_changes(self) -> None:
  2832. """Test checkout behavior with uncommitted changes."""
  2833. # Modify a file
  2834. with open(self._foo_path, "w") as f:
  2835. f.write("modified content\n")
  2836. # Should raise error when trying to checkout
  2837. with self.assertRaises(porcelain.CheckoutError) as cm:
  2838. porcelain.checkout(self.repo, "feature")
  2839. self.assertIn("local changes", str(cm.exception))
  2840. self.assertIn("foo", str(cm.exception))
  2841. # Should still be on master
  2842. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2843. def test_checkout_force(self) -> None:
  2844. """Test forced checkout discards local changes."""
  2845. # Modify a file
  2846. with open(self._foo_path, "w") as f:
  2847. f.write("modified content\n")
  2848. # Force checkout should succeed
  2849. porcelain.checkout(self.repo, "feature", force=True)
  2850. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2851. # Local changes should be discarded
  2852. with open(self._foo_path) as f:
  2853. content = f.read()
  2854. self.assertEqual("initial content\n", content)
  2855. def test_checkout_nonexistent_ref(self) -> None:
  2856. """Test checkout of non-existent branch/commit."""
  2857. with self.assertRaises(KeyError):
  2858. porcelain.checkout(self.repo, "nonexistent")
  2859. def test_checkout_partial_sha(self) -> None:
  2860. """Test checkout with partial SHA."""
  2861. # Git typically allows checkout with partial SHA
  2862. partial_sha = self._sha1.decode("ascii")[:7]
  2863. porcelain.checkout(self.repo, partial_sha)
  2864. # Should be in detached HEAD state at the right commit
  2865. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  2866. def test_checkout_preserves_untracked_files(self) -> None:
  2867. """Test that checkout preserves untracked files."""
  2868. # Create an untracked file
  2869. untracked_path = os.path.join(self.repo.path, "untracked.txt")
  2870. with open(untracked_path, "w") as f:
  2871. f.write("untracked content\n")
  2872. # Checkout another branch
  2873. porcelain.checkout(self.repo, "feature")
  2874. # Untracked file should still exist
  2875. self.assertTrue(os.path.exists(untracked_path))
  2876. with open(untracked_path) as f:
  2877. content = f.read()
  2878. self.assertEqual("untracked content\n", content)
  2879. def test_checkout_full_ref_paths(self) -> None:
  2880. """Test checkout with full ref paths."""
  2881. # Test checkout with full branch ref path
  2882. porcelain.checkout(self.repo, "refs/heads/feature")
  2883. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2884. # Test checkout with full tag ref path
  2885. porcelain.checkout(self.repo, "refs/tags/v1.0")
  2886. # Should be in detached HEAD state
  2887. with self.assertRaises((ValueError, IndexError)):
  2888. porcelain.active_branch(self.repo)
  2889. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  2890. def test_checkout_bytes_vs_string_target(self) -> None:
  2891. """Test that checkout works with both bytes and string targets."""
  2892. # Test with string target
  2893. porcelain.checkout(self.repo, "feature")
  2894. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2895. # Test with bytes target
  2896. porcelain.checkout(self.repo, b"master")
  2897. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2898. def test_checkout_new_branch_from_commit(self) -> None:
  2899. """Test creating a new branch from a specific commit."""
  2900. # Create new branch from first commit
  2901. porcelain.checkout(self.repo, self._sha1.decode(), new_branch="from-commit")
  2902. self.assertEqual(b"from-commit", porcelain.active_branch(self.repo))
  2903. # Should be at the first commit (no bar file)
  2904. self.assertFalse(os.path.exists(self._bar_path))
  2905. def test_checkout_with_staged_addition(self) -> None:
  2906. """Test checkout behavior with staged file additions."""
  2907. # Create and stage a new file that doesn't exist in target branch
  2908. new_file_path = os.path.join(self.repo.path, "new.txt")
  2909. with open(new_file_path, "w") as f:
  2910. f.write("new file content\n")
  2911. porcelain.add(self.repo, [new_file_path])
  2912. # This should succeed because the file doesn't exist in target branch
  2913. porcelain.checkout(self.repo, "feature")
  2914. # Should be on feature branch
  2915. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2916. # The new file should still exist and be staged
  2917. self.assertTrue(os.path.exists(new_file_path))
  2918. status = porcelain.status(self.repo)
  2919. self.assertIn(b"new.txt", status.staged["add"])
  2920. def test_checkout_with_staged_modification_conflict(self) -> None:
  2921. """Test checkout behavior with staged modifications that would conflict."""
  2922. # Stage changes to a file that exists in both branches
  2923. with open(self._foo_path, "w") as f:
  2924. f.write("modified content\n")
  2925. porcelain.add(self.repo, [self._foo_path])
  2926. # Should prevent checkout due to staged changes to existing file
  2927. with self.assertRaises(porcelain.CheckoutError) as cm:
  2928. porcelain.checkout(self.repo, "feature")
  2929. self.assertIn("local changes", str(cm.exception))
  2930. self.assertIn("foo", str(cm.exception))
  2931. def test_checkout_head_reference(self) -> None:
  2932. """Test checkout of HEAD reference."""
  2933. # Move to feature branch first
  2934. porcelain.checkout(self.repo, "feature")
  2935. # Checkout HEAD creates detached HEAD state
  2936. porcelain.checkout(self.repo, "HEAD")
  2937. # Should be in detached HEAD state
  2938. with self.assertRaises((ValueError, IndexError)):
  2939. porcelain.active_branch(self.repo)
  2940. def test_checkout_error_messages(self) -> None:
  2941. """Test that checkout error messages are helpful."""
  2942. # Create uncommitted changes
  2943. with open(self._foo_path, "w") as f:
  2944. f.write("uncommitted changes\n")
  2945. # Try to checkout
  2946. with self.assertRaises(porcelain.CheckoutError) as cm:
  2947. porcelain.checkout(self.repo, "feature")
  2948. error_msg = str(cm.exception)
  2949. self.assertIn("local changes", error_msg)
  2950. self.assertIn("foo", error_msg)
  2951. self.assertIn("overwritten", error_msg)
  2952. self.assertIn("commit or stash", error_msg)
  2953. class SubmoduleTests(PorcelainTestCase):
  2954. def test_empty(self) -> None:
  2955. porcelain.commit(
  2956. repo=self.repo.path,
  2957. message=b"init",
  2958. author=b"author <email>",
  2959. committer=b"committer <email>",
  2960. )
  2961. self.assertEqual([], list(porcelain.submodule_list(self.repo)))
  2962. def test_add(self) -> None:
  2963. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  2964. with open(f"{self.repo.path}/.gitmodules") as f:
  2965. self.assertEqual(
  2966. """\
  2967. [submodule "bar"]
  2968. \turl = ../bar.git
  2969. \tpath = bar
  2970. """,
  2971. f.read(),
  2972. )
  2973. def test_init(self) -> None:
  2974. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  2975. porcelain.submodule_init(self.repo)
  2976. class PushTests(PorcelainTestCase):
  2977. def test_simple(self) -> None:
  2978. """Basic test of porcelain push where self.repo is the remote. First
  2979. clone the remote, commit a file to the clone, then push the changes
  2980. back to the remote.
  2981. """
  2982. outstream = BytesIO()
  2983. errstream = BytesIO()
  2984. porcelain.commit(
  2985. repo=self.repo.path,
  2986. message=b"init",
  2987. author=b"author <email>",
  2988. committer=b"committer <email>",
  2989. )
  2990. # Setup target repo cloned from temp test repo
  2991. clone_path = tempfile.mkdtemp()
  2992. self.addCleanup(shutil.rmtree, clone_path)
  2993. target_repo = porcelain.clone(
  2994. self.repo.path, target=clone_path, errstream=errstream
  2995. )
  2996. try:
  2997. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  2998. finally:
  2999. target_repo.close()
  3000. # create a second file to be pushed back to origin
  3001. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3002. os.close(handle)
  3003. porcelain.add(repo=clone_path, paths=[fullpath])
  3004. porcelain.commit(
  3005. repo=clone_path,
  3006. message=b"push",
  3007. author=b"author <email>",
  3008. committer=b"committer <email>",
  3009. )
  3010. # Setup a non-checked out branch in the remote
  3011. refs_path = b"refs/heads/foo"
  3012. new_id = self.repo[b"HEAD"].id
  3013. self.assertNotEqual(new_id, ZERO_SHA)
  3014. self.repo.refs[refs_path] = new_id
  3015. # Push to the remote
  3016. porcelain.push(
  3017. clone_path,
  3018. "origin",
  3019. b"HEAD:" + refs_path,
  3020. outstream=outstream,
  3021. errstream=errstream,
  3022. )
  3023. self.assertEqual(
  3024. target_repo.refs[b"refs/remotes/origin/foo"],
  3025. target_repo.refs[b"HEAD"],
  3026. )
  3027. # Check that the target and source
  3028. with Repo(clone_path) as r_clone:
  3029. self.assertEqual(
  3030. {
  3031. b"HEAD": new_id,
  3032. b"refs/heads/foo": r_clone[b"HEAD"].id,
  3033. b"refs/heads/master": new_id,
  3034. },
  3035. self.repo.get_refs(),
  3036. )
  3037. self.assertEqual(r_clone[b"HEAD"].id, self.repo[refs_path].id)
  3038. # Get the change in the target repo corresponding to the add
  3039. # this will be in the foo branch.
  3040. change = next(
  3041. iter(
  3042. tree_changes(
  3043. self.repo,
  3044. self.repo[b"HEAD"].tree,
  3045. self.repo[b"refs/heads/foo"].tree,
  3046. )
  3047. )
  3048. )
  3049. self.assertEqual(
  3050. os.path.basename(fullpath), change.new.path.decode("ascii")
  3051. )
  3052. def test_local_missing(self) -> None:
  3053. """Pushing a new branch."""
  3054. outstream = BytesIO()
  3055. errstream = BytesIO()
  3056. # Setup target repo cloned from temp test repo
  3057. clone_path = tempfile.mkdtemp()
  3058. self.addCleanup(shutil.rmtree, clone_path)
  3059. target_repo = porcelain.init(clone_path)
  3060. target_repo.close()
  3061. self.assertRaises(
  3062. porcelain.Error,
  3063. porcelain.push,
  3064. self.repo,
  3065. clone_path,
  3066. b"HEAD:refs/heads/master",
  3067. outstream=outstream,
  3068. errstream=errstream,
  3069. )
  3070. def test_new(self) -> None:
  3071. """Pushing a new branch."""
  3072. outstream = BytesIO()
  3073. errstream = BytesIO()
  3074. # Setup target repo cloned from temp test repo
  3075. clone_path = tempfile.mkdtemp()
  3076. self.addCleanup(shutil.rmtree, clone_path)
  3077. target_repo = porcelain.init(clone_path)
  3078. target_repo.close()
  3079. # create a second file to be pushed back to origin
  3080. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3081. os.close(handle)
  3082. porcelain.add(repo=clone_path, paths=[fullpath])
  3083. new_id = porcelain.commit(
  3084. repo=self.repo,
  3085. message=b"push",
  3086. author=b"author <email>",
  3087. committer=b"committer <email>",
  3088. )
  3089. # Push to the remote
  3090. porcelain.push(
  3091. self.repo,
  3092. clone_path,
  3093. b"HEAD:refs/heads/master",
  3094. outstream=outstream,
  3095. errstream=errstream,
  3096. )
  3097. with Repo(clone_path) as r_clone:
  3098. self.assertEqual(
  3099. {
  3100. b"HEAD": new_id,
  3101. b"refs/heads/master": new_id,
  3102. },
  3103. r_clone.get_refs(),
  3104. )
  3105. def test_delete(self) -> None:
  3106. """Basic test of porcelain push, removing a branch."""
  3107. outstream = BytesIO()
  3108. errstream = BytesIO()
  3109. porcelain.commit(
  3110. repo=self.repo.path,
  3111. message=b"init",
  3112. author=b"author <email>",
  3113. committer=b"committer <email>",
  3114. )
  3115. # Setup target repo cloned from temp test repo
  3116. clone_path = tempfile.mkdtemp()
  3117. self.addCleanup(shutil.rmtree, clone_path)
  3118. target_repo = porcelain.clone(
  3119. self.repo.path, target=clone_path, errstream=errstream
  3120. )
  3121. target_repo.close()
  3122. # Setup a non-checked out branch in the remote
  3123. refs_path = b"refs/heads/foo"
  3124. new_id = self.repo[b"HEAD"].id
  3125. self.assertNotEqual(new_id, ZERO_SHA)
  3126. self.repo.refs[refs_path] = new_id
  3127. # Push to the remote
  3128. porcelain.push(
  3129. clone_path,
  3130. self.repo.path,
  3131. b":" + refs_path,
  3132. outstream=outstream,
  3133. errstream=errstream,
  3134. )
  3135. self.assertEqual(
  3136. {
  3137. b"HEAD": new_id,
  3138. b"refs/heads/master": new_id,
  3139. },
  3140. self.repo.get_refs(),
  3141. )
  3142. def test_diverged(self) -> None:
  3143. outstream = BytesIO()
  3144. errstream = BytesIO()
  3145. porcelain.commit(
  3146. repo=self.repo.path,
  3147. message=b"init",
  3148. author=b"author <email>",
  3149. committer=b"committer <email>",
  3150. )
  3151. # Setup target repo cloned from temp test repo
  3152. clone_path = tempfile.mkdtemp()
  3153. self.addCleanup(shutil.rmtree, clone_path)
  3154. target_repo = porcelain.clone(
  3155. self.repo.path, target=clone_path, errstream=errstream
  3156. )
  3157. target_repo.close()
  3158. remote_id = porcelain.commit(
  3159. repo=self.repo.path,
  3160. message=b"remote change",
  3161. author=b"author <email>",
  3162. committer=b"committer <email>",
  3163. )
  3164. local_id = porcelain.commit(
  3165. repo=clone_path,
  3166. message=b"local change",
  3167. author=b"author <email>",
  3168. committer=b"committer <email>",
  3169. )
  3170. outstream = BytesIO()
  3171. errstream = BytesIO()
  3172. # Push to the remote
  3173. self.assertRaises(
  3174. porcelain.DivergedBranches,
  3175. porcelain.push,
  3176. clone_path,
  3177. self.repo.path,
  3178. b"refs/heads/master",
  3179. outstream=outstream,
  3180. errstream=errstream,
  3181. )
  3182. self.assertEqual(
  3183. {
  3184. b"HEAD": remote_id,
  3185. b"refs/heads/master": remote_id,
  3186. },
  3187. self.repo.get_refs(),
  3188. )
  3189. self.assertEqual(b"", outstream.getvalue())
  3190. self.assertEqual(b"", errstream.getvalue())
  3191. outstream = BytesIO()
  3192. errstream = BytesIO()
  3193. # Push to the remote with --force
  3194. porcelain.push(
  3195. clone_path,
  3196. self.repo.path,
  3197. b"refs/heads/master",
  3198. outstream=outstream,
  3199. errstream=errstream,
  3200. force=True,
  3201. )
  3202. self.assertEqual(
  3203. {
  3204. b"HEAD": local_id,
  3205. b"refs/heads/master": local_id,
  3206. },
  3207. self.repo.get_refs(),
  3208. )
  3209. self.assertEqual(b"", outstream.getvalue())
  3210. self.assertTrue(re.match(b"Push to .* successful.\n", errstream.getvalue()))
  3211. def test_push_returns_sendpackresult(self) -> None:
  3212. """Test that push returns a SendPackResult with per-ref information."""
  3213. outstream = BytesIO()
  3214. errstream = BytesIO()
  3215. # Create initial commit
  3216. porcelain.commit(
  3217. repo=self.repo.path,
  3218. message=b"init",
  3219. author=b"author <email>",
  3220. committer=b"committer <email>",
  3221. )
  3222. # Setup target repo cloned from temp test repo
  3223. clone_path = tempfile.mkdtemp()
  3224. self.addCleanup(shutil.rmtree, clone_path)
  3225. target_repo = porcelain.clone(
  3226. self.repo.path, target=clone_path, errstream=errstream
  3227. )
  3228. target_repo.close()
  3229. # Create a commit in the clone
  3230. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3231. os.close(handle)
  3232. porcelain.add(repo=clone_path, paths=[fullpath])
  3233. porcelain.commit(
  3234. repo=clone_path,
  3235. message=b"push",
  3236. author=b"author <email>",
  3237. committer=b"committer <email>",
  3238. )
  3239. # Push and check the return value
  3240. result = porcelain.push(
  3241. clone_path,
  3242. "origin",
  3243. b"HEAD:refs/heads/new-branch",
  3244. outstream=outstream,
  3245. errstream=errstream,
  3246. )
  3247. # Verify that we get a SendPackResult
  3248. self.assertIsInstance(result, SendPackResult)
  3249. # Verify that it contains refs
  3250. self.assertIsNotNone(result.refs)
  3251. self.assertIn(b"refs/heads/new-branch", result.refs)
  3252. # Verify ref_status - should be None for successful updates
  3253. if result.ref_status:
  3254. self.assertIsNone(result.ref_status.get(b"refs/heads/new-branch"))
  3255. class PullTests(PorcelainTestCase):
  3256. def setUp(self) -> None:
  3257. super().setUp()
  3258. # create a file for initial commit
  3259. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3260. os.close(handle)
  3261. porcelain.add(repo=self.repo.path, paths=fullpath)
  3262. porcelain.commit(
  3263. repo=self.repo.path,
  3264. message=b"test",
  3265. author=b"test <email>",
  3266. committer=b"test <email>",
  3267. )
  3268. # Setup target repo
  3269. self.target_path = tempfile.mkdtemp()
  3270. self.addCleanup(shutil.rmtree, self.target_path)
  3271. target_repo = porcelain.clone(
  3272. self.repo.path, target=self.target_path, errstream=BytesIO()
  3273. )
  3274. target_repo.close()
  3275. # create a second file to be pushed
  3276. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3277. os.close(handle)
  3278. porcelain.add(repo=self.repo.path, paths=fullpath)
  3279. porcelain.commit(
  3280. repo=self.repo.path,
  3281. message=b"test2",
  3282. author=b"test2 <email>",
  3283. committer=b"test2 <email>",
  3284. )
  3285. self.assertIn(b"refs/heads/master", self.repo.refs)
  3286. self.assertIn(b"refs/heads/master", target_repo.refs)
  3287. def test_simple(self) -> None:
  3288. outstream = BytesIO()
  3289. errstream = BytesIO()
  3290. # Pull changes into the cloned repo
  3291. porcelain.pull(
  3292. self.target_path,
  3293. self.repo.path,
  3294. b"refs/heads/master",
  3295. outstream=outstream,
  3296. errstream=errstream,
  3297. )
  3298. # Check the target repo for pushed changes
  3299. with Repo(self.target_path) as r:
  3300. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  3301. def test_diverged(self) -> None:
  3302. outstream = BytesIO()
  3303. errstream = BytesIO()
  3304. c3a = porcelain.commit(
  3305. repo=self.target_path,
  3306. message=b"test3a",
  3307. author=b"test2 <email>",
  3308. committer=b"test2 <email>",
  3309. )
  3310. porcelain.commit(
  3311. repo=self.repo.path,
  3312. message=b"test3b",
  3313. author=b"test2 <email>",
  3314. committer=b"test2 <email>",
  3315. )
  3316. # Pull changes into the cloned repo
  3317. self.assertRaises(
  3318. porcelain.DivergedBranches,
  3319. porcelain.pull,
  3320. self.target_path,
  3321. self.repo.path,
  3322. b"refs/heads/master",
  3323. outstream=outstream,
  3324. errstream=errstream,
  3325. )
  3326. # Check the target repo for pushed changes
  3327. with Repo(self.target_path) as r:
  3328. self.assertEqual(r[b"refs/heads/master"].id, c3a)
  3329. # Pull with merge should now work
  3330. porcelain.pull(
  3331. self.target_path,
  3332. self.repo.path,
  3333. b"refs/heads/master",
  3334. outstream=outstream,
  3335. errstream=errstream,
  3336. fast_forward=False,
  3337. )
  3338. # Check the target repo for merged changes
  3339. with Repo(self.target_path) as r:
  3340. # HEAD should now be a merge commit
  3341. head = r[b"HEAD"]
  3342. # It should have two parents
  3343. self.assertEqual(len(head.parents), 2)
  3344. # One parent should be the previous HEAD (c3a)
  3345. self.assertIn(c3a, head.parents)
  3346. # The other parent should be from the source repo
  3347. self.assertIn(self.repo[b"HEAD"].id, head.parents)
  3348. def test_no_refspec(self) -> None:
  3349. outstream = BytesIO()
  3350. errstream = BytesIO()
  3351. # Pull changes into the cloned repo
  3352. porcelain.pull(
  3353. self.target_path,
  3354. self.repo.path,
  3355. outstream=outstream,
  3356. errstream=errstream,
  3357. )
  3358. # Check the target repo for pushed changes
  3359. with Repo(self.target_path) as r:
  3360. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  3361. def test_no_remote_location(self) -> None:
  3362. outstream = BytesIO()
  3363. errstream = BytesIO()
  3364. # Pull changes into the cloned repo
  3365. porcelain.pull(
  3366. self.target_path,
  3367. refspecs=b"refs/heads/master",
  3368. outstream=outstream,
  3369. errstream=errstream,
  3370. )
  3371. # Check the target repo for pushed changes
  3372. with Repo(self.target_path) as r:
  3373. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  3374. def test_pull_updates_working_tree(self) -> None:
  3375. """Test that pull updates the working tree with new files."""
  3376. outstream = BytesIO()
  3377. errstream = BytesIO()
  3378. # Create a new file with content in the source repo
  3379. new_file = os.path.join(self.repo.path, "newfile.txt")
  3380. with open(new_file, "w") as f:
  3381. f.write("This is new content")
  3382. porcelain.add(repo=self.repo.path, paths=[new_file])
  3383. porcelain.commit(
  3384. repo=self.repo.path,
  3385. message=b"Add new file",
  3386. author=b"test <email>",
  3387. committer=b"test <email>",
  3388. )
  3389. # Before pull, the file should not exist in target
  3390. target_file = os.path.join(self.target_path, "newfile.txt")
  3391. self.assertFalse(os.path.exists(target_file))
  3392. # Pull changes into the cloned repo
  3393. porcelain.pull(
  3394. self.target_path,
  3395. self.repo.path,
  3396. b"refs/heads/master",
  3397. outstream=outstream,
  3398. errstream=errstream,
  3399. )
  3400. # After pull, the file should exist with correct content
  3401. self.assertTrue(os.path.exists(target_file))
  3402. with open(target_file) as f:
  3403. self.assertEqual(f.read(), "This is new content")
  3404. # Check the HEAD is updated too
  3405. with Repo(self.target_path) as r:
  3406. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  3407. class StatusTests(PorcelainTestCase):
  3408. def test_empty(self) -> None:
  3409. results = porcelain.status(self.repo)
  3410. self.assertEqual({"add": [], "delete": [], "modify": []}, results.staged)
  3411. self.assertEqual([], results.unstaged)
  3412. def test_status_base(self) -> None:
  3413. """Integration test for `status` functionality."""
  3414. # Commit a dummy file then modify it
  3415. fullpath = os.path.join(self.repo.path, "foo")
  3416. with open(fullpath, "w") as f:
  3417. f.write("origstuff")
  3418. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3419. porcelain.commit(
  3420. repo=self.repo.path,
  3421. message=b"test status",
  3422. author=b"author <email>",
  3423. committer=b"committer <email>",
  3424. )
  3425. # modify access and modify time of path
  3426. os.utime(fullpath, (0, 0))
  3427. with open(fullpath, "wb") as f:
  3428. f.write(b"stuff")
  3429. # Make a dummy file and stage it
  3430. filename_add = "bar"
  3431. fullpath = os.path.join(self.repo.path, filename_add)
  3432. with open(fullpath, "w") as f:
  3433. f.write("stuff")
  3434. porcelain.add(repo=self.repo.path, paths=fullpath)
  3435. results = porcelain.status(self.repo)
  3436. self.assertEqual(results.staged["add"][0], filename_add.encode("ascii"))
  3437. self.assertEqual(results.unstaged, [b"foo"])
  3438. def test_status_all(self) -> None:
  3439. del_path = os.path.join(self.repo.path, "foo")
  3440. mod_path = os.path.join(self.repo.path, "bar")
  3441. add_path = os.path.join(self.repo.path, "baz")
  3442. us_path = os.path.join(self.repo.path, "blye")
  3443. ut_path = os.path.join(self.repo.path, "blyat")
  3444. with open(del_path, "w") as f:
  3445. f.write("origstuff")
  3446. with open(mod_path, "w") as f:
  3447. f.write("origstuff")
  3448. with open(us_path, "w") as f:
  3449. f.write("origstuff")
  3450. porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path])
  3451. porcelain.commit(
  3452. repo=self.repo.path,
  3453. message=b"test status",
  3454. author=b"author <email>",
  3455. committer=b"committer <email>",
  3456. )
  3457. porcelain.remove(self.repo.path, [del_path])
  3458. with open(add_path, "w") as f:
  3459. f.write("origstuff")
  3460. with open(mod_path, "w") as f:
  3461. f.write("more_origstuff")
  3462. with open(us_path, "w") as f:
  3463. f.write("more_origstuff")
  3464. porcelain.add(repo=self.repo.path, paths=[add_path, mod_path])
  3465. with open(us_path, "w") as f:
  3466. f.write("\norigstuff")
  3467. with open(ut_path, "w") as f:
  3468. f.write("origstuff")
  3469. results = porcelain.status(self.repo.path)
  3470. self.assertDictEqual(
  3471. {"add": [b"baz"], "delete": [b"foo"], "modify": [b"bar"]},
  3472. results.staged,
  3473. )
  3474. self.assertListEqual(results.unstaged, [b"blye"])
  3475. results_no_untracked = porcelain.status(self.repo.path, untracked_files="no")
  3476. self.assertListEqual(results_no_untracked.untracked, [])
  3477. def test_status_wrong_untracked_files_value(self) -> None:
  3478. with self.assertRaises(ValueError):
  3479. porcelain.status(self.repo.path, untracked_files="antani")
  3480. def test_status_untracked_path(self) -> None:
  3481. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  3482. os.mkdir(untracked_dir)
  3483. untracked_file = os.path.join(untracked_dir, "untracked_file")
  3484. with open(untracked_file, "w") as fh:
  3485. fh.write("untracked")
  3486. _, _, untracked = porcelain.status(self.repo.path, untracked_files="all")
  3487. self.assertEqual(untracked, ["untracked_dir/untracked_file"])
  3488. def test_status_untracked_path_normal(self) -> None:
  3489. # Create an untracked directory with multiple files
  3490. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  3491. os.mkdir(untracked_dir)
  3492. untracked_file1 = os.path.join(untracked_dir, "file1")
  3493. untracked_file2 = os.path.join(untracked_dir, "file2")
  3494. with open(untracked_file1, "w") as fh:
  3495. fh.write("untracked1")
  3496. with open(untracked_file2, "w") as fh:
  3497. fh.write("untracked2")
  3498. # Create a nested untracked directory
  3499. nested_dir = os.path.join(untracked_dir, "nested")
  3500. os.mkdir(nested_dir)
  3501. nested_file = os.path.join(nested_dir, "file3")
  3502. with open(nested_file, "w") as fh:
  3503. fh.write("untracked3")
  3504. # Test "normal" mode - should only show the directory, not individual files
  3505. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  3506. self.assertEqual(untracked, ["untracked_dir/"])
  3507. # Test "all" mode - should show all files
  3508. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  3509. self.assertEqual(
  3510. sorted(untracked_all),
  3511. [
  3512. "untracked_dir/file1",
  3513. "untracked_dir/file2",
  3514. "untracked_dir/nested/file3",
  3515. ],
  3516. )
  3517. def test_status_mixed_tracked_untracked(self) -> None:
  3518. # Create a directory with both tracked and untracked files
  3519. mixed_dir = os.path.join(self.repo_path, "mixed_dir")
  3520. os.mkdir(mixed_dir)
  3521. # Add a tracked file
  3522. tracked_file = os.path.join(mixed_dir, "tracked.txt")
  3523. with open(tracked_file, "w") as fh:
  3524. fh.write("tracked content")
  3525. porcelain.add(self.repo.path, paths=[tracked_file])
  3526. porcelain.commit(
  3527. repo=self.repo.path,
  3528. message=b"add tracked file",
  3529. author=b"author <email>",
  3530. committer=b"committer <email>",
  3531. )
  3532. # Add untracked files to the same directory
  3533. untracked_file = os.path.join(mixed_dir, "untracked.txt")
  3534. with open(untracked_file, "w") as fh:
  3535. fh.write("untracked content")
  3536. # In "normal" mode, should show individual untracked files in mixed dirs
  3537. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  3538. self.assertEqual(untracked, ["mixed_dir/untracked.txt"])
  3539. # In "all" mode, should be the same for mixed directories
  3540. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  3541. self.assertEqual(untracked_all, ["mixed_dir/untracked.txt"])
  3542. def test_status_crlf_mismatch(self) -> None:
  3543. # First make a commit as if the file has been added on a Linux system
  3544. # or with core.autocrlf=True
  3545. file_path = os.path.join(self.repo.path, "crlf")
  3546. with open(file_path, "wb") as f:
  3547. f.write(b"line1\nline2")
  3548. porcelain.add(repo=self.repo.path, paths=[file_path])
  3549. porcelain.commit(
  3550. repo=self.repo.path,
  3551. message=b"test status",
  3552. author=b"author <email>",
  3553. committer=b"committer <email>",
  3554. )
  3555. # Then update the file as if it was created by CGit on a Windows
  3556. # system with core.autocrlf=true
  3557. with open(file_path, "wb") as f:
  3558. f.write(b"line1\r\nline2")
  3559. results = porcelain.status(self.repo)
  3560. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  3561. self.assertListEqual(results.unstaged, [b"crlf"])
  3562. self.assertListEqual(results.untracked, [])
  3563. def test_status_autocrlf_true(self) -> None:
  3564. # First make a commit as if the file has been added on a Linux system
  3565. # or with core.autocrlf=True
  3566. file_path = os.path.join(self.repo.path, "crlf")
  3567. with open(file_path, "wb") as f:
  3568. f.write(b"line1\nline2")
  3569. porcelain.add(repo=self.repo.path, paths=[file_path])
  3570. porcelain.commit(
  3571. repo=self.repo.path,
  3572. message=b"test status",
  3573. author=b"author <email>",
  3574. committer=b"committer <email>",
  3575. )
  3576. # Then update the file as if it was created by CGit on a Windows
  3577. # system with core.autocrlf=true
  3578. with open(file_path, "wb") as f:
  3579. f.write(b"line1\r\nline2")
  3580. # TODO: It should be set automatically by looking at the configuration
  3581. c = self.repo.get_config()
  3582. c.set("core", "autocrlf", True)
  3583. c.write_to_path()
  3584. results = porcelain.status(self.repo)
  3585. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  3586. self.assertListEqual(results.unstaged, [])
  3587. self.assertListEqual(results.untracked, [])
  3588. def test_status_autocrlf_input(self) -> None:
  3589. # Commit existing file with CRLF
  3590. file_path = os.path.join(self.repo.path, "crlf-exists")
  3591. with open(file_path, "wb") as f:
  3592. f.write(b"line1\r\nline2")
  3593. porcelain.add(repo=self.repo.path, paths=[file_path])
  3594. porcelain.commit(
  3595. repo=self.repo.path,
  3596. message=b"test status",
  3597. author=b"author <email>",
  3598. committer=b"committer <email>",
  3599. )
  3600. c = self.repo.get_config()
  3601. c.set("core", "autocrlf", "input")
  3602. c.write_to_path()
  3603. # Add new (untracked) file
  3604. file_path = os.path.join(self.repo.path, "crlf-new")
  3605. with open(file_path, "wb") as f:
  3606. f.write(b"line1\r\nline2")
  3607. porcelain.add(repo=self.repo.path, paths=[file_path])
  3608. results = porcelain.status(self.repo)
  3609. self.assertDictEqual(
  3610. {"add": [b"crlf-new"], "delete": [], "modify": []}, results.staged
  3611. )
  3612. self.assertListEqual(results.unstaged, [])
  3613. self.assertListEqual(results.untracked, [])
  3614. def test_get_tree_changes_add(self) -> None:
  3615. """Unit test for get_tree_changes add."""
  3616. # Make a dummy file, stage
  3617. filename = "bar"
  3618. fullpath = os.path.join(self.repo.path, filename)
  3619. with open(fullpath, "w") as f:
  3620. f.write("stuff")
  3621. porcelain.add(repo=self.repo.path, paths=fullpath)
  3622. porcelain.commit(
  3623. repo=self.repo.path,
  3624. message=b"test status",
  3625. author=b"author <email>",
  3626. committer=b"committer <email>",
  3627. )
  3628. filename = "foo"
  3629. fullpath = os.path.join(self.repo.path, filename)
  3630. with open(fullpath, "w") as f:
  3631. f.write("stuff")
  3632. porcelain.add(repo=self.repo.path, paths=fullpath)
  3633. changes = porcelain.get_tree_changes(self.repo.path)
  3634. self.assertEqual(changes["add"][0], filename.encode("ascii"))
  3635. self.assertEqual(len(changes["add"]), 1)
  3636. self.assertEqual(len(changes["modify"]), 0)
  3637. self.assertEqual(len(changes["delete"]), 0)
  3638. def test_get_tree_changes_modify(self) -> None:
  3639. """Unit test for get_tree_changes modify."""
  3640. # Make a dummy file, stage, commit, modify
  3641. filename = "foo"
  3642. fullpath = os.path.join(self.repo.path, filename)
  3643. with open(fullpath, "w") as f:
  3644. f.write("stuff")
  3645. porcelain.add(repo=self.repo.path, paths=fullpath)
  3646. porcelain.commit(
  3647. repo=self.repo.path,
  3648. message=b"test status",
  3649. author=b"author <email>",
  3650. committer=b"committer <email>",
  3651. )
  3652. with open(fullpath, "w") as f:
  3653. f.write("otherstuff")
  3654. porcelain.add(repo=self.repo.path, paths=fullpath)
  3655. changes = porcelain.get_tree_changes(self.repo.path)
  3656. self.assertEqual(changes["modify"][0], filename.encode("ascii"))
  3657. self.assertEqual(len(changes["add"]), 0)
  3658. self.assertEqual(len(changes["modify"]), 1)
  3659. self.assertEqual(len(changes["delete"]), 0)
  3660. def test_get_tree_changes_delete(self) -> None:
  3661. """Unit test for get_tree_changes delete."""
  3662. # Make a dummy file, stage, commit, remove
  3663. filename = "foo"
  3664. fullpath = os.path.join(self.repo.path, filename)
  3665. with open(fullpath, "w") as f:
  3666. f.write("stuff")
  3667. porcelain.add(repo=self.repo.path, paths=fullpath)
  3668. porcelain.commit(
  3669. repo=self.repo.path,
  3670. message=b"test status",
  3671. author=b"author <email>",
  3672. committer=b"committer <email>",
  3673. )
  3674. cwd = os.getcwd()
  3675. try:
  3676. os.chdir(self.repo.path)
  3677. porcelain.remove(repo=self.repo.path, paths=[filename])
  3678. finally:
  3679. os.chdir(cwd)
  3680. changes = porcelain.get_tree_changes(self.repo.path)
  3681. self.assertEqual(changes["delete"][0], filename.encode("ascii"))
  3682. self.assertEqual(len(changes["add"]), 0)
  3683. self.assertEqual(len(changes["modify"]), 0)
  3684. self.assertEqual(len(changes["delete"]), 1)
  3685. def test_get_untracked_paths(self) -> None:
  3686. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3687. f.write("ignored\n")
  3688. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  3689. f.write("blah\n")
  3690. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  3691. f.write("blah\n")
  3692. os.symlink(
  3693. os.path.join(self.repo.path, os.pardir, "external_target"),
  3694. os.path.join(self.repo.path, "link"),
  3695. )
  3696. self.assertEqual(
  3697. {"ignored", "notignored", ".gitignore", "link"},
  3698. set(
  3699. porcelain.get_untracked_paths(
  3700. self.repo.path, self.repo.path, self.repo.open_index()
  3701. )
  3702. ),
  3703. )
  3704. self.assertEqual(
  3705. {".gitignore", "notignored", "link"},
  3706. set(porcelain.status(self.repo).untracked),
  3707. )
  3708. self.assertEqual(
  3709. {".gitignore", "notignored", "ignored", "link"},
  3710. set(porcelain.status(self.repo, ignored=True).untracked),
  3711. )
  3712. def test_get_untracked_paths_subrepo(self) -> None:
  3713. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3714. f.write("nested/\n")
  3715. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  3716. f.write("blah\n")
  3717. subrepo = Repo.init(os.path.join(self.repo.path, "nested"), mkdir=True)
  3718. with open(os.path.join(subrepo.path, "ignored"), "w") as f:
  3719. f.write("bleep\n")
  3720. with open(os.path.join(subrepo.path, "with"), "w") as f:
  3721. f.write("bloop\n")
  3722. with open(os.path.join(subrepo.path, "manager"), "w") as f:
  3723. f.write("blop\n")
  3724. self.assertEqual(
  3725. {".gitignore", "notignored", os.path.join("nested", "")},
  3726. set(
  3727. porcelain.get_untracked_paths(
  3728. self.repo.path, self.repo.path, self.repo.open_index()
  3729. )
  3730. ),
  3731. )
  3732. self.assertEqual(
  3733. {".gitignore", "notignored"},
  3734. set(
  3735. porcelain.get_untracked_paths(
  3736. self.repo.path,
  3737. self.repo.path,
  3738. self.repo.open_index(),
  3739. exclude_ignored=True,
  3740. )
  3741. ),
  3742. )
  3743. self.assertEqual(
  3744. {"ignored", "with", "manager"},
  3745. set(
  3746. porcelain.get_untracked_paths(
  3747. subrepo.path, subrepo.path, subrepo.open_index()
  3748. )
  3749. ),
  3750. )
  3751. self.assertEqual(
  3752. set(),
  3753. set(
  3754. porcelain.get_untracked_paths(
  3755. subrepo.path,
  3756. self.repo.path,
  3757. self.repo.open_index(),
  3758. )
  3759. ),
  3760. )
  3761. self.assertEqual(
  3762. {
  3763. os.path.join("nested", "ignored"),
  3764. os.path.join("nested", "with"),
  3765. os.path.join("nested", "manager"),
  3766. },
  3767. set(
  3768. porcelain.get_untracked_paths(
  3769. self.repo.path,
  3770. subrepo.path,
  3771. self.repo.open_index(),
  3772. )
  3773. ),
  3774. )
  3775. def test_get_untracked_paths_subdir(self) -> None:
  3776. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3777. f.write("subdir/\nignored")
  3778. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  3779. f.write("blah\n")
  3780. os.mkdir(os.path.join(self.repo.path, "subdir"))
  3781. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  3782. f.write("foo")
  3783. with open(os.path.join(self.repo.path, "subdir", "ignored"), "w") as f:
  3784. f.write("foo")
  3785. self.assertEqual(
  3786. {
  3787. ".gitignore",
  3788. "notignored",
  3789. "ignored",
  3790. os.path.join("subdir", ""),
  3791. },
  3792. set(
  3793. porcelain.get_untracked_paths(
  3794. self.repo.path,
  3795. self.repo.path,
  3796. self.repo.open_index(),
  3797. )
  3798. ),
  3799. )
  3800. self.assertEqual(
  3801. {".gitignore", "notignored"},
  3802. set(
  3803. porcelain.get_untracked_paths(
  3804. self.repo.path,
  3805. self.repo.path,
  3806. self.repo.open_index(),
  3807. exclude_ignored=True,
  3808. )
  3809. ),
  3810. )
  3811. def test_get_untracked_paths_invalid_untracked_files(self) -> None:
  3812. with self.assertRaises(ValueError):
  3813. list(
  3814. porcelain.get_untracked_paths(
  3815. self.repo.path,
  3816. self.repo.path,
  3817. self.repo.open_index(),
  3818. untracked_files="invalid_value",
  3819. )
  3820. )
  3821. def test_get_untracked_paths_normal(self) -> None:
  3822. # Create an untracked directory with files
  3823. untracked_dir = os.path.join(self.repo.path, "untracked_dir")
  3824. os.mkdir(untracked_dir)
  3825. with open(os.path.join(untracked_dir, "file1.txt"), "w") as f:
  3826. f.write("untracked content")
  3827. with open(os.path.join(untracked_dir, "file2.txt"), "w") as f:
  3828. f.write("more untracked content")
  3829. # Test that "normal" mode works and returns only the directory
  3830. _, _, untracked = porcelain.status(
  3831. repo=self.repo.path, untracked_files="normal"
  3832. )
  3833. self.assertEqual(untracked, ["untracked_dir/"])
  3834. def test_get_untracked_paths_top_level_issue_1247(self) -> None:
  3835. """Test for issue #1247: ensure top-level untracked files are detected."""
  3836. # Create a single top-level untracked file
  3837. with open(os.path.join(self.repo.path, "sample.txt"), "w") as f:
  3838. f.write("test content")
  3839. # Test get_untracked_paths directly
  3840. untracked = list(
  3841. porcelain.get_untracked_paths(
  3842. self.repo.path, self.repo.path, self.repo.open_index()
  3843. )
  3844. )
  3845. self.assertIn(
  3846. "sample.txt",
  3847. untracked,
  3848. "Top-level file 'sample.txt' should be in untracked list",
  3849. )
  3850. # Test via status
  3851. status = porcelain.status(self.repo)
  3852. self.assertIn(
  3853. "sample.txt",
  3854. status.untracked,
  3855. "Top-level file 'sample.txt' should be in status.untracked",
  3856. )
  3857. # TODO(jelmer): Add test for dulwich.porcelain.daemon
  3858. class UploadPackTests(PorcelainTestCase):
  3859. """Tests for upload_pack."""
  3860. def test_upload_pack(self) -> None:
  3861. outf = BytesIO()
  3862. exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf)
  3863. outlines = outf.getvalue().splitlines()
  3864. self.assertEqual([b"0000"], outlines)
  3865. self.assertEqual(0, exitcode)
  3866. class ReceivePackTests(PorcelainTestCase):
  3867. """Tests for receive_pack."""
  3868. def test_receive_pack(self) -> None:
  3869. filename = "foo"
  3870. fullpath = os.path.join(self.repo.path, filename)
  3871. with open(fullpath, "w") as f:
  3872. f.write("stuff")
  3873. porcelain.add(repo=self.repo.path, paths=fullpath)
  3874. self.repo.do_commit(
  3875. message=b"test status",
  3876. author=b"author <email>",
  3877. committer=b"committer <email>",
  3878. author_timestamp=1402354300,
  3879. commit_timestamp=1402354300,
  3880. author_timezone=0,
  3881. commit_timezone=0,
  3882. )
  3883. outf = BytesIO()
  3884. exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf)
  3885. outlines = outf.getvalue().splitlines()
  3886. self.assertEqual(
  3887. [
  3888. b"0091319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status "
  3889. b"delete-refs quiet ofs-delta side-band-64k "
  3890. b"no-done symref=HEAD:refs/heads/master",
  3891. b"003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master",
  3892. b"0000",
  3893. ],
  3894. outlines,
  3895. )
  3896. self.assertEqual(0, exitcode)
  3897. class BranchListTests(PorcelainTestCase):
  3898. def test_standard(self) -> None:
  3899. self.assertEqual(set(), set(porcelain.branch_list(self.repo)))
  3900. def test_new_branch(self) -> None:
  3901. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3902. self.repo[b"HEAD"] = c1.id
  3903. porcelain.branch_create(self.repo, b"foo")
  3904. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  3905. class BranchCreateTests(PorcelainTestCase):
  3906. def test_branch_exists(self) -> None:
  3907. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3908. self.repo[b"HEAD"] = c1.id
  3909. porcelain.branch_create(self.repo, b"foo")
  3910. self.assertRaises(porcelain.Error, porcelain.branch_create, self.repo, b"foo")
  3911. porcelain.branch_create(self.repo, b"foo", force=True)
  3912. def test_new_branch(self) -> None:
  3913. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3914. self.repo[b"HEAD"] = c1.id
  3915. porcelain.branch_create(self.repo, b"foo")
  3916. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  3917. class BranchDeleteTests(PorcelainTestCase):
  3918. def test_simple(self) -> None:
  3919. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3920. self.repo[b"HEAD"] = c1.id
  3921. porcelain.branch_create(self.repo, b"foo")
  3922. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  3923. porcelain.branch_delete(self.repo, b"foo")
  3924. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  3925. def test_simple_unicode(self) -> None:
  3926. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3927. self.repo[b"HEAD"] = c1.id
  3928. porcelain.branch_create(self.repo, "foo")
  3929. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  3930. porcelain.branch_delete(self.repo, "foo")
  3931. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  3932. class FetchTests(PorcelainTestCase):
  3933. def test_simple(self) -> None:
  3934. outstream = BytesIO()
  3935. errstream = BytesIO()
  3936. # create a file for initial commit
  3937. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3938. os.close(handle)
  3939. porcelain.add(repo=self.repo.path, paths=fullpath)
  3940. porcelain.commit(
  3941. repo=self.repo.path,
  3942. message=b"test",
  3943. author=b"test <email>",
  3944. committer=b"test <email>",
  3945. )
  3946. # Setup target repo
  3947. target_path = tempfile.mkdtemp()
  3948. self.addCleanup(shutil.rmtree, target_path)
  3949. target_repo = porcelain.clone(
  3950. self.repo.path, target=target_path, errstream=errstream
  3951. )
  3952. # create a second file to be pushed
  3953. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3954. os.close(handle)
  3955. porcelain.add(repo=self.repo.path, paths=fullpath)
  3956. porcelain.commit(
  3957. repo=self.repo.path,
  3958. message=b"test2",
  3959. author=b"test2 <email>",
  3960. committer=b"test2 <email>",
  3961. )
  3962. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  3963. target_repo.close()
  3964. # Fetch changes into the cloned repo
  3965. porcelain.fetch(target_path, "origin", outstream=outstream, errstream=errstream)
  3966. # Assert that fetch updated the local image of the remote
  3967. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  3968. # Check the target repo for pushed changes
  3969. with Repo(target_path) as r:
  3970. self.assertIn(self.repo[b"HEAD"].id, r)
  3971. def test_with_remote_name(self) -> None:
  3972. remote_name = "origin"
  3973. outstream = BytesIO()
  3974. errstream = BytesIO()
  3975. # create a file for initial commit
  3976. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3977. os.close(handle)
  3978. porcelain.add(repo=self.repo.path, paths=fullpath)
  3979. porcelain.commit(
  3980. repo=self.repo.path,
  3981. message=b"test",
  3982. author=b"test <email>",
  3983. committer=b"test <email>",
  3984. )
  3985. # Setup target repo
  3986. target_path = tempfile.mkdtemp()
  3987. self.addCleanup(shutil.rmtree, target_path)
  3988. target_repo = porcelain.clone(
  3989. self.repo.path, target=target_path, errstream=errstream
  3990. )
  3991. # Capture current refs
  3992. target_refs = target_repo.get_refs()
  3993. # create a second file to be pushed
  3994. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3995. os.close(handle)
  3996. porcelain.add(repo=self.repo.path, paths=fullpath)
  3997. porcelain.commit(
  3998. repo=self.repo.path,
  3999. message=b"test2",
  4000. author=b"test2 <email>",
  4001. committer=b"test2 <email>",
  4002. )
  4003. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  4004. target_config = target_repo.get_config()
  4005. target_config.set(
  4006. (b"remote", remote_name.encode()), b"url", self.repo.path.encode()
  4007. )
  4008. target_repo.close()
  4009. # Fetch changes into the cloned repo
  4010. porcelain.fetch(
  4011. target_path, remote_name, outstream=outstream, errstream=errstream
  4012. )
  4013. # Assert that fetch updated the local image of the remote
  4014. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  4015. # Check the target repo for pushed changes, as well as updates
  4016. # for the refs
  4017. with Repo(target_path) as r:
  4018. self.assertIn(self.repo[b"HEAD"].id, r)
  4019. self.assertNotEqual(self.repo.get_refs(), target_refs)
  4020. def assert_correct_remote_refs(
  4021. self, local_refs, remote_refs, remote_name=b"origin"
  4022. ) -> None:
  4023. """Assert that known remote refs corresponds to actual remote refs."""
  4024. local_ref_prefix = b"refs/heads"
  4025. remote_ref_prefix = b"refs/remotes/" + remote_name
  4026. locally_known_remote_refs = {
  4027. k[len(remote_ref_prefix) + 1 :]: v
  4028. for k, v in local_refs.items()
  4029. if k.startswith(remote_ref_prefix)
  4030. }
  4031. normalized_remote_refs = {
  4032. k[len(local_ref_prefix) + 1 :]: v
  4033. for k, v in remote_refs.items()
  4034. if k.startswith(local_ref_prefix)
  4035. }
  4036. if b"HEAD" in locally_known_remote_refs and b"HEAD" in remote_refs:
  4037. normalized_remote_refs[b"HEAD"] = remote_refs[b"HEAD"]
  4038. self.assertEqual(locally_known_remote_refs, normalized_remote_refs)
  4039. class RepackTests(PorcelainTestCase):
  4040. def test_empty(self) -> None:
  4041. porcelain.repack(self.repo)
  4042. def test_simple(self) -> None:
  4043. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4044. os.close(handle)
  4045. porcelain.add(repo=self.repo.path, paths=fullpath)
  4046. porcelain.repack(self.repo)
  4047. class LsTreeTests(PorcelainTestCase):
  4048. def test_empty(self) -> None:
  4049. porcelain.commit(
  4050. repo=self.repo.path,
  4051. message=b"test status",
  4052. author=b"author <email>",
  4053. committer=b"committer <email>",
  4054. )
  4055. f = StringIO()
  4056. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  4057. self.assertEqual(f.getvalue(), "")
  4058. def test_simple(self) -> None:
  4059. # Commit a dummy file then modify it
  4060. fullpath = os.path.join(self.repo.path, "foo")
  4061. with open(fullpath, "w") as f:
  4062. f.write("origstuff")
  4063. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4064. porcelain.commit(
  4065. repo=self.repo.path,
  4066. message=b"test status",
  4067. author=b"author <email>",
  4068. committer=b"committer <email>",
  4069. )
  4070. f = StringIO()
  4071. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  4072. self.assertEqual(
  4073. f.getvalue(),
  4074. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n",
  4075. )
  4076. def test_recursive(self) -> None:
  4077. # Create a directory then write a dummy file in it
  4078. dirpath = os.path.join(self.repo.path, "adir")
  4079. filepath = os.path.join(dirpath, "afile")
  4080. os.mkdir(dirpath)
  4081. with open(filepath, "w") as f:
  4082. f.write("origstuff")
  4083. porcelain.add(repo=self.repo.path, paths=[filepath])
  4084. porcelain.commit(
  4085. repo=self.repo.path,
  4086. message=b"test status",
  4087. author=b"author <email>",
  4088. committer=b"committer <email>",
  4089. )
  4090. f = StringIO()
  4091. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  4092. self.assertEqual(
  4093. f.getvalue(),
  4094. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n",
  4095. )
  4096. f = StringIO()
  4097. porcelain.ls_tree(self.repo, b"HEAD", outstream=f, recursive=True)
  4098. self.assertEqual(
  4099. f.getvalue(),
  4100. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n"
  4101. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir"
  4102. "/afile\n",
  4103. )
  4104. class LsRemoteTests(PorcelainTestCase):
  4105. def test_empty(self) -> None:
  4106. result = porcelain.ls_remote(self.repo.path)
  4107. self.assertEqual({}, result.refs)
  4108. self.assertEqual({}, result.symrefs)
  4109. def test_some(self) -> None:
  4110. cid = porcelain.commit(
  4111. repo=self.repo.path,
  4112. message=b"test status",
  4113. author=b"author <email>",
  4114. committer=b"committer <email>",
  4115. )
  4116. result = porcelain.ls_remote(self.repo.path)
  4117. self.assertEqual(
  4118. {b"refs/heads/master": cid, b"HEAD": cid},
  4119. result.refs,
  4120. )
  4121. # HEAD should be a symref to refs/heads/master
  4122. self.assertEqual({b"HEAD": b"refs/heads/master"}, result.symrefs)
  4123. class LsFilesTests(PorcelainTestCase):
  4124. def test_empty(self) -> None:
  4125. self.assertEqual([], list(porcelain.ls_files(self.repo)))
  4126. def test_simple(self) -> None:
  4127. # Commit a dummy file then modify it
  4128. fullpath = os.path.join(self.repo.path, "foo")
  4129. with open(fullpath, "w") as f:
  4130. f.write("origstuff")
  4131. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4132. self.assertEqual([b"foo"], list(porcelain.ls_files(self.repo)))
  4133. class RemoteAddTests(PorcelainTestCase):
  4134. def test_new(self) -> None:
  4135. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  4136. c = self.repo.get_config()
  4137. self.assertEqual(
  4138. c.get((b"remote", b"jelmer"), b"url"),
  4139. b"git://jelmer.uk/code/dulwich",
  4140. )
  4141. def test_exists(self) -> None:
  4142. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  4143. self.assertRaises(
  4144. porcelain.RemoteExists,
  4145. porcelain.remote_add,
  4146. self.repo,
  4147. "jelmer",
  4148. "git://jelmer.uk/code/dulwich",
  4149. )
  4150. class RemoteRemoveTests(PorcelainTestCase):
  4151. def test_remove(self) -> None:
  4152. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  4153. c = self.repo.get_config()
  4154. self.assertEqual(
  4155. c.get((b"remote", b"jelmer"), b"url"),
  4156. b"git://jelmer.uk/code/dulwich",
  4157. )
  4158. porcelain.remote_remove(self.repo, "jelmer")
  4159. self.assertRaises(KeyError, porcelain.remote_remove, self.repo, "jelmer")
  4160. c = self.repo.get_config()
  4161. self.assertRaises(KeyError, c.get, (b"remote", b"jelmer"), b"url")
  4162. class CheckIgnoreTests(PorcelainTestCase):
  4163. def test_check_ignored(self) -> None:
  4164. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  4165. f.write("foo")
  4166. foo_path = os.path.join(self.repo.path, "foo")
  4167. with open(foo_path, "w") as f:
  4168. f.write("BAR")
  4169. bar_path = os.path.join(self.repo.path, "bar")
  4170. with open(bar_path, "w") as f:
  4171. f.write("BAR")
  4172. self.assertEqual(["foo"], list(porcelain.check_ignore(self.repo, [foo_path])))
  4173. self.assertEqual([], list(porcelain.check_ignore(self.repo, [bar_path])))
  4174. def test_check_added_abs(self) -> None:
  4175. path = os.path.join(self.repo.path, "foo")
  4176. with open(path, "w") as f:
  4177. f.write("BAR")
  4178. self.repo.stage(["foo"])
  4179. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  4180. f.write("foo\n")
  4181. self.assertEqual([], list(porcelain.check_ignore(self.repo, [path])))
  4182. self.assertEqual(
  4183. ["foo"],
  4184. list(porcelain.check_ignore(self.repo, [path], no_index=True)),
  4185. )
  4186. def test_check_added_rel(self) -> None:
  4187. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  4188. f.write("BAR")
  4189. self.repo.stage(["foo"])
  4190. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  4191. f.write("foo\n")
  4192. cwd = os.getcwd()
  4193. os.mkdir(os.path.join(self.repo.path, "bar"))
  4194. os.chdir(os.path.join(self.repo.path, "bar"))
  4195. try:
  4196. self.assertEqual(list(porcelain.check_ignore(self.repo, ["../foo"])), [])
  4197. self.assertEqual(
  4198. ["../foo"],
  4199. list(porcelain.check_ignore(self.repo, ["../foo"], no_index=True)),
  4200. )
  4201. finally:
  4202. os.chdir(cwd)
  4203. class UpdateHeadTests(PorcelainTestCase):
  4204. def test_set_to_branch(self) -> None:
  4205. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4206. self.repo.refs[b"refs/heads/blah"] = c1.id
  4207. porcelain.update_head(self.repo, "blah")
  4208. self.assertEqual(c1.id, self.repo.head())
  4209. self.assertEqual(b"ref: refs/heads/blah", self.repo.refs.read_ref(b"HEAD"))
  4210. def test_set_to_branch_detached(self) -> None:
  4211. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4212. self.repo.refs[b"refs/heads/blah"] = c1.id
  4213. porcelain.update_head(self.repo, "blah", detached=True)
  4214. self.assertEqual(c1.id, self.repo.head())
  4215. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  4216. def test_set_to_commit_detached(self) -> None:
  4217. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4218. self.repo.refs[b"refs/heads/blah"] = c1.id
  4219. porcelain.update_head(self.repo, c1.id, detached=True)
  4220. self.assertEqual(c1.id, self.repo.head())
  4221. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  4222. def test_set_new_branch(self) -> None:
  4223. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4224. self.repo.refs[b"refs/heads/blah"] = c1.id
  4225. porcelain.update_head(self.repo, "blah", new_branch="bar")
  4226. self.assertEqual(c1.id, self.repo.head())
  4227. self.assertEqual(b"ref: refs/heads/bar", self.repo.refs.read_ref(b"HEAD"))
  4228. class MailmapTests(PorcelainTestCase):
  4229. def test_no_mailmap(self) -> None:
  4230. self.assertEqual(
  4231. b"Jelmer Vernooij <jelmer@samba.org>",
  4232. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  4233. )
  4234. def test_mailmap_lookup(self) -> None:
  4235. with open(os.path.join(self.repo.path, ".mailmap"), "wb") as f:
  4236. f.write(
  4237. b"""\
  4238. Jelmer Vernooij <jelmer@debian.org>
  4239. """
  4240. )
  4241. self.assertEqual(
  4242. b"Jelmer Vernooij <jelmer@debian.org>",
  4243. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  4244. )
  4245. class FsckTests(PorcelainTestCase):
  4246. def test_none(self) -> None:
  4247. self.assertEqual([], list(porcelain.fsck(self.repo)))
  4248. def test_git_dir(self) -> None:
  4249. obj = Tree()
  4250. a = Blob()
  4251. a.data = b"foo"
  4252. obj.add(b".git", 0o100644, a.id)
  4253. self.repo.object_store.add_objects([(a, None), (obj, None)])
  4254. self.assertEqual(
  4255. [(obj.id, "invalid name .git")],
  4256. [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)],
  4257. )
  4258. class DescribeTests(PorcelainTestCase):
  4259. def test_no_commits(self) -> None:
  4260. self.assertRaises(KeyError, porcelain.describe, self.repo.path)
  4261. def test_single_commit(self) -> None:
  4262. fullpath = os.path.join(self.repo.path, "foo")
  4263. with open(fullpath, "w") as f:
  4264. f.write("BAR")
  4265. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4266. sha = porcelain.commit(
  4267. self.repo.path,
  4268. message=b"Some message",
  4269. author=b"Joe <joe@example.com>",
  4270. committer=b"Bob <bob@example.com>",
  4271. )
  4272. self.assertEqual(
  4273. "g{}".format(sha[:7].decode("ascii")),
  4274. porcelain.describe(self.repo.path),
  4275. )
  4276. def test_tag(self) -> None:
  4277. fullpath = os.path.join(self.repo.path, "foo")
  4278. with open(fullpath, "w") as f:
  4279. f.write("BAR")
  4280. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4281. porcelain.commit(
  4282. self.repo.path,
  4283. message=b"Some message",
  4284. author=b"Joe <joe@example.com>",
  4285. committer=b"Bob <bob@example.com>",
  4286. )
  4287. porcelain.tag_create(
  4288. self.repo.path,
  4289. b"tryme",
  4290. b"foo <foo@bar.com>",
  4291. b"bar",
  4292. annotated=True,
  4293. )
  4294. self.assertEqual("tryme", porcelain.describe(self.repo.path))
  4295. def test_tag_and_commit(self) -> None:
  4296. fullpath = os.path.join(self.repo.path, "foo")
  4297. with open(fullpath, "w") as f:
  4298. f.write("BAR")
  4299. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4300. porcelain.commit(
  4301. self.repo.path,
  4302. message=b"Some message",
  4303. author=b"Joe <joe@example.com>",
  4304. committer=b"Bob <bob@example.com>",
  4305. )
  4306. porcelain.tag_create(
  4307. self.repo.path,
  4308. b"tryme",
  4309. b"foo <foo@bar.com>",
  4310. b"bar",
  4311. annotated=True,
  4312. )
  4313. with open(fullpath, "w") as f:
  4314. f.write("BAR2")
  4315. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4316. sha = porcelain.commit(
  4317. self.repo.path,
  4318. message=b"Some message",
  4319. author=b"Joe <joe@example.com>",
  4320. committer=b"Bob <bob@example.com>",
  4321. )
  4322. self.assertEqual(
  4323. "tryme-1-g{}".format(sha[:7].decode("ascii")),
  4324. porcelain.describe(self.repo.path),
  4325. )
  4326. def test_tag_and_commit_full(self) -> None:
  4327. fullpath = os.path.join(self.repo.path, "foo")
  4328. with open(fullpath, "w") as f:
  4329. f.write("BAR")
  4330. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4331. porcelain.commit(
  4332. self.repo.path,
  4333. message=b"Some message",
  4334. author=b"Joe <joe@example.com>",
  4335. committer=b"Bob <bob@example.com>",
  4336. )
  4337. porcelain.tag_create(
  4338. self.repo.path,
  4339. b"tryme",
  4340. b"foo <foo@bar.com>",
  4341. b"bar",
  4342. annotated=True,
  4343. )
  4344. with open(fullpath, "w") as f:
  4345. f.write("BAR2")
  4346. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4347. sha = porcelain.commit(
  4348. self.repo.path,
  4349. message=b"Some message",
  4350. author=b"Joe <joe@example.com>",
  4351. committer=b"Bob <bob@example.com>",
  4352. )
  4353. self.assertEqual(
  4354. "tryme-1-g{}".format(sha.decode("ascii")),
  4355. porcelain.describe(self.repo.path, abbrev=40),
  4356. )
  4357. def test_untagged_commit_abbreviation(self) -> None:
  4358. _, _, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]])
  4359. self.repo.refs[b"HEAD"] = c3.id
  4360. brief_description, complete_description = (
  4361. porcelain.describe(self.repo),
  4362. porcelain.describe(self.repo, abbrev=40),
  4363. )
  4364. self.assertTrue(complete_description.startswith(brief_description))
  4365. self.assertEqual(
  4366. "g{}".format(c3.id.decode("ascii")),
  4367. complete_description,
  4368. )
  4369. class PathToTreeTests(PorcelainTestCase):
  4370. def setUp(self) -> None:
  4371. super().setUp()
  4372. self.fp = os.path.join(self.test_dir, "bar")
  4373. with open(self.fp, "w") as f:
  4374. f.write("something")
  4375. oldcwd = os.getcwd()
  4376. self.addCleanup(os.chdir, oldcwd)
  4377. os.chdir(self.test_dir)
  4378. def test_path_to_tree_path_base(self) -> None:
  4379. self.assertEqual(b"bar", porcelain.path_to_tree_path(self.test_dir, self.fp))
  4380. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  4381. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "bar"))
  4382. cwd = os.getcwd()
  4383. self.assertEqual(
  4384. b"bar", porcelain.path_to_tree_path(".", os.path.join(cwd, "bar"))
  4385. )
  4386. self.assertEqual(b"bar", porcelain.path_to_tree_path(cwd, "bar"))
  4387. def test_path_to_tree_path_syntax(self) -> None:
  4388. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  4389. def test_path_to_tree_path_error(self) -> None:
  4390. with self.assertRaises(ValueError):
  4391. with tempfile.TemporaryDirectory() as od:
  4392. porcelain.path_to_tree_path(od, self.fp)
  4393. def test_path_to_tree_path_rel(self) -> None:
  4394. cwd = os.getcwd()
  4395. os.mkdir(os.path.join(self.repo.path, "foo"))
  4396. os.mkdir(os.path.join(self.repo.path, "foo/bar"))
  4397. try:
  4398. os.chdir(os.path.join(self.repo.path, "foo/bar"))
  4399. with open("baz", "w") as f:
  4400. f.write("contents")
  4401. self.assertEqual(b"bar/baz", porcelain.path_to_tree_path("..", "baz"))
  4402. self.assertEqual(
  4403. b"bar/baz",
  4404. porcelain.path_to_tree_path(
  4405. os.path.join(os.getcwd(), ".."),
  4406. os.path.join(os.getcwd(), "baz"),
  4407. ),
  4408. )
  4409. self.assertEqual(
  4410. b"bar/baz",
  4411. porcelain.path_to_tree_path("..", os.path.join(os.getcwd(), "baz")),
  4412. )
  4413. self.assertEqual(
  4414. b"bar/baz",
  4415. porcelain.path_to_tree_path(os.path.join(os.getcwd(), ".."), "baz"),
  4416. )
  4417. finally:
  4418. os.chdir(cwd)
  4419. class GetObjectByPathTests(PorcelainTestCase):
  4420. def test_simple(self) -> None:
  4421. fullpath = os.path.join(self.repo.path, "foo")
  4422. with open(fullpath, "w") as f:
  4423. f.write("BAR")
  4424. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4425. porcelain.commit(
  4426. self.repo.path,
  4427. message=b"Some message",
  4428. author=b"Joe <joe@example.com>",
  4429. committer=b"Bob <bob@example.com>",
  4430. )
  4431. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  4432. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  4433. def test_encoding(self) -> None:
  4434. fullpath = os.path.join(self.repo.path, "foo")
  4435. with open(fullpath, "w") as f:
  4436. f.write("BAR")
  4437. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4438. porcelain.commit(
  4439. self.repo.path,
  4440. message=b"Some message",
  4441. author=b"Joe <joe@example.com>",
  4442. committer=b"Bob <bob@example.com>",
  4443. encoding=b"utf-8",
  4444. )
  4445. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  4446. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  4447. def test_missing(self) -> None:
  4448. self.assertRaises(KeyError, porcelain.get_object_by_path, self.repo, "foo")
  4449. class WriteTreeTests(PorcelainTestCase):
  4450. def test_simple(self) -> None:
  4451. fullpath = os.path.join(self.repo.path, "foo")
  4452. with open(fullpath, "w") as f:
  4453. f.write("BAR")
  4454. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4455. self.assertEqual(
  4456. b"d2092c8a9f311f0311083bf8d177f2ca0ab5b241",
  4457. porcelain.write_tree(self.repo),
  4458. )
  4459. class ActiveBranchTests(PorcelainTestCase):
  4460. def test_simple(self) -> None:
  4461. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4462. class BranchTrackingTests(PorcelainTestCase):
  4463. def test_get_branch_merge(self) -> None:
  4464. # Set up branch tracking configuration
  4465. config = self.repo.get_config()
  4466. config.set((b"branch", b"master"), b"remote", b"origin")
  4467. config.set((b"branch", b"master"), b"merge", b"refs/heads/main")
  4468. config.write_to_path()
  4469. # Test getting merge ref for current branch
  4470. merge_ref = porcelain.get_branch_merge(self.repo)
  4471. self.assertEqual(b"refs/heads/main", merge_ref)
  4472. # Test getting merge ref for specific branch
  4473. merge_ref = porcelain.get_branch_merge(self.repo, b"master")
  4474. self.assertEqual(b"refs/heads/main", merge_ref)
  4475. # Test branch without merge config
  4476. with self.assertRaises(KeyError):
  4477. porcelain.get_branch_merge(self.repo, b"nonexistent")
  4478. def test_set_branch_tracking(self) -> None:
  4479. # Create a new branch
  4480. sha, _ = _commit_file_with_content(self.repo, "foo", "content\n")
  4481. porcelain.branch_create(self.repo, "feature")
  4482. # Set up tracking
  4483. porcelain.set_branch_tracking(
  4484. self.repo, b"feature", b"upstream", b"refs/heads/main"
  4485. )
  4486. # Verify configuration was written
  4487. config = self.repo.get_config()
  4488. self.assertEqual(b"upstream", config.get((b"branch", b"feature"), b"remote"))
  4489. self.assertEqual(
  4490. b"refs/heads/main", config.get((b"branch", b"feature"), b"merge")
  4491. )
  4492. class FindUniqueAbbrevTests(PorcelainTestCase):
  4493. def test_simple(self) -> None:
  4494. c1, c2, c3 = build_commit_graph(
  4495. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  4496. )
  4497. self.repo.refs[b"HEAD"] = c3.id
  4498. self.assertEqual(
  4499. c1.id.decode("ascii")[:7],
  4500. porcelain.find_unique_abbrev(self.repo.object_store, c1.id),
  4501. )
  4502. class PackRefsTests(PorcelainTestCase):
  4503. def test_all(self) -> None:
  4504. c1, c2, c3 = build_commit_graph(
  4505. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  4506. )
  4507. self.repo.refs[b"HEAD"] = c3.id
  4508. self.repo.refs[b"refs/heads/master"] = c2.id
  4509. self.repo.refs[b"refs/tags/foo"] = c1.id
  4510. porcelain.pack_refs(self.repo, all=True)
  4511. self.assertEqual(
  4512. self.repo.refs.get_packed_refs(),
  4513. {
  4514. b"refs/heads/master": c2.id,
  4515. b"refs/tags/foo": c1.id,
  4516. },
  4517. )
  4518. def test_not_all(self) -> None:
  4519. c1, c2, c3 = build_commit_graph(
  4520. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  4521. )
  4522. self.repo.refs[b"HEAD"] = c3.id
  4523. self.repo.refs[b"refs/heads/master"] = c2.id
  4524. self.repo.refs[b"refs/tags/foo"] = c1.id
  4525. porcelain.pack_refs(self.repo)
  4526. self.assertEqual(
  4527. self.repo.refs.get_packed_refs(),
  4528. {
  4529. b"refs/tags/foo": c1.id,
  4530. },
  4531. )
  4532. class ServerTests(PorcelainTestCase):
  4533. @contextlib.contextmanager
  4534. def _serving(self):
  4535. with make_server("localhost", 0, self.app) as server:
  4536. thread = threading.Thread(target=server.serve_forever, daemon=True)
  4537. thread.start()
  4538. try:
  4539. yield f"http://localhost:{server.server_port}"
  4540. finally:
  4541. server.shutdown()
  4542. thread.join(10)
  4543. def setUp(self) -> None:
  4544. super().setUp()
  4545. self.served_repo_path = os.path.join(self.test_dir, "served_repo.git")
  4546. self.served_repo = Repo.init_bare(self.served_repo_path, mkdir=True)
  4547. self.addCleanup(self.served_repo.close)
  4548. backend = DictBackend({"/": self.served_repo})
  4549. self.app = make_wsgi_chain(backend)
  4550. def test_pull(self) -> None:
  4551. (c1,) = build_commit_graph(self.served_repo.object_store, [[1]])
  4552. self.served_repo.refs[b"refs/heads/master"] = c1.id
  4553. with self._serving() as url:
  4554. porcelain.pull(self.repo, url, "master")
  4555. def test_push(self) -> None:
  4556. (c1,) = build_commit_graph(self.repo.object_store, [[1]])
  4557. self.repo.refs[b"refs/heads/master"] = c1.id
  4558. with self._serving() as url:
  4559. porcelain.push(self.repo, url, "master")
  4560. class ForEachTests(PorcelainTestCase):
  4561. def setUp(self) -> None:
  4562. super().setUp()
  4563. c1, c2, c3, c4 = build_commit_graph(
  4564. self.repo.object_store, [[1], [2, 1], [3, 1, 2], [4]]
  4565. )
  4566. porcelain.tag_create(
  4567. self.repo.path,
  4568. b"v0.1",
  4569. objectish=c1.id,
  4570. annotated=True,
  4571. message=b"0.1",
  4572. )
  4573. porcelain.tag_create(
  4574. self.repo.path,
  4575. b"v1.0",
  4576. objectish=c2.id,
  4577. annotated=True,
  4578. message=b"1.0",
  4579. )
  4580. porcelain.tag_create(self.repo.path, b"simple-tag", objectish=c3.id)
  4581. porcelain.tag_create(
  4582. self.repo.path,
  4583. b"v1.1",
  4584. objectish=c4.id,
  4585. annotated=True,
  4586. message=b"1.1",
  4587. )
  4588. porcelain.branch_create(
  4589. self.repo.path, b"feat", objectish=c2.id.decode("ascii")
  4590. )
  4591. self.repo.refs[b"HEAD"] = c4.id
  4592. def test_for_each_ref(self) -> None:
  4593. refs = porcelain.for_each_ref(self.repo)
  4594. self.assertEqual(
  4595. [(object_type, tag) for _, object_type, tag in refs],
  4596. [
  4597. (b"commit", b"refs/heads/feat"),
  4598. (b"commit", b"refs/heads/master"),
  4599. (b"commit", b"refs/tags/simple-tag"),
  4600. (b"tag", b"refs/tags/v0.1"),
  4601. (b"tag", b"refs/tags/v1.0"),
  4602. (b"tag", b"refs/tags/v1.1"),
  4603. ],
  4604. )
  4605. def test_for_each_ref_pattern(self) -> None:
  4606. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v*")
  4607. self.assertEqual(
  4608. [(object_type, tag) for _, object_type, tag in versions],
  4609. [
  4610. (b"tag", b"refs/tags/v0.1"),
  4611. (b"tag", b"refs/tags/v1.0"),
  4612. (b"tag", b"refs/tags/v1.1"),
  4613. ],
  4614. )
  4615. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v1.?")
  4616. self.assertEqual(
  4617. [(object_type, tag) for _, object_type, tag in versions],
  4618. [
  4619. (b"tag", b"refs/tags/v1.0"),
  4620. (b"tag", b"refs/tags/v1.1"),
  4621. ],
  4622. )
  4623. class SparseCheckoutTests(PorcelainTestCase):
  4624. """Integration tests for Dulwich's sparse checkout feature."""
  4625. # NOTE: We do NOT override `setUp()` here because the parent class
  4626. # (PorcelainTestCase) already:
  4627. # 1) Creates self.test_dir = a unique temp dir
  4628. # 2) Creates a subdir named "repo"
  4629. # 3) Calls Repo.init() on that path
  4630. # Re-initializing again caused FileExistsError.
  4631. #
  4632. # Utility/Placeholder
  4633. #
  4634. def sparse_checkout(self, repo, patterns, force=False):
  4635. """Wrapper around the actual porcelain.sparse_checkout function
  4636. to handle any test-specific setup or logging.
  4637. """
  4638. return porcelain.sparse_checkout(repo, patterns, force=force)
  4639. def _write_file(self, rel_path, content):
  4640. """Helper to write a file in the repository working tree."""
  4641. abs_path = os.path.join(self.repo_path, rel_path)
  4642. os.makedirs(os.path.dirname(abs_path), exist_ok=True)
  4643. with open(abs_path, "w") as f:
  4644. f.write(content)
  4645. return abs_path
  4646. def _commit_file(self, rel_path, content):
  4647. """Helper to write, add, and commit a file."""
  4648. abs_path = self._write_file(rel_path, content)
  4649. add(self.repo_path, paths=[abs_path])
  4650. commit(self.repo_path, message=b"Added " + rel_path.encode("utf-8"))
  4651. def _list_wtree_files(self):
  4652. """Return a set of all files (not dirs) present
  4653. in the working tree, ignoring .git/.
  4654. """
  4655. found_files = set()
  4656. for root, dirs, files in os.walk(self.repo_path):
  4657. # Skip .git in the walk
  4658. if ".git" in dirs:
  4659. dirs.remove(".git")
  4660. for filename in files:
  4661. file_rel = os.path.relpath(os.path.join(root, filename), self.repo_path)
  4662. found_files.add(file_rel)
  4663. return found_files
  4664. def test_only_included_paths_appear_in_wtree(self):
  4665. """Only included paths remain in the working tree, excluded paths are removed.
  4666. Commits two files, "keep_me.txt" and "exclude_me.txt". Then applies a
  4667. sparse-checkout pattern containing only "keep_me.txt". Ensures that
  4668. the latter remains in the working tree, while "exclude_me.txt" is
  4669. removed. This verifies correct application of sparse-checkout patterns
  4670. to remove files not listed.
  4671. """
  4672. self._commit_file("keep_me.txt", "I'll stay\n")
  4673. self._commit_file("exclude_me.txt", "I'll be excluded\n")
  4674. patterns = ["keep_me.txt"]
  4675. self.sparse_checkout(self.repo, patterns)
  4676. actual_files = self._list_wtree_files()
  4677. expected_files = {"keep_me.txt"}
  4678. self.assertEqual(
  4679. expected_files,
  4680. actual_files,
  4681. f"Expected only {expected_files}, but found {actual_files}",
  4682. )
  4683. def test_previously_included_paths_become_excluded(self):
  4684. """Previously included files become excluded after pattern changes.
  4685. Verifies that files initially brought into the working tree (e.g.,
  4686. by including `data/`) can later be excluded by narrowing the
  4687. sparse-checkout pattern to just `data/included_1.txt`. Confirms that
  4688. the file `data/included_2.txt` remains in the index with
  4689. skip-worktree set (rather than being removed entirely), ensuring
  4690. data is not lost and Dulwich correctly updates the index flags.
  4691. """
  4692. self._commit_file("data/included_1.txt", "some content\n")
  4693. self._commit_file("data/included_2.txt", "other content\n")
  4694. initial_patterns = ["data/"]
  4695. self.sparse_checkout(self.repo, initial_patterns)
  4696. updated_patterns = ["data/included_1.txt"]
  4697. self.sparse_checkout(self.repo, updated_patterns)
  4698. actual_files = self._list_wtree_files()
  4699. expected_files = {os.path.join("data", "included_1.txt")}
  4700. self.assertEqual(expected_files, actual_files)
  4701. idx = self.repo.open_index()
  4702. self.assertIn(b"data/included_2.txt", idx)
  4703. entry = idx[b"data/included_2.txt"]
  4704. self.assertTrue(entry.skip_worktree)
  4705. def test_force_removes_local_changes_for_excluded_paths(self):
  4706. """Forced sparse checkout removes local modifications for newly excluded paths.
  4707. Verifies that specifying force=True allows destructive operations
  4708. which discard uncommitted changes. First, we commit "file1.txt" and
  4709. then modify it. Next, we apply a pattern that excludes the file,
  4710. using force=True. The local modifications (and the file) should
  4711. be removed, leaving the working tree empty.
  4712. """
  4713. self._commit_file("file1.txt", "original content\n")
  4714. file1_path = os.path.join(self.repo_path, "file1.txt")
  4715. with open(file1_path, "a") as f:
  4716. f.write("local changes!\n")
  4717. new_patterns = ["some_other_file.txt"]
  4718. self.sparse_checkout(self.repo, new_patterns, force=True)
  4719. actual_files = self._list_wtree_files()
  4720. self.assertEqual(
  4721. set(),
  4722. actual_files,
  4723. "Force-sparse-checkout did not remove file with local changes.",
  4724. )
  4725. def test_destructive_refuse_uncommitted_changes_without_force(self):
  4726. """Fail on uncommitted changes for newly excluded paths without force.
  4727. Ensures that a sparse checkout is blocked if it would remove local
  4728. modifications from the working tree. We commit 'config.yaml', then
  4729. modify it, and finally attempt to exclude it via new patterns without
  4730. using force=True. This should raise a CheckoutError rather than
  4731. discarding the local changes.
  4732. """
  4733. self._commit_file("config.yaml", "initial\n")
  4734. cfg_path = os.path.join(self.repo_path, "config.yaml")
  4735. with open(cfg_path, "a") as f:
  4736. f.write("local modifications\n")
  4737. exclude_patterns = ["docs/"]
  4738. with self.assertRaises(CheckoutError):
  4739. self.sparse_checkout(self.repo, exclude_patterns, force=False)
  4740. def test_fnmatch_gitignore_pattern_expansion(self):
  4741. """Reading/writing patterns align with gitignore/fnmatch expansions.
  4742. Ensures that `sparse_checkout` interprets wildcard patterns (like `*.py`)
  4743. in the same way Git's sparse-checkout would. Multiple files are committed
  4744. to `src/` (e.g. `foo.py`, `foo_test.py`, `foo_helper.py`) and to `docs/`.
  4745. Then the pattern `src/foo*.py` is applied, confirming that only the
  4746. matching Python files remain in the working tree while the Markdown file
  4747. under `docs/` is excluded.
  4748. Finally, verifies that the `.git/info/sparse-checkout` file contains the
  4749. specified wildcard pattern (`src/foo*.py`), ensuring correct round-trip
  4750. of user-supplied patterns.
  4751. """
  4752. self._commit_file("src/foo.py", "print('hello')\n")
  4753. self._commit_file("src/foo_test.py", "print('test')\n")
  4754. self._commit_file("docs/readme.md", "# docs\n")
  4755. self._commit_file("src/foo_helper.py", "print('helper')\n")
  4756. patterns = ["src/foo*.py"]
  4757. self.sparse_checkout(self.repo, patterns)
  4758. actual_files = self._list_wtree_files()
  4759. expected_files = {
  4760. os.path.join("src", "foo.py"),
  4761. os.path.join("src", "foo_test.py"),
  4762. os.path.join("src", "foo_helper.py"),
  4763. }
  4764. self.assertEqual(
  4765. expected_files,
  4766. actual_files,
  4767. "Wildcard pattern not matched as expected. Either too strict or too broad.",
  4768. )
  4769. sc_file = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  4770. self.assertTrue(os.path.isfile(sc_file))
  4771. with open(sc_file) as f:
  4772. lines = f.read().strip().split()
  4773. self.assertIn("src/foo*.py", lines)
  4774. class ConeModeTests(PorcelainTestCase):
  4775. """Provide integration tests for Dulwich's cone mode sparse checkout.
  4776. This test suite verifies the expected behavior for:
  4777. * cone_mode_init
  4778. * cone_mode_set
  4779. * cone_mode_add
  4780. Although Dulwich does not yet implement cone mode, these tests are
  4781. prepared in advance to guide future development.
  4782. """
  4783. def setUp(self):
  4784. """Set up a fresh repository for each test.
  4785. This method creates a new empty repo_path and Repo object
  4786. as provided by the PorcelainTestCase base class.
  4787. """
  4788. super().setUp()
  4789. def _commit_file(self, rel_path, content=b"contents"):
  4790. """Add a file at the given relative path and commit it.
  4791. Creates necessary directories, writes the file content,
  4792. stages, and commits. The commit message and author/committer
  4793. are also provided.
  4794. """
  4795. full_path = os.path.join(self.repo_path, rel_path)
  4796. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  4797. with open(full_path, "wb") as f:
  4798. f.write(content)
  4799. porcelain.add(self.repo_path, paths=[full_path])
  4800. porcelain.commit(
  4801. self.repo_path,
  4802. message=b"Adding " + rel_path.encode("utf-8"),
  4803. author=b"Test Author <author@example.com>",
  4804. committer=b"Test Committer <committer@example.com>",
  4805. )
  4806. def _list_wtree_files(self):
  4807. """Return a set of all file paths relative to the repository root.
  4808. Walks the working tree, skipping the .git directory.
  4809. """
  4810. found_files = set()
  4811. for root, dirs, files in os.walk(self.repo_path):
  4812. if ".git" in dirs:
  4813. dirs.remove(".git")
  4814. for fn in files:
  4815. relp = os.path.relpath(os.path.join(root, fn), self.repo_path)
  4816. found_files.add(relp)
  4817. return found_files
  4818. def test_init_excludes_everything(self):
  4819. """Verify that cone_mode_init writes minimal patterns and empties the working tree.
  4820. Make some dummy files, commit them, then call cone_mode_init. Confirm
  4821. that the working tree is empty, the sparse-checkout file has the
  4822. minimal patterns (/*, !/*/), and the relevant config values are set.
  4823. """
  4824. self._commit_file("docs/readme.md", b"# doc\n")
  4825. self._commit_file("src/main.py", b"print('hello')\n")
  4826. porcelain.cone_mode_init(self.repo)
  4827. actual_files = self._list_wtree_files()
  4828. self.assertEqual(
  4829. set(),
  4830. actual_files,
  4831. "cone_mode_init did not exclude all files from the working tree.",
  4832. )
  4833. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  4834. with open(sp_path) as f:
  4835. lines = [ln.strip() for ln in f if ln.strip()]
  4836. self.assertIn("/*", lines)
  4837. self.assertIn("!/*/", lines)
  4838. config = self.repo.get_config()
  4839. self.assertEqual(config.get((b"core",), b"sparseCheckout"), b"true")
  4840. self.assertEqual(config.get((b"core",), b"sparseCheckoutCone"), b"true")
  4841. def test_set_specific_dirs(self):
  4842. """Verify that cone_mode_set overwrites the included directories to only the specified ones.
  4843. Initializes cone mode, commits some files, then calls cone_mode_set with
  4844. a list of directories. Expects that only those directories remain in the
  4845. working tree.
  4846. """
  4847. porcelain.cone_mode_init(self.repo)
  4848. self._commit_file("docs/readme.md", b"# doc\n")
  4849. self._commit_file("src/main.py", b"print('hello')\n")
  4850. self._commit_file("tests/test_foo.py", b"# tests\n")
  4851. # Everything is still excluded initially by init.
  4852. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  4853. actual_files = self._list_wtree_files()
  4854. expected_files = {
  4855. os.path.join("docs", "readme.md"),
  4856. os.path.join("src", "main.py"),
  4857. }
  4858. self.assertEqual(
  4859. expected_files,
  4860. actual_files,
  4861. "Did not see only the 'docs/' and 'src/' dirs in the working tree.",
  4862. )
  4863. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  4864. with open(sp_path) as f:
  4865. lines = [ln.strip() for ln in f if ln.strip()]
  4866. # For standard cone mode, we'd expect lines like:
  4867. # /* (include top-level files)
  4868. # !/*/ (exclude subdirectories)
  4869. # !/docs/ (re-include docs)
  4870. # !/src/ (re-include src)
  4871. # Instead of the wildcard-based lines the old test used.
  4872. self.assertIn("/*", lines)
  4873. self.assertIn("!/*/", lines)
  4874. self.assertIn("/docs/", lines)
  4875. self.assertIn("/src/", lines)
  4876. self.assertNotIn("/tests/", lines)
  4877. def test_set_overwrites_old_dirs(self):
  4878. """Ensure that calling cone_mode_set again overwrites old includes.
  4879. Initializes cone mode, includes two directories, then calls
  4880. cone_mode_set again with a different directory to confirm the
  4881. new set of includes replaces the old.
  4882. """
  4883. porcelain.cone_mode_init(self.repo)
  4884. self._commit_file("docs/readme.md")
  4885. self._commit_file("src/main.py")
  4886. self._commit_file("tests/test_bar.py")
  4887. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  4888. self.assertEqual(
  4889. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  4890. self._list_wtree_files(),
  4891. )
  4892. # Overwrite includes, now only 'tests'
  4893. porcelain.cone_mode_set(self.repo, dirs=["tests"], force=True)
  4894. actual_files = self._list_wtree_files()
  4895. expected_files = {os.path.join("tests", "test_bar.py")}
  4896. self.assertEqual(expected_files, actual_files)
  4897. def test_force_removal_of_local_mods(self):
  4898. """Confirm that force=True removes local changes in excluded paths.
  4899. cone_mode_init and cone_mode_set are called, a file is locally modified,
  4900. and then cone_mode_set is called again with force=True to exclude that path.
  4901. The excluded file should be removed with no CheckoutError.
  4902. """
  4903. porcelain.cone_mode_init(self.repo)
  4904. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  4905. self._commit_file("docs/readme.md", b"Docs stuff\n")
  4906. self._commit_file("src/main.py", b"print('hello')\n")
  4907. # Modify src/main.py
  4908. with open(os.path.join(self.repo_path, "src/main.py"), "ab") as f:
  4909. f.write(b"extra line\n")
  4910. # Exclude src/ with force=True
  4911. porcelain.cone_mode_set(self.repo, dirs=["docs"], force=True)
  4912. actual_files = self._list_wtree_files()
  4913. expected_files = {os.path.join("docs", "readme.md")}
  4914. self.assertEqual(expected_files, actual_files)
  4915. def test_add_and_merge_dirs(self):
  4916. """Verify that cone_mode_add merges new directories instead of overwriting them.
  4917. After initializing cone mode and including a single directory, call
  4918. cone_mode_add with a new directory. Confirm that both directories
  4919. remain included. Repeat for an additional directory to ensure it
  4920. is merged, not overwritten.
  4921. """
  4922. porcelain.cone_mode_init(self.repo)
  4923. self._commit_file("docs/readme.md", b"# doc\n")
  4924. self._commit_file("src/main.py", b"print('hello')\n")
  4925. self._commit_file("tests/test_bar.py", b"# tests\n")
  4926. # Include "docs" only
  4927. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  4928. self.assertEqual({os.path.join("docs", "readme.md")}, self._list_wtree_files())
  4929. # Add "src"
  4930. porcelain.cone_mode_add(self.repo, dirs=["src"])
  4931. actual_files = self._list_wtree_files()
  4932. self.assertEqual(
  4933. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  4934. actual_files,
  4935. )
  4936. # Add "tests" as well
  4937. porcelain.cone_mode_add(self.repo, dirs=["tests"])
  4938. actual_files = self._list_wtree_files()
  4939. expected_files = {
  4940. os.path.join("docs", "readme.md"),
  4941. os.path.join("src", "main.py"),
  4942. os.path.join("tests", "test_bar.py"),
  4943. }
  4944. self.assertEqual(expected_files, actual_files)
  4945. # Check .git/info/sparse-checkout
  4946. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  4947. with open(sp_path) as f:
  4948. lines = [ln.strip() for ln in f if ln.strip()]
  4949. # Standard cone mode lines:
  4950. # "/*" -> include top-level
  4951. # "!/*/" -> exclude subdirectories
  4952. # "!/docs/", "!/src/", "!/tests/" -> re-include the directories we added
  4953. self.assertIn("/*", lines)
  4954. self.assertIn("!/*/", lines)
  4955. self.assertIn("/docs/", lines)
  4956. self.assertIn("/src/", lines)
  4957. self.assertIn("/tests/", lines)
  4958. class UnpackObjectsTest(PorcelainTestCase):
  4959. def test_unpack_objects(self):
  4960. """Test unpacking objects from a pack file."""
  4961. # Create a test repository with some objects
  4962. b1 = Blob()
  4963. b1.data = b"test content 1"
  4964. b2 = Blob()
  4965. b2.data = b"test content 2"
  4966. # Add objects to the repo
  4967. self.repo.object_store.add_object(b1)
  4968. self.repo.object_store.add_object(b2)
  4969. # Create a pack file with these objects
  4970. pack_path = os.path.join(self.test_dir, "test_pack")
  4971. with (
  4972. open(pack_path + ".pack", "wb") as pack_f,
  4973. open(pack_path + ".idx", "wb") as idx_f,
  4974. ):
  4975. porcelain.pack_objects(
  4976. self.repo,
  4977. [b1.id, b2.id],
  4978. pack_f,
  4979. idx_f,
  4980. )
  4981. # Create a new repository to unpack into
  4982. target_repo_path = os.path.join(self.test_dir, "target_repo")
  4983. target_repo = Repo.init(target_repo_path, mkdir=True)
  4984. self.addCleanup(target_repo.close)
  4985. # Unpack the objects
  4986. count = porcelain.unpack_objects(pack_path + ".pack", target_repo_path)
  4987. # Verify the objects were unpacked
  4988. self.assertEqual(2, count)
  4989. self.assertIn(b1.id, target_repo.object_store)
  4990. self.assertIn(b2.id, target_repo.object_store)
  4991. # Verify the content is correct
  4992. unpacked_b1 = target_repo.object_store[b1.id]
  4993. unpacked_b2 = target_repo.object_store[b2.id]
  4994. self.assertEqual(b1.data, unpacked_b1.data)
  4995. self.assertEqual(b2.data, unpacked_b2.data)
  4996. class CountObjectsTests(PorcelainTestCase):
  4997. def test_count_objects_empty_repo(self):
  4998. """Test counting objects in an empty repository."""
  4999. stats = porcelain.count_objects(self.repo)
  5000. self.assertEqual(0, stats.count)
  5001. self.assertEqual(0, stats.size)
  5002. def test_count_objects_verbose_empty_repo(self):
  5003. """Test verbose counting in an empty repository."""
  5004. stats = porcelain.count_objects(self.repo, verbose=True)
  5005. self.assertEqual(0, stats.count)
  5006. self.assertEqual(0, stats.size)
  5007. self.assertEqual(0, stats.in_pack)
  5008. self.assertEqual(0, stats.packs)
  5009. self.assertEqual(0, stats.size_pack)
  5010. def test_count_objects_with_loose_objects(self):
  5011. """Test counting loose objects."""
  5012. # Create some loose objects
  5013. blob1 = make_object(Blob, data=b"data1")
  5014. blob2 = make_object(Blob, data=b"data2")
  5015. self.repo.object_store.add_object(blob1)
  5016. self.repo.object_store.add_object(blob2)
  5017. stats = porcelain.count_objects(self.repo)
  5018. self.assertEqual(2, stats.count)
  5019. self.assertGreater(stats.size, 0)
  5020. def test_count_objects_verbose_with_objects(self):
  5021. """Test verbose counting with both loose and packed objects."""
  5022. # Add some loose objects
  5023. for i in range(3):
  5024. blob = make_object(Blob, data=f"data{i}".encode())
  5025. self.repo.object_store.add_object(blob)
  5026. # Create a simple commit to have some objects in a pack
  5027. tree = Tree()
  5028. c1 = make_commit(tree=tree.id, message=b"Test commit")
  5029. self.repo.object_store.add_objects([(tree, None), (c1, None)])
  5030. self.repo.refs[b"HEAD"] = c1.id
  5031. # Repack to create a pack file
  5032. porcelain.repack(self.repo)
  5033. stats = porcelain.count_objects(self.repo, verbose=True)
  5034. # After repacking, loose objects might be cleaned up
  5035. self.assertIsInstance(stats.count, int)
  5036. self.assertIsInstance(stats.size, int)
  5037. self.assertGreater(stats.in_pack, 0) # Should have packed objects
  5038. self.assertGreater(stats.packs, 0) # Should have at least one pack
  5039. self.assertGreater(stats.size_pack, 0) # Pack should have size
  5040. # Verify it's the correct dataclass type
  5041. self.assertIsInstance(stats, CountObjectsResult)
  5042. class PruneTests(PorcelainTestCase):
  5043. def test_prune_removes_old_tempfiles(self):
  5044. """Test that prune removes old temporary files."""
  5045. # Create an old temporary file in the objects directory
  5046. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  5047. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_test")
  5048. with open(tmp_pack_path, "wb") as f:
  5049. f.write(b"old temporary data")
  5050. # Make it old
  5051. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  5052. os.utime(tmp_pack_path, (old_time, old_time))
  5053. # Run prune
  5054. porcelain.prune(self.repo.path)
  5055. # Verify the file was removed
  5056. self.assertFalse(os.path.exists(tmp_pack_path))
  5057. def test_prune_keeps_recent_tempfiles(self):
  5058. """Test that prune keeps recent temporary files."""
  5059. # Create a recent temporary file
  5060. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  5061. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_recent")
  5062. with open(tmp_pack_path, "wb") as f:
  5063. f.write(b"recent temporary data")
  5064. self.addCleanup(os.remove, tmp_pack_path)
  5065. # Run prune
  5066. porcelain.prune(self.repo.path)
  5067. # Verify the file was NOT removed
  5068. self.assertTrue(os.path.exists(tmp_pack_path))
  5069. def test_prune_with_custom_grace_period(self):
  5070. """Test prune with custom grace period."""
  5071. # Create a 1-hour-old temporary file
  5072. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  5073. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_1hour")
  5074. with open(tmp_pack_path, "wb") as f:
  5075. f.write(b"1 hour old data")
  5076. # Make it 1 hour old
  5077. old_time = time.time() - 3600
  5078. os.utime(tmp_pack_path, (old_time, old_time))
  5079. # Prune with 30-minute grace period should remove it
  5080. porcelain.prune(self.repo.path, grace_period=1800)
  5081. # Verify the file was removed
  5082. self.assertFalse(os.path.exists(tmp_pack_path))
  5083. def test_prune_dry_run(self):
  5084. """Test prune in dry-run mode."""
  5085. # Create an old temporary file
  5086. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  5087. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_dryrun")
  5088. with open(tmp_pack_path, "wb") as f:
  5089. f.write(b"old temporary data")
  5090. self.addCleanup(os.remove, tmp_pack_path)
  5091. # Make it old
  5092. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  5093. os.utime(tmp_pack_path, (old_time, old_time))
  5094. # Run prune in dry-run mode
  5095. porcelain.prune(self.repo.path, dry_run=True)
  5096. # Verify the file was NOT removed (dry run)
  5097. self.assertTrue(os.path.exists(tmp_pack_path))
  5098. class FilterBranchTests(PorcelainTestCase):
  5099. def setUp(self):
  5100. super().setUp()
  5101. # Create initial commits with different authors
  5102. from dulwich.objects import Commit, Tree
  5103. # Create actual tree and blob objects
  5104. tree = Tree()
  5105. self.repo.object_store.add_object(tree)
  5106. c1 = Commit()
  5107. c1.tree = tree.id
  5108. c1.parents = []
  5109. c1.author = b"Old Author <old@example.com>"
  5110. c1.author_time = 1000
  5111. c1.author_timezone = 0
  5112. c1.committer = b"Old Committer <old@example.com>"
  5113. c1.commit_time = 1000
  5114. c1.commit_timezone = 0
  5115. c1.message = b"Initial commit"
  5116. self.repo.object_store.add_object(c1)
  5117. c2 = Commit()
  5118. c2.tree = tree.id
  5119. c2.parents = [c1.id]
  5120. c2.author = b"Another Author <another@example.com>"
  5121. c2.author_time = 2000
  5122. c2.author_timezone = 0
  5123. c2.committer = b"Another Committer <another@example.com>"
  5124. c2.commit_time = 2000
  5125. c2.commit_timezone = 0
  5126. c2.message = b"Second commit\n\nWith body"
  5127. self.repo.object_store.add_object(c2)
  5128. c3 = Commit()
  5129. c3.tree = tree.id
  5130. c3.parents = [c2.id]
  5131. c3.author = b"Third Author <third@example.com>"
  5132. c3.author_time = 3000
  5133. c3.author_timezone = 0
  5134. c3.committer = b"Third Committer <third@example.com>"
  5135. c3.commit_time = 3000
  5136. c3.commit_timezone = 0
  5137. c3.message = b"Third commit"
  5138. self.repo.object_store.add_object(c3)
  5139. self.repo.refs[b"refs/heads/master"] = c3.id
  5140. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  5141. # Store IDs for test assertions
  5142. self.c1_id = c1.id
  5143. self.c2_id = c2.id
  5144. self.c3_id = c3.id
  5145. def test_filter_branch_author(self):
  5146. """Test filtering branch with author changes."""
  5147. def filter_author(author):
  5148. # Change all authors to "New Author"
  5149. return b"New Author <new@example.com>"
  5150. result = porcelain.filter_branch(
  5151. self.repo_path, "master", filter_author=filter_author
  5152. )
  5153. # Check that we have mappings for all commits
  5154. self.assertEqual(len(result), 3)
  5155. # Verify the branch ref was updated
  5156. new_head = self.repo.refs[b"refs/heads/master"]
  5157. self.assertNotEqual(new_head, self.c3_id)
  5158. # Verify the original ref was saved
  5159. original_ref = self.repo.refs[b"refs/original/refs/heads/master"]
  5160. self.assertEqual(original_ref, self.c3_id)
  5161. # Check that authors were updated
  5162. new_commit = self.repo[new_head]
  5163. self.assertEqual(new_commit.author, b"New Author <new@example.com>")
  5164. # Check parent chain
  5165. parent = self.repo[new_commit.parents[0]]
  5166. self.assertEqual(parent.author, b"New Author <new@example.com>")
  5167. def test_filter_branch_message(self):
  5168. """Test filtering branch with message changes."""
  5169. def filter_message(message):
  5170. # Add prefix to all messages
  5171. return b"[FILTERED] " + message
  5172. porcelain.filter_branch(self.repo_path, "master", filter_message=filter_message)
  5173. # Verify messages were updated
  5174. new_head = self.repo.refs[b"refs/heads/master"]
  5175. new_commit = self.repo[new_head]
  5176. self.assertTrue(new_commit.message.startswith(b"[FILTERED] "))
  5177. def test_filter_branch_custom_filter(self):
  5178. """Test filtering branch with custom filter function."""
  5179. def custom_filter(commit):
  5180. # Change both author and message
  5181. return {
  5182. "author": b"Custom Author <custom@example.com>",
  5183. "message": b"Custom: " + commit.message,
  5184. }
  5185. porcelain.filter_branch(self.repo_path, "master", filter_fn=custom_filter)
  5186. # Verify custom filter was applied
  5187. new_head = self.repo.refs[b"refs/heads/master"]
  5188. new_commit = self.repo[new_head]
  5189. self.assertEqual(new_commit.author, b"Custom Author <custom@example.com>")
  5190. self.assertTrue(new_commit.message.startswith(b"Custom: "))
  5191. def test_filter_branch_no_changes(self):
  5192. """Test filtering branch with no changes."""
  5193. result = porcelain.filter_branch(self.repo_path, "master")
  5194. # All commits should map to themselves
  5195. for old_sha, new_sha in result.items():
  5196. self.assertEqual(old_sha, new_sha)
  5197. # HEAD should be unchanged
  5198. self.assertEqual(self.repo.refs[b"refs/heads/master"], self.c3_id)
  5199. def test_filter_branch_force(self):
  5200. """Test force filtering a previously filtered branch."""
  5201. # First filter
  5202. porcelain.filter_branch(
  5203. self.repo_path, "master", filter_message=lambda m: b"First: " + m
  5204. )
  5205. # Try again without force - should fail
  5206. with self.assertRaises(porcelain.Error):
  5207. porcelain.filter_branch(
  5208. self.repo_path, "master", filter_message=lambda m: b"Second: " + m
  5209. )
  5210. # Try again with force - should succeed
  5211. porcelain.filter_branch(
  5212. self.repo_path,
  5213. "master",
  5214. filter_message=lambda m: b"Second: " + m,
  5215. force=True,
  5216. )
  5217. # Verify second filter was applied
  5218. new_head = self.repo.refs[b"refs/heads/master"]
  5219. new_commit = self.repo[new_head]
  5220. self.assertTrue(new_commit.message.startswith(b"Second: First: "))