test_porcelain.py 228 KB

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