test_porcelain.py 261 KB

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