2
0

test_porcelain.py 260 KB

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