2
0

test_porcelain.py 293 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078
  1. # test_porcelain.py -- porcelain tests
  2. # Copyright (C) 2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Tests for dulwich.porcelain."""
  22. import contextlib
  23. import os
  24. import platform
  25. import re
  26. import shutil
  27. import stat
  28. import subprocess
  29. import sys
  30. import tarfile
  31. import tempfile
  32. import threading
  33. import time
  34. from io import BytesIO, StringIO
  35. from unittest import skipIf
  36. from dulwich import porcelain
  37. from dulwich.client import SendPackResult
  38. from dulwich.diff_tree import tree_changes
  39. from dulwich.errors import CommitError
  40. from dulwich.object_store import DEFAULT_TEMPFILE_GRACE_PERIOD
  41. from dulwich.objects import ZERO_SHA, Blob, Commit, Tag, Tree
  42. from dulwich.porcelain import (
  43. CheckoutError, # Hypothetical or real error class
  44. CountObjectsResult,
  45. add,
  46. commit,
  47. )
  48. from dulwich.repo import NoIndexPresent, Repo
  49. from dulwich.server import DictBackend
  50. from dulwich.tests.utils import build_commit_graph, make_commit, make_object
  51. from dulwich.web import make_server, make_wsgi_chain
  52. from . import TestCase
  53. try:
  54. import gpg
  55. except ImportError:
  56. gpg = None
  57. def flat_walk_dir(dir_to_walk):
  58. for dirpath, _, filenames in os.walk(dir_to_walk):
  59. rel_dirpath = os.path.relpath(dirpath, dir_to_walk)
  60. if not dirpath == dir_to_walk:
  61. yield rel_dirpath
  62. for filename in filenames:
  63. if dirpath == dir_to_walk:
  64. yield filename
  65. else:
  66. yield os.path.join(rel_dirpath, filename)
  67. class PorcelainTestCase(TestCase):
  68. def setUp(self) -> None:
  69. super().setUp()
  70. # Disable pagers for tests
  71. self.overrideEnv("PAGER", "false")
  72. self.overrideEnv("GIT_PAGER", "false")
  73. self.overrideEnv("DULWICH_PAGER", "false")
  74. self.test_dir = tempfile.mkdtemp()
  75. self.addCleanup(shutil.rmtree, self.test_dir)
  76. self.repo_path = os.path.join(self.test_dir, "repo")
  77. self.repo = Repo.init(self.repo_path, mkdir=True)
  78. self.addCleanup(self.repo.close)
  79. def assertRecentTimestamp(self, ts) -> None:
  80. # On some slow CIs it does actually take more than 5 seconds to go from
  81. # creating the tag to here.
  82. self.assertLess(time.time() - ts, 50)
  83. @skipIf(gpg is None, "gpg is not available")
  84. class PorcelainGpgTestCase(PorcelainTestCase):
  85. DEFAULT_KEY = """
  86. -----BEGIN PGP PRIVATE KEY BLOCK-----
  87. lQVYBGBjIyIBDADAwydvMPQqeEiK54FG1DHwT5sQejAaJOb+PsOhVa4fLcKsrO3F
  88. g5CxO+/9BHCXAr8xQAtp/gOhDN05fyK3MFyGlL9s+Cd8xf34S3R4rN/qbF0oZmaa
  89. FW0MuGnniq54HINs8KshadVn1Dhi/GYSJ588qNFRl/qxFTYAk+zaGsgX/QgFfy0f
  90. djWXJLypZXu9D6DlyJ0cPSzUlfBkI2Ytx6grzIquRjY0FbkjK3l+iGsQ+ebRMdcP
  91. Sqd5iTN9XuzIUVoBFAZBRjibKV3N2wxlnCbfLlzCyDp7rktzSThzjJ2pVDuLrMAx
  92. 6/L9hIhwmFwdtY4FBFGvMR0b0Ugh3kCsRWr8sgj9I7dUoLHid6ObYhJFhnD3GzRc
  93. U+xX1uy3iTCqJDsG334aQIhC5Giuxln4SUZna2MNbq65ksh38N1aM/t3+Dc/TKVB
  94. rb5KWicRPCQ4DIQkHMDCSPyj+dvRLCPzIaPvHD7IrCfHYHOWuvvPGCpwjo0As3iP
  95. IecoMeguPLVaqgcAEQEAAQAL/i5/pQaUd4G7LDydpbixPS6r9UrfPrU/y5zvBP/p
  96. DCynPDutJ1oq539pZvXQ2VwEJJy7x0UVKkjyMndJLNWly9wHC7o8jkHx/NalVP47
  97. LXR+GWbCdOOcYYbdAWcCNB3zOtzPnWhdAEagkc2G9xRQDIB0dLHLCIUpCbLP/CWM
  98. qlHnDsVMrVTWjgzcpsnyGgw8NeLYJtYGB8dsN+XgCCjo7a9LEvUBKNgdmWBbf14/
  99. iBw7PCugazFcH9QYfZwzhsi3nqRRagTXHbxFRG0LD9Ro9qCEutHYGP2PJ59Nj8+M
  100. zaVkJj/OxWxVOGvn2q16mQBCjKpbWfqXZVVl+G5DGOmiSTZqXy+3j6JCKdOMy6Qd
  101. JBHOHhFZXYmWYaaPzoc33T/C3QhMfY5sOtUDLJmV05Wi4dyBeNBEslYgUuTk/jXb
  102. 5ZAie25eDdrsoqkcnSs2ZguMF7AXhe6il2zVhUUMs/6UZgd6I7I4Is0HXT/pnxEp
  103. uiTRFu4v8E+u+5a8O3pffe5boQYA3TsIxceen20qY+kRaTOkURHMZLn/y6KLW8bZ
  104. rNJyXWS9hBAcbbSGhfOwYfzbDCM17yPQO3E2zo8lcGdRklUdIIaCxQwtu36N5dfx
  105. OLCCQc5LmYdl/EAm91iAhrr7dNntZ18MU09gdzUu+ONZwu4CP3cJT83+qYZULso8
  106. 4Fvd/X8IEfGZ7kM+ylrdqBwtlrn8yYXtom+ows2M2UuNR53B+BUOd73kVLTkTCjE
  107. JH63+nE8BqG7tDLCMws+23SAA3xxBgDfDrr0x7zCozQKVQEqBzQr9Uoo/c/ZjAfi
  108. syzNSrDz+g5gqJYtuL9XpPJVWf6V1GXVyJlSbxR9CjTkBxmlPxpvV25IsbVSsh0o
  109. aqkf2eWpbCL6Qb2E0jd1rvf8sGeTTohzYfiSVVsC2t9ngRO/CmetizwQBvRzLGMZ
  110. 4mtAPiy7ZEDc2dFrPp7zlKISYmJZUx/DJVuZWuOrVMpBP+bSgJXoMTlICxZUqUnE
  111. 2VKVStb/L+Tl8XCwIWdrZb9BaDnHqfcGAM2B4HNPxP88Yj1tEDly/vqeb3vVMhj+
  112. S1lunnLdgxp46YyuTMYAzj88eCGurRtzBsdxxlGAsioEnZGebEqAHQbieKq/DO6I
  113. MOMZHMSVBDqyyIx3assGlxSX8BSFW0lhKyT7i0XqnAgCJ9f/5oq0SbFGq+01VQb7
  114. jIx9PbcYJORxsE0JG/CXXPv27bRtQXsudkWGSYvC0NLOgk4z8+kQpQtyFh16lujq
  115. WRwMeriu0qNDjCa1/eHIKDovhAZ3GyO5/9m1tBlUZXN0IFVzZXIgPHRlc3RAdGVz
  116. dC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAFiEEjrR8
  117. MQ4fJK44PYMvfN2AClLmXiYFAmDcEZEACgkQfN2AClLmXibZzgv/ZfeTpTuqQE1W
  118. C1jT5KpQExnt0BizTX0U7BvSn8Fr6VXTyol6kYc3u71GLUuJyawCLtIzOXqOXJvz
  119. bjcZqymcMADuftKcfMy513FhbF6MhdVd6QoeBP6+7/xXOFJCi+QVYF7SQ2h7K1Qm
  120. +yXOiAMgSxhCZQGPBNJLlDUOd47nSIMANvlumFtmLY/1FD7RpG7WQWjeX1mnxNTw
  121. hUU+Yv7GuFc/JprXCIYqHbhWfvXyVtae2ZK4xuVi5eqwA2RfggOVM7drb+CgPhG0
  122. +9aEDDLOZqVi65wK7J73Puo3rFTbPQMljxw5s27rWqF+vB6hhVdJOPNomWy3naPi
  123. k5MW0mhsacASz1WYndpZz+XaQTq/wJF5HUyyeUWJ0vlOEdwx021PHcqSTyfNnkjD
  124. KncrE21t2sxWRsgGDETxIwkd2b2HNGAvveUD0ffFK/oJHGSXjAERFGc3wuiDj3mQ
  125. BvKm4wt4QF9ZMrCdhMAA6ax5kfEUqQR4ntmrJk/khp/mV7TILaI4nQVYBGBjIyIB
  126. DADghIo9wXnRxzfdDTvwnP8dHpLAIaPokgdpyLswqUCixJWiW2xcV6weUjEWwH6n
  127. eN/t1uZYVehbrotxVPla+MPvzhxp6/cmG+2lhzEBOp6zRwnL1wIB6HoKJfpREhyM
  128. c8rLR0zMso1L1bJTyydvnu07a7BWo3VWKjilb0rEZZUSD/2hidx5HxMOJSoidLWe
  129. d/PPuv6yht3NtA4UThlcfldm9G6PbqCdm1kMEKAkq0wVJvhPJ6gEFRNJimgygfUw
  130. MDFXEIhQtxjgdV5Uoz3O5452VLoRsDlgpi3E0WDGj7WXDaO5uSU0T5aJgVgHCP/f
  131. xZhHuQFk2YYIl5nCBpOZyWWI0IKmscTuEwzpkhICQDQFvcMZ5ibsl7wA2P7YTrQf
  132. FDMjjzuaK80GYPfxDFlyKUyLqFt8w/QzsZLDLX7+jxIEpbRAaMw/JsWqm5BMxxbS
  133. 3CIQiS5S3oSKDsNINelqWFfwvLhvlQra8gIxyNTlek25OdgG66BiiX+seH8A/ql+
  134. F+MAEQEAAQAL/1jrNSLjMt9pwo6qFKClVQZP2vf7+sH7v7LeHIDXr3EnYUnVYnOq
  135. B1FU5PspTp/+J9W25DB9CZLx7Gj8qeslFdiuLSOoIBB4RCToB3kAoeTH0DHqW/Gs
  136. hFTrmJkuDp9zpo/ek6SIXJx5rHAyR9KVw0fizQprH2f6PcgLbTWeM61dJuqowmg3
  137. 7eCOyIKv7VQvFqEhYokLD+JNmrvg+Htg0DXGvdjRjAwPf/NezEXpj67a6cHTp1/C
  138. hwp7pevG+3fTxaCJFesl5/TxxtnaBLE8m2uo/S6Hxgn9l0edonroe1QlTjEqGLy2
  139. 7qi2z5Rem+v6GWNDRgvAWur13v8FNdyduHlioG/NgRsU9mE2MYeFsfi3cfNpJQp/
  140. wC9PSCIXrb/45mkS8KyjZpCrIPB9RV/m0MREq01TPom7rstZc4A1pD0Ot7AtUYS3
  141. e95zLyEmeLziPJ9fV4fgPmEudDr1uItnmV0LOskKlpg5sc0hhdrwYoobfkKt2dx6
  142. DqfMlcM1ZkUbLQYA4jwfpFJG4HmYvjL2xCJxM0ycjvMbqFN+4UjgYWVlRfOrm1V4
  143. Op86FjbRbV6OOCNhznotAg7mul4xtzrrTkK8o3YLBeJseDgl4AWuzXtNa9hE0XpK
  144. 9gJoEHUuBOOsamVh2HpXESFyE5CclOV7JSh541TlZKfnqfZYCg4JSbp0UijkawCL
  145. 5bJJUiGGMD9rZUxIAKQO1DvUEzptS7Jl6S3y5sbIIhilp4KfYWbSk3PPu9CnZD5b
  146. LhEQp0elxnb/IL8PBgD+DpTeC8unkGKXUpbe9x0ISI6V1D6FmJq/FxNg7fMa3QCh
  147. fGiAyoTm80ZETynj+blRaDO3gY4lTLa3Opubof1EqK2QmwXmpyvXEZNYcQfQ2CCS
  148. GOWUCK8jEQamUPf1PWndZXJUmROI1WukhlL71V/ir6zQeVCv1wcwPwclJPnAe87u
  149. pEklnCYpvsEldwHUX9u0BWzoULIEsi+ddtHmT0KTeF/DHRy0W15jIHbjFqhqckj1
  150. /6fmr7l7kIi/kN4vWe0F/0Q8IXX+cVMgbl3aIuaGcvENLGcoAsAtPGx88SfRgmfu
  151. HK64Y7hx1m+Bo215rxJzZRjqHTBPp0BmCi+JKkaavIBrYRbsx20gveI4dzhLcUhB
  152. kiT4Q7oz0/VbGHS1CEf9KFeS/YOGj57s4yHauSVI0XdP9kBRTWmXvBkzsooB2cKH
  153. hwhUN7iiT1k717CiTNUT6Q/pcPFCyNuMoBBGQTU206JEgIjQvI3f8xMUMGmGVVQz
  154. 9/k716ycnhb2JZ/Q/AyQIeHJiQG2BBgBCAAgAhsMFiEEjrR8MQ4fJK44PYMvfN2A
  155. ClLmXiYFAmDcEa4ACgkQfN2AClLmXiZxxQv/XaMN0hPCygtrQMbCsTNb34JbvJzh
  156. hngPuUAfTbRHrR3YeATyQofNbL0DD3fvfzeFF8qESqvzCSZxS6dYsXPd4MCJTzlp
  157. zYBZ2X0sOrgDqZvqCZKN72RKgdk0KvthdzAxsIm2dfcQOxxowXMxhJEXZmsFpusx
  158. jKJxOcrfVRjXJnh9isY0NpCoqMQ+3k3wDJ3VGEHV7G+A+vFkWfbLJF5huQ96uaH9
  159. Uc+jUsREUH9G82ZBqpoioEN8Ith4VXpYnKdTMonK/+ZcyeraJZhXrvbjnEomKdzU
  160. 0pu4bt1HlLR3dcnpjN7b009MBf2xLgEfQk2nPZ4zzY+tDkxygtPllaB4dldFjBpT
  161. j7Q+t49sWMjmlJUbLlHfuJ7nUUK5+cGjBsWVObAEcyfemHWCTVFnEa2BJslGC08X
  162. rFcjRRcMEr9ct4551QFBHsv3O/Wp3/wqczYgE9itSnGT05w+4vLt4smG+dnEHjRJ
  163. brMb2upTHa+kjktjdO96/BgSnKYqmNmPB/qB
  164. =ivA/
  165. -----END PGP PRIVATE KEY BLOCK-----
  166. """
  167. DEFAULT_KEY_ID = "8EB47C310E1F24AE383D832F7CDD800A52E65E26"
  168. NON_DEFAULT_KEY = """
  169. -----BEGIN PGP PRIVATE KEY BLOCK-----
  170. lQVYBGBjI0ABDADGWBRp+t02emfzUlhrc1psqIhhecFm6Em0Kv33cfDpnfoMF1tK
  171. Yy/4eLYIR7FmpdbFPcDThFNHbXJzBi00L1mp0XQE2l50h/2bDAAgREdZ+NVo5a7/
  172. RSZjauNU1PxW6pnXMehEh1tyIQmV78jAukaakwaicrpIenMiFUN3fAKHnLuFffA6
  173. t0f3LqJvTDhUw/o2vPgw5e6UDQhA1C+KTv1KXVrhJNo88a3hZqCZ76z3drKR411Q
  174. zYgT4DUb8lfnbN+z2wfqT9oM5cegh2k86/mxAA3BYOeQrhmQo/7uhezcgbxtdGZr
  175. YlbuaNDTSBrn10ZoaxLPo2dJe2zWxgD6MpvsGU1w3tcRW508qo/+xoWp2/pDzmok
  176. +uhOh1NAj9zB05VWBz1r7oBgCOIKpkD/LD4VKq59etsZ/UnrYDwKdXWZp7uhshkU
  177. M7N35lUJcR76a852dlMdrgpmY18+BP7+o7M+5ElHTiqQbMuE1nHTg8RgVpdV+tUx
  178. dg6GWY/XHf5asm8AEQEAAQAL/A85epOp+GnymmEQfI3+5D178D//Lwu9n86vECB6
  179. xAHCqQtdjZnXpDp/1YUsL59P8nzgYRk7SoMskQDoQ/cB/XFuDOhEdMSgHaTVlnrj
  180. ktCCq6rqGnUosyolbb64vIfVaSqd/5SnCStpAsnaBoBYrAu4ZmV4xfjDQWwn0q5s
  181. u+r56mD0SkjPgbwk/b3qTVagVmf2OFzUgWwm1e/X+bA1oPag1NV8VS4hZPXswT4f
  182. qhiyqUFOgP6vUBcqehkjkIDIl/54xII7/P5tp3LIZawvIXqHKNTqYPCqaCqCj+SL
  183. vMYDIb6acjescfZoM71eAeHAANeFZzr/rwfBT+dEP6qKmPXNcvgE11X44ZCr04nT
  184. zOV/uDUifEvKT5qgtyJpSFEVr7EXubJPKoNNhoYqq9z1pYU7IedX5BloiVXKOKTY
  185. 0pk7JkLqf3g5fYtXh/wol1owemITJy5V5PgaqZvk491LkI6S+kWC7ANYUg+TDPIW
  186. afxW3E5N1CYV6XDAl0ZihbLcoQYAy0Ky/p/wayWKePyuPBLwx9O89GSONK2pQljZ
  187. yaAgxPQ5/i1vx6LIMg7k/722bXR9W3zOjWOin4eatPM3d2hkG96HFvnBqXSmXOPV
  188. 03Xqy1/B5Tj8E9naLKUHE/OBQEc363DgLLG9db5HfPlpAngeppYPdyWkhzXyzkgS
  189. PylaE5eW3zkdjEbYJ6RBTecTZEgBaMvJNPdWbn//frpP7kGvyiCg5Es+WjLInUZ6
  190. 0sdifcNTCewzLXK80v/y5mVOdJhPBgD5zs9cYdyiQJayqAuOr+He1eMHMVUbm9as
  191. qBmPrst398eBW9ZYF7eBfTSlUf6B+WnvyLKEGsUf/7IK0EWDlzoBuWzWiHjUAY1g
  192. m9eTV2MnvCCCefqCErWwfFo2nWOasAZA9sKD+ICIBY4tbtvSl4yfLBzTMwSvs9ZS
  193. K1ocPSYUnhm2miSWZ8RLZPH7roHQasNHpyq/AX7DahFf2S/bJ+46ZGZ8Pigr7hA+
  194. MjmpQ4qVdb5SaViPmZhAKO+PjuCHm+EF/2H0Y3Sl4eXgxZWoQVOUeXdWg9eMfYrj
  195. XDtUMIFppV/QxbeztZKvJdfk64vt/crvLsOp0hOky9cKwY89r4QaHfexU3qR+qDq
  196. UlMvR1rHk7dS5HZAtw0xKsFJNkuDxvBkMqv8Los8zp3nUl+U99dfZOArzNkW38wx
  197. FPa0ixkC9za2BkDrWEA8vTnxw0A2upIFegDUhwOByrSyfPPnG3tKGeqt3Izb/kDk
  198. Q9vmo+HgxBOguMIvlzbBfQZwtbd/gXzlvPqCtCJBbm90aGVyIFRlc3QgVXNlciA8
  199. dGVzdDJAdGVzdC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4B
  200. AheAFiEEapM5P1DF5qzT1vtFuTYhLttOFMAFAmDcEeEACgkQuTYhLttOFMDe0Qv/
  201. Qx/bzXztJ3BCc+CYAVDx7Kr37S68etwwLgcWzhG+CDeMB5F/QE+upKgxy2iaqQFR
  202. mxfOMgf/TIQkUfkbaASzK1LpnesYO85pk7XYjoN1bYEHiXTkeW+bgB6aJIxrRmO2
  203. SrWasdBC/DsI3Mrya8YMt/TiHC6VpRJVxCe5vv7/kZC4CXrgTBnZocXx/YXimbke
  204. poPMVdbvhYh6N0aGeS38jRKgyN10KXmhDTAQDwseVFavBWAjVfx3DEwjtK2Z2GbA
  205. aL8JvAwRtqiPFkDMIKPL4UwxtXFws8SpMt6juroUkNyf6+BxNWYqmwXHPy8zCJAb
  206. xkxIJMlEc+s7qQsP3fILOo8Xn+dVzJ5sa5AoARoXm1GMjsdqaKAzq99Dic/dHnaQ
  207. Civev1PQsdwlYW2C2wNXNeIrxMndbDMFfNuZ6BnGHWJ/wjcp/pFs4YkyyZN8JH7L
  208. hP2FO4Jgham3AuP13kC3Ivea7V6hR8QNcDZRwFPOMIX4tXwQv1T72+7DZGaA25O7
  209. nQVXBGBjI0ABDADJMBYIcG0Yil9YxFs7aYzNbd7alUAr89VbY8eIGPHP3INFPM1w
  210. lBQCu+4j6xdEbhMpppLBZ9A5TEylP4C6qLtPa+oLtPeuSw8gHDE10XE4lbgPs376
  211. rL60XdImSOHhiduACUefYjqpcmFH9Bim1CC+koArYrSQJQx1Jri+OpnTaL/8UID0
  212. KzD/kEgMVGlHIVj9oJmb4+j9pW8I/g0wDSnIaEKFMxqu6SIVJ1GWj+MUMvZigjLC
  213. sNCZd7PnbOC5VeU3SsXj6he74Jx0AmGMPWIHi9M0DjHO5d1cCbXTnud8xxM1bOh4
  214. 7aCTnMK5cVyIr+adihgJpVVhrndSM8aklBPRgtozrGNCgF2CkYU2P1blxfloNr/8
  215. UZpM83o+s1aObBszzRNLxnpNORqoLqjfPtLEPQnagxE+4EapCq0NZ/x6yO5VTwwp
  216. NljdFAEk40uGuKyn1QA3uNMHy5DlpLl+tU7t1KEovdZ+OVYsYKZhVzw0MTpKogk9
  217. JI7AN0q62ronPskAEQEAAQAL+O8BUSt1ZCVjPSIXIsrR+ZOSkszZwgJ1CWIoh0IH
  218. YD2vmcMHGIhFYgBdgerpvhptKhaw7GcXDScEnYkyh5s4GE2hxclik1tbj/x1gYCN
  219. 8BNoyeDdPFxQG73qN12D99QYEctpOsz9xPLIDwmL0j1ehAfhwqHIAPm9Ca+i8JYM
  220. x/F+35S/jnKDXRI+NVlwbiEyXKXxxIqNlpy9i8sDBGexO5H5Sg0zSN/B1duLekGD
  221. biDw6gLc6bCgnS+0JOUpU07Z2fccMOY9ncjKGD2uIb/ePPUaek92GCQyq0eorCIV
  222. brcQsRc5sSsNtnRKQTQtxioROeDg7kf2oWySeHTswlXW/219ihrSXgteHJd+rPm7
  223. DYLEeGLRny8bRKv8rQdAtApHaJE4dAATXeY4RYo4NlXHYaztGYtU6kiM/3zCfWAe
  224. 9Nn+Wh9jMTZrjefUCagS5r6ZqAh7veNo/vgIGaCLh0a1Ypa0Yk9KFrn3LYEM3zgk
  225. 3m3bn+7qgy5cUYXoJ3DGJJEhBgDPonpW0WElqLs5ZMem1ha85SC38F0IkAaSuzuz
  226. v3eORiKWuyJGF32Q2XHa1RHQs1JtUKd8rxFer3b8Oq71zLz6JtVc9dmRudvgcJYX
  227. 0PC11F6WGjZFSSp39dajFp0A5DKUs39F3w7J1yuDM56TDIN810ywufGAHARY1pZb
  228. UJAy/dTqjFnCbNjpAakor3hVzqxcmUG+7Y2X9c2AGncT1MqAQC3M8JZcuZvkK8A9
  229. cMk8B914ryYE7VsZMdMhyTwHmykGAPgNLLa3RDETeGeGCKWI+ZPOoU0ib5JtJZ1d
  230. P3tNwfZKuZBZXKW9gqYqyBa/qhMip84SP30pr/TvulcdAFC759HK8sQZyJ6Vw24P
  231. c+5ssRxrQUEw1rvJPWhmQCmCOZHBMQl5T6eaTOpR5u3aUKTMlxPKhK9eC1dCSTnI
  232. /nyL8An3VKnLy+K/LI42YGphBVLLJmBewuTVDIJviWRdntiG8dElyEJMOywUltk3
  233. 2CEmqgsD9tPO8rXZjnMrMn3gfsiaoQYA6/6/e2utkHr7gAoWBgrBBdqVHsvqh5Ro
  234. 2DjLAOpZItO/EdCJfDAmbTYOa04535sBDP2tcH/vipPOPpbr1Y9Y/mNsKCulNxed
  235. yqAmEkKOcerLUP5UHju0AB6VBjHJFdU2mqT+UjPyBk7WeKXgFomyoYMv3KpNOFWR
  236. xi0Xji4kKHbttA6Hy3UcGPr9acyUAlDYeKmxbSUYIPhw32bbGrX9+F5YriTufRsG
  237. 3jftQVo9zqdcQSD/5pUTMn3EYbEcohYB2YWJAbYEGAEIACACGwwWIQRqkzk/UMXm
  238. rNPW+0W5NiEu204UwAUCYNwR6wAKCRC5NiEu204UwOPnC/92PgB1c3h9FBXH1maz
  239. g29fndHIHH65VLgqMiQ7HAMojwRlT5Xnj5tdkCBmszRkv5vMvdJRa3ZY8Ed/Inqr
  240. hxBFNzpjqX4oj/RYIQLKXWWfkTKYVLJFZFPCSo00jesw2gieu3Ke/Yy4gwhtNodA
  241. v+s6QNMvffTW/K3XNrWDB0E7/LXbdidzhm+MBu8ov2tuC3tp9liLICiE1jv/2xT4
  242. CNSO6yphmk1/1zEYHS/mN9qJ2csBmte2cdmGyOcuVEHk3pyINNMDOamaURBJGRwF
  243. XB5V7gTKUFU4jCp3chywKrBHJHxGGDUmPBmZtDtfWAOgL32drK7/KUyzZL/WO7Fj
  244. akOI0hRDFOcqTYWL20H7+hAiX3oHMP7eou3L5C7wJ9+JMcACklN/WMjG9a536DFJ
  245. 4UgZ6HyKPP+wy837Hbe8b25kNMBwFgiaLR0lcgzxj7NyQWjVCMOEN+M55tRCjvL6
  246. ya6JVZCRbMXfdCy8lVPgtNQ6VlHaj8Wvnn2FLbWWO2n2r3s=
  247. =9zU5
  248. -----END PGP PRIVATE KEY BLOCK-----
  249. """
  250. NON_DEFAULT_KEY_ID = "6A93393F50C5E6ACD3D6FB45B936212EDB4E14C0"
  251. def setUp(self) -> None:
  252. super().setUp()
  253. self.gpg_dir = os.path.join(self.test_dir, "gpg")
  254. os.mkdir(self.gpg_dir, mode=0o700)
  255. # Ignore errors when deleting GNUPGHOME, because of race conditions
  256. # (e.g. the gpg-agent socket having been deleted). See
  257. # https://github.com/jelmer/dulwich/issues/1000
  258. self.addCleanup(shutil.rmtree, self.gpg_dir, ignore_errors=True)
  259. self.overrideEnv("GNUPGHOME", self.gpg_dir)
  260. def import_default_key(self) -> None:
  261. subprocess.run(
  262. ["gpg", "--import"],
  263. stdout=subprocess.DEVNULL,
  264. stderr=subprocess.DEVNULL,
  265. input=PorcelainGpgTestCase.DEFAULT_KEY,
  266. text=True,
  267. )
  268. def import_non_default_key(self) -> None:
  269. subprocess.run(
  270. ["gpg", "--import"],
  271. stdout=subprocess.DEVNULL,
  272. stderr=subprocess.DEVNULL,
  273. input=PorcelainGpgTestCase.NON_DEFAULT_KEY,
  274. text=True,
  275. )
  276. class ArchiveTests(PorcelainTestCase):
  277. """Tests for the archive command."""
  278. def test_simple(self) -> None:
  279. c1, c2, c3 = build_commit_graph(
  280. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  281. )
  282. self.repo.refs[b"refs/heads/master"] = c3.id
  283. out = BytesIO()
  284. err = BytesIO()
  285. porcelain.archive(
  286. self.repo.path, b"refs/heads/master", outstream=out, errstream=err
  287. )
  288. self.assertEqual(b"", err.getvalue())
  289. tf = tarfile.TarFile(fileobj=out)
  290. self.addCleanup(tf.close)
  291. self.assertEqual([], tf.getnames())
  292. class UpdateServerInfoTests(PorcelainTestCase):
  293. def test_simple(self) -> None:
  294. c1, c2, c3 = build_commit_graph(
  295. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  296. )
  297. self.repo.refs[b"refs/heads/foo"] = c3.id
  298. porcelain.update_server_info(self.repo.path)
  299. self.assertTrue(
  300. os.path.exists(os.path.join(self.repo.controldir(), "info", "refs"))
  301. )
  302. class CommitTests(PorcelainTestCase):
  303. def test_custom_author(self) -> None:
  304. c1, c2, c3 = build_commit_graph(
  305. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  306. )
  307. self.repo.refs[b"refs/heads/foo"] = c3.id
  308. sha = porcelain.commit(
  309. self.repo.path,
  310. message=b"Some message",
  311. author=b"Joe <joe@example.com>",
  312. committer=b"Bob <bob@example.com>",
  313. )
  314. self.assertIsInstance(sha, bytes)
  315. self.assertEqual(len(sha), 40)
  316. def test_unicode(self) -> None:
  317. c1, c2, c3 = build_commit_graph(
  318. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  319. )
  320. self.repo.refs[b"refs/heads/foo"] = c3.id
  321. sha = porcelain.commit(
  322. self.repo.path,
  323. message="Some message",
  324. author="Joe <joe@example.com>",
  325. committer="Bob <bob@example.com>",
  326. )
  327. self.assertIsInstance(sha, bytes)
  328. self.assertEqual(len(sha), 40)
  329. def test_no_verify(self) -> None:
  330. if os.name != "posix":
  331. self.skipTest("shell hook tests requires POSIX shell")
  332. self.assertTrue(os.path.exists("/bin/sh"))
  333. hooks_dir = os.path.join(self.repo.controldir(), "hooks")
  334. os.makedirs(hooks_dir, exist_ok=True)
  335. self.addCleanup(shutil.rmtree, hooks_dir)
  336. c1, c2, c3 = build_commit_graph(
  337. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  338. )
  339. hook_fail = "#!/bin/sh\nexit 1"
  340. # hooks are executed in pre-commit, commit-msg order
  341. # test commit-msg failure first, then pre-commit failure, then
  342. # no_verify to skip both hooks
  343. commit_msg = os.path.join(hooks_dir, "commit-msg")
  344. with open(commit_msg, "w") as f:
  345. f.write(hook_fail)
  346. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  347. with self.assertRaises(CommitError):
  348. porcelain.commit(
  349. self.repo.path,
  350. message="Some message",
  351. author="Joe <joe@example.com>",
  352. committer="Bob <bob@example.com>",
  353. )
  354. pre_commit = os.path.join(hooks_dir, "pre-commit")
  355. with open(pre_commit, "w") as f:
  356. f.write(hook_fail)
  357. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  358. with self.assertRaises(CommitError):
  359. porcelain.commit(
  360. self.repo.path,
  361. message="Some message",
  362. author="Joe <joe@example.com>",
  363. committer="Bob <bob@example.com>",
  364. )
  365. sha = porcelain.commit(
  366. self.repo.path,
  367. message="Some message",
  368. author="Joe <joe@example.com>",
  369. committer="Bob <bob@example.com>",
  370. no_verify=True,
  371. )
  372. self.assertIsInstance(sha, bytes)
  373. self.assertEqual(len(sha), 40)
  374. def test_timezone(self) -> None:
  375. c1, c2, c3 = build_commit_graph(
  376. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  377. )
  378. self.repo.refs[b"refs/heads/foo"] = c3.id
  379. sha = porcelain.commit(
  380. self.repo.path,
  381. message="Some message",
  382. author="Joe <joe@example.com>",
  383. author_timezone=18000,
  384. committer="Bob <bob@example.com>",
  385. commit_timezone=18000,
  386. )
  387. self.assertIsInstance(sha, bytes)
  388. self.assertEqual(len(sha), 40)
  389. commit = self.repo.get_object(sha)
  390. assert isinstance(commit, Commit)
  391. self.assertEqual(commit._author_timezone, 18000)
  392. self.assertEqual(commit._commit_timezone, 18000)
  393. self.overrideEnv("GIT_AUTHOR_DATE", "1995-11-20T19:12:08-0501")
  394. self.overrideEnv("GIT_COMMITTER_DATE", "1995-11-20T19:12:08-0501")
  395. sha = porcelain.commit(
  396. self.repo.path,
  397. message="Some message",
  398. author="Joe <joe@example.com>",
  399. committer="Bob <bob@example.com>",
  400. )
  401. self.assertIsInstance(sha, bytes)
  402. self.assertEqual(len(sha), 40)
  403. commit = self.repo.get_object(sha)
  404. assert isinstance(commit, Commit)
  405. self.assertEqual(commit._author_timezone, -18060)
  406. self.assertEqual(commit._commit_timezone, -18060)
  407. self.overrideEnv("GIT_AUTHOR_DATE", None)
  408. self.overrideEnv("GIT_COMMITTER_DATE", None)
  409. local_timezone = time.localtime().tm_gmtoff
  410. sha = porcelain.commit(
  411. self.repo.path,
  412. message="Some message",
  413. author="Joe <joe@example.com>",
  414. committer="Bob <bob@example.com>",
  415. )
  416. self.assertIsInstance(sha, bytes)
  417. self.assertEqual(len(sha), 40)
  418. commit = self.repo.get_object(sha)
  419. assert isinstance(commit, Commit)
  420. self.assertEqual(commit._author_timezone, local_timezone)
  421. self.assertEqual(commit._commit_timezone, local_timezone)
  422. @skipIf(
  423. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  424. "gpgme not easily available or supported on Windows and PyPy",
  425. )
  426. class CommitSignTests(PorcelainGpgTestCase):
  427. def test_default_key(self) -> None:
  428. c1, c2, c3 = build_commit_graph(
  429. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  430. )
  431. self.repo.refs[b"HEAD"] = c3.id
  432. cfg = self.repo.get_config()
  433. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  434. self.import_default_key()
  435. sha = porcelain.commit(
  436. self.repo.path,
  437. message="Some message",
  438. author="Joe <joe@example.com>",
  439. committer="Bob <bob@example.com>",
  440. signoff=True,
  441. )
  442. self.assertIsInstance(sha, bytes)
  443. self.assertEqual(len(sha), 40)
  444. commit = self.repo.get_object(sha)
  445. assert isinstance(commit, Commit)
  446. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  447. commit.verify()
  448. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  449. self.import_non_default_key()
  450. self.assertRaises(
  451. gpg.errors.MissingSignatures,
  452. commit.verify,
  453. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  454. )
  455. assert isinstance(commit, Commit)
  456. commit.committer = b"Alice <alice@example.com>"
  457. self.assertRaises(
  458. gpg.errors.BadSignatures,
  459. commit.verify,
  460. )
  461. def test_non_default_key(self) -> None:
  462. c1, c2, c3 = build_commit_graph(
  463. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  464. )
  465. self.repo.refs[b"HEAD"] = c3.id
  466. cfg = self.repo.get_config()
  467. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  468. self.import_non_default_key()
  469. sha = porcelain.commit(
  470. self.repo.path,
  471. message="Some message",
  472. author="Joe <joe@example.com>",
  473. committer="Bob <bob@example.com>",
  474. signoff=PorcelainGpgTestCase.NON_DEFAULT_KEY_ID,
  475. )
  476. self.assertIsInstance(sha, bytes)
  477. self.assertEqual(len(sha), 40)
  478. commit = self.repo.get_object(sha)
  479. assert isinstance(commit, Commit)
  480. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  481. commit.verify()
  482. def test_sign_uses_config_signingkey(self) -> None:
  483. """Test that sign=True uses user.signingKey from config."""
  484. c1, c2, c3 = build_commit_graph(
  485. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  486. )
  487. self.repo.refs[b"HEAD"] = c3.id
  488. # Set up user.signingKey in config
  489. cfg = self.repo.get_config()
  490. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  491. cfg.write_to_path()
  492. self.import_default_key()
  493. # Create commit with sign=True (should use signingKey from config)
  494. sha = porcelain.commit(
  495. self.repo.path,
  496. message="Signed with configured key",
  497. author="Joe <joe@example.com>",
  498. committer="Bob <bob@example.com>",
  499. signoff=True, # This should read user.signingKey from config
  500. )
  501. self.assertIsInstance(sha, bytes)
  502. self.assertEqual(len(sha), 40)
  503. commit = self.repo.get_object(sha)
  504. assert isinstance(commit, Commit)
  505. # Verify the commit is signed with the configured key
  506. commit.verify()
  507. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  508. def test_commit_gpg_sign_config_enabled(self) -> None:
  509. """Test that commit.gpgSign=true automatically signs commits."""
  510. c1, c2, c3 = build_commit_graph(
  511. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  512. )
  513. self.repo.refs[b"HEAD"] = c3.id
  514. # Set up user.signingKey and commit.gpgSign in config
  515. cfg = self.repo.get_config()
  516. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  517. cfg.set(("commit",), "gpgSign", True)
  518. cfg.write_to_path()
  519. self.import_default_key()
  520. # Create commit without explicit signoff parameter (should auto-sign due to config)
  521. sha = porcelain.commit(
  522. self.repo.path,
  523. message="Auto-signed commit",
  524. author="Joe <joe@example.com>",
  525. committer="Bob <bob@example.com>",
  526. # No signoff parameter - should use commit.gpgSign config
  527. )
  528. self.assertIsInstance(sha, bytes)
  529. self.assertEqual(len(sha), 40)
  530. commit = self.repo.get_object(sha)
  531. assert isinstance(commit, Commit)
  532. # Verify the commit is signed due to config
  533. commit.verify()
  534. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  535. def test_commit_gpg_sign_config_disabled(self) -> None:
  536. """Test that commit.gpgSign=false does not sign commits."""
  537. c1, c2, c3 = build_commit_graph(
  538. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  539. )
  540. self.repo.refs[b"HEAD"] = c3.id
  541. # Set up user.signingKey and commit.gpgSign=false in config
  542. cfg = self.repo.get_config()
  543. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  544. cfg.set(("commit",), "gpgSign", False)
  545. cfg.write_to_path()
  546. self.import_default_key()
  547. # Create commit without explicit signoff parameter (should not sign)
  548. sha = porcelain.commit(
  549. self.repo.path,
  550. message="Unsigned commit",
  551. author="Joe <joe@example.com>",
  552. committer="Bob <bob@example.com>",
  553. # No signoff parameter - should use commit.gpgSign=false config
  554. )
  555. self.assertIsInstance(sha, bytes)
  556. self.assertEqual(len(sha), 40)
  557. commit = self.repo.get_object(sha)
  558. assert isinstance(commit, Commit)
  559. # Verify the commit is not signed
  560. self.assertIsNone(commit._gpgsig)
  561. def test_commit_gpg_sign_config_no_signing_key(self) -> None:
  562. """Test that commit.gpgSign=true works without user.signingKey (uses default)."""
  563. c1, c2, c3 = build_commit_graph(
  564. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  565. )
  566. self.repo.refs[b"HEAD"] = c3.id
  567. # Set up commit.gpgSign but no user.signingKey
  568. cfg = self.repo.get_config()
  569. cfg.set(("commit",), "gpgSign", True)
  570. cfg.write_to_path()
  571. self.import_default_key()
  572. # Create commit without explicit signoff parameter (should auto-sign with default key)
  573. sha = porcelain.commit(
  574. self.repo.path,
  575. message="Default signed commit",
  576. author="Joe <joe@example.com>",
  577. committer="Bob <bob@example.com>",
  578. # No signoff parameter - should use commit.gpgSign config with default key
  579. )
  580. self.assertIsInstance(sha, bytes)
  581. self.assertEqual(len(sha), 40)
  582. commit = self.repo.get_object(sha)
  583. assert isinstance(commit, Commit)
  584. # Verify the commit is signed with default key
  585. commit.verify()
  586. def test_explicit_signoff_overrides_config(self) -> None:
  587. """Test that explicit signoff parameter overrides commit.gpgSign config."""
  588. c1, c2, c3 = build_commit_graph(
  589. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  590. )
  591. self.repo.refs[b"HEAD"] = c3.id
  592. # Set up commit.gpgSign=false but explicitly pass signoff=True
  593. cfg = self.repo.get_config()
  594. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  595. cfg.set(("commit",), "gpgSign", False)
  596. cfg.write_to_path()
  597. self.import_default_key()
  598. # Create commit with explicit signoff=True (should override config)
  599. sha = porcelain.commit(
  600. self.repo.path,
  601. message="Explicitly signed commit",
  602. author="Joe <joe@example.com>",
  603. committer="Bob <bob@example.com>",
  604. signoff=True, # This should override commit.gpgSign=false
  605. )
  606. self.assertIsInstance(sha, bytes)
  607. self.assertEqual(len(sha), 40)
  608. commit = self.repo.get_object(sha)
  609. assert isinstance(commit, Commit)
  610. # Verify the commit is signed despite config=false
  611. commit.verify()
  612. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  613. def test_explicit_false_disables_signing(self) -> None:
  614. """Test that explicit signoff=False disables signing even with config=true."""
  615. c1, c2, c3 = build_commit_graph(
  616. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  617. )
  618. self.repo.refs[b"HEAD"] = c3.id
  619. # Set up commit.gpgSign=true but explicitly pass signoff=False
  620. cfg = self.repo.get_config()
  621. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  622. cfg.set(("commit",), "gpgSign", True)
  623. cfg.write_to_path()
  624. self.import_default_key()
  625. # Create commit with explicit signoff=False (should disable signing)
  626. sha = porcelain.commit(
  627. self.repo.path,
  628. message="Explicitly unsigned commit",
  629. author="Joe <joe@example.com>",
  630. committer="Bob <bob@example.com>",
  631. signoff=False, # This should override commit.gpgSign=true
  632. )
  633. self.assertIsInstance(sha, bytes)
  634. self.assertEqual(len(sha), 40)
  635. commit = self.repo.get_object(sha)
  636. assert isinstance(commit, Commit)
  637. # Verify the commit is NOT signed despite config=true
  638. self.assertIsNone(commit._gpgsig)
  639. class TimezoneTests(PorcelainTestCase):
  640. def put_envs(self, value) -> None:
  641. self.overrideEnv("GIT_AUTHOR_DATE", value)
  642. self.overrideEnv("GIT_COMMITTER_DATE", value)
  643. def fallback(self, value) -> None:
  644. self.put_envs(value)
  645. self.assertRaises(porcelain.TimezoneFormatError, porcelain.get_user_timezones)
  646. def test_internal_format(self) -> None:
  647. self.put_envs("0 +0500")
  648. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  649. def test_rfc_2822(self) -> None:
  650. self.put_envs("Mon, 20 Nov 1995 19:12:08 -0500")
  651. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  652. self.put_envs("Mon, 20 Nov 1995 19:12:08")
  653. self.assertTupleEqual((0, 0), porcelain.get_user_timezones())
  654. def test_iso8601(self) -> None:
  655. self.put_envs("1995-11-20T19:12:08-0501")
  656. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  657. self.put_envs("1995-11-20T19:12:08+0501")
  658. self.assertTupleEqual((18060, 18060), porcelain.get_user_timezones())
  659. self.put_envs("1995-11-20T19:12:08-05:01")
  660. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  661. self.put_envs("1995-11-20 19:12:08-05")
  662. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  663. # https://github.com/git/git/blob/96b2d4fa927c5055adc5b1d08f10a5d7352e2989/t/t6300-for-each-ref.sh#L128
  664. self.put_envs("2006-07-03 17:18:44 +0200")
  665. self.assertTupleEqual((7200, 7200), porcelain.get_user_timezones())
  666. def test_missing_or_malformed(self) -> None:
  667. # TODO: add more here
  668. self.fallback("0 + 0500")
  669. self.fallback("a +0500")
  670. self.fallback("1995-11-20T19:12:08")
  671. self.fallback("1995-11-20T19:12:08-05:")
  672. self.fallback("1995.11.20")
  673. self.fallback("11/20/1995")
  674. self.fallback("20.11.1995")
  675. def test_different_envs(self) -> None:
  676. self.overrideEnv("GIT_AUTHOR_DATE", "0 +0500")
  677. self.overrideEnv("GIT_COMMITTER_DATE", "0 +0501")
  678. self.assertTupleEqual((18000, 18060), porcelain.get_user_timezones())
  679. def test_no_envs(self) -> None:
  680. local_timezone = time.localtime().tm_gmtoff
  681. self.put_envs("0 +0500")
  682. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  683. self.overrideEnv("GIT_COMMITTER_DATE", None)
  684. self.assertTupleEqual((18000, local_timezone), porcelain.get_user_timezones())
  685. self.put_envs("0 +0500")
  686. self.overrideEnv("GIT_AUTHOR_DATE", None)
  687. self.assertTupleEqual((local_timezone, 18000), porcelain.get_user_timezones())
  688. self.put_envs("0 +0500")
  689. self.overrideEnv("GIT_AUTHOR_DATE", None)
  690. self.overrideEnv("GIT_COMMITTER_DATE", None)
  691. self.assertTupleEqual(
  692. (local_timezone, local_timezone), porcelain.get_user_timezones()
  693. )
  694. class CleanTests(PorcelainTestCase):
  695. def put_files(self, tracked, ignored, untracked, empty_dirs) -> None:
  696. """Put the described files in the wd."""
  697. all_files = tracked | ignored | untracked
  698. for file_path in all_files:
  699. abs_path = os.path.join(self.repo.path, file_path)
  700. # File may need to be written in a dir that doesn't exist yet, so
  701. # create the parent dir(s) as necessary
  702. parent_dir = os.path.dirname(abs_path)
  703. try:
  704. os.makedirs(parent_dir)
  705. except FileExistsError:
  706. pass
  707. with open(abs_path, "w") as f:
  708. f.write("")
  709. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  710. f.writelines(ignored)
  711. for dir_path in empty_dirs:
  712. os.mkdir(os.path.join(self.repo.path, "empty_dir"))
  713. files_to_add = [os.path.join(self.repo.path, t) for t in tracked]
  714. porcelain.add(repo=self.repo.path, paths=files_to_add)
  715. porcelain.commit(repo=self.repo.path, message="init commit")
  716. def assert_wd(self, expected_paths) -> None:
  717. """Assert paths of files and dirs in wd are same as expected_paths."""
  718. control_dir_rel = os.path.relpath(self.repo._controldir, self.repo.path)
  719. # normalize paths to simplify comparison across platforms
  720. found_paths = {
  721. os.path.normpath(p)
  722. for p in flat_walk_dir(self.repo.path)
  723. if not p.split(os.sep)[0] == control_dir_rel
  724. }
  725. norm_expected_paths = {os.path.normpath(p) for p in expected_paths}
  726. self.assertEqual(found_paths, norm_expected_paths)
  727. def test_from_root(self) -> None:
  728. self.put_files(
  729. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  730. ignored={"ignored_file"},
  731. untracked={
  732. "untracked_file",
  733. "tracked_dir/untracked_dir/untracked_file",
  734. "untracked_dir/untracked_dir/untracked_file",
  735. },
  736. empty_dirs={"empty_dir"},
  737. )
  738. porcelain.clean(repo=self.repo.path, target_dir=self.repo.path)
  739. self.assert_wd(
  740. {
  741. "tracked_file",
  742. "tracked_dir/tracked_file",
  743. ".gitignore",
  744. "ignored_file",
  745. "tracked_dir",
  746. }
  747. )
  748. def test_from_subdir(self) -> None:
  749. self.put_files(
  750. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  751. ignored={"ignored_file"},
  752. untracked={
  753. "untracked_file",
  754. "tracked_dir/untracked_dir/untracked_file",
  755. "untracked_dir/untracked_dir/untracked_file",
  756. },
  757. empty_dirs={"empty_dir"},
  758. )
  759. porcelain.clean(
  760. repo=self.repo,
  761. target_dir=os.path.join(self.repo.path, "untracked_dir"),
  762. )
  763. self.assert_wd(
  764. {
  765. "tracked_file",
  766. "tracked_dir/tracked_file",
  767. ".gitignore",
  768. "ignored_file",
  769. "untracked_file",
  770. "tracked_dir/untracked_dir/untracked_file",
  771. "empty_dir",
  772. "untracked_dir",
  773. "tracked_dir",
  774. "tracked_dir/untracked_dir",
  775. }
  776. )
  777. class CloneTests(PorcelainTestCase):
  778. def test_simple_local(self) -> None:
  779. f1_1 = make_object(Blob, data=b"f1")
  780. commit_spec = [[1], [2, 1], [3, 1, 2]]
  781. trees = {
  782. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  783. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  784. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  785. }
  786. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  787. self.repo.refs[b"refs/heads/master"] = c3.id
  788. self.repo.refs[b"refs/tags/foo"] = c3.id
  789. target_path = tempfile.mkdtemp()
  790. errstream = BytesIO()
  791. self.addCleanup(shutil.rmtree, target_path)
  792. r = porcelain.clone(
  793. self.repo.path, target_path, checkout=False, errstream=errstream
  794. )
  795. self.addCleanup(r.close)
  796. self.assertEqual(r.path, target_path)
  797. target_repo = Repo(target_path)
  798. self.addCleanup(target_repo.close)
  799. self.assertEqual(0, len(target_repo.open_index()))
  800. self.assertEqual(c3.id, target_repo.refs[b"refs/tags/foo"])
  801. self.assertNotIn(b"f1", os.listdir(target_path))
  802. self.assertNotIn(b"f2", os.listdir(target_path))
  803. c = r.get_config()
  804. encoded_path = self.repo.path
  805. if not isinstance(encoded_path, bytes):
  806. encoded_path_bytes = encoded_path.encode("utf-8")
  807. else:
  808. encoded_path_bytes = encoded_path
  809. self.assertEqual(encoded_path_bytes, c.get((b"remote", b"origin"), b"url"))
  810. self.assertEqual(
  811. b"+refs/heads/*:refs/remotes/origin/*",
  812. c.get((b"remote", b"origin"), b"fetch"),
  813. )
  814. def test_simple_local_with_checkout(self) -> None:
  815. f1_1 = make_object(Blob, data=b"f1")
  816. commit_spec = [[1], [2, 1], [3, 1, 2]]
  817. trees = {
  818. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  819. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  820. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  821. }
  822. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  823. self.repo.refs[b"refs/heads/master"] = c3.id
  824. target_path = tempfile.mkdtemp()
  825. errstream = BytesIO()
  826. self.addCleanup(shutil.rmtree, target_path)
  827. with porcelain.clone(
  828. self.repo.path, target_path, checkout=True, errstream=errstream
  829. ) as r:
  830. self.assertEqual(r.path, target_path)
  831. with Repo(target_path) as r:
  832. self.assertEqual(r.head(), c3.id)
  833. self.assertIn("f1", os.listdir(target_path))
  834. self.assertIn("f2", os.listdir(target_path))
  835. def test_bare_local_with_checkout(self) -> None:
  836. f1_1 = make_object(Blob, data=b"f1")
  837. commit_spec = [[1], [2, 1], [3, 1, 2]]
  838. trees = {
  839. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  840. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  841. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  842. }
  843. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  844. self.repo.refs[b"refs/heads/master"] = c3.id
  845. target_path = tempfile.mkdtemp()
  846. errstream = BytesIO()
  847. self.addCleanup(shutil.rmtree, target_path)
  848. with porcelain.clone(
  849. self.repo.path, target_path, bare=True, errstream=errstream
  850. ) as r:
  851. self.assertEqual(r.path, target_path)
  852. with Repo(target_path) as r:
  853. r.head()
  854. self.assertRaises(NoIndexPresent, r.open_index)
  855. self.assertNotIn(b"f1", os.listdir(target_path))
  856. self.assertNotIn(b"f2", os.listdir(target_path))
  857. def test_no_checkout_with_bare(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. self.repo.refs[b"HEAD"] = c1.id
  864. target_path = tempfile.mkdtemp()
  865. errstream = BytesIO()
  866. self.addCleanup(shutil.rmtree, target_path)
  867. self.assertRaises(
  868. porcelain.Error,
  869. porcelain.clone,
  870. self.repo.path,
  871. target_path,
  872. checkout=True,
  873. bare=True,
  874. errstream=errstream,
  875. )
  876. def test_no_head_no_checkout(self) -> None:
  877. f1_1 = make_object(Blob, data=b"f1")
  878. commit_spec = [[1]]
  879. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  880. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  881. self.repo.refs[b"refs/heads/master"] = c1.id
  882. target_path = tempfile.mkdtemp()
  883. self.addCleanup(shutil.rmtree, target_path)
  884. errstream = BytesIO()
  885. r = porcelain.clone(
  886. self.repo.path, target_path, checkout=True, errstream=errstream
  887. )
  888. r.close()
  889. def test_no_head_no_checkout_outstream_errstream_autofallback(self) -> None:
  890. f1_1 = make_object(Blob, data=b"f1")
  891. commit_spec = [[1]]
  892. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  893. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  894. self.repo.refs[b"refs/heads/master"] = c1.id
  895. target_path = tempfile.mkdtemp()
  896. self.addCleanup(shutil.rmtree, target_path)
  897. errstream = porcelain.NoneStream()
  898. r = porcelain.clone(
  899. self.repo.path, target_path, checkout=True, errstream=errstream
  900. )
  901. r.close()
  902. def test_source_broken(self) -> None:
  903. with tempfile.TemporaryDirectory() as parent:
  904. target_path = os.path.join(parent, "target")
  905. self.assertRaises(
  906. Exception, porcelain.clone, "/nonexistent/repo", target_path
  907. )
  908. self.assertFalse(os.path.exists(target_path))
  909. def test_fetch_symref(self) -> None:
  910. f1_1 = make_object(Blob, data=b"f1")
  911. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  912. [c1] = build_commit_graph(self.repo.object_store, [[1]], trees)
  913. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/else")
  914. self.repo.refs[b"refs/heads/else"] = c1.id
  915. target_path = tempfile.mkdtemp()
  916. errstream = BytesIO()
  917. self.addCleanup(shutil.rmtree, target_path)
  918. r = porcelain.clone(
  919. self.repo.path, target_path, checkout=False, errstream=errstream
  920. )
  921. self.addCleanup(r.close)
  922. self.assertEqual(r.path, target_path)
  923. target_repo = Repo(target_path)
  924. self.addCleanup(target_repo.close)
  925. self.assertEqual(0, len(target_repo.open_index()))
  926. self.assertEqual(c1.id, target_repo.refs[b"refs/heads/else"])
  927. self.assertEqual(c1.id, target_repo.refs[b"HEAD"])
  928. self.assertEqual(
  929. {
  930. b"HEAD": b"refs/heads/else",
  931. b"refs/remotes/origin/HEAD": b"refs/remotes/origin/else",
  932. },
  933. target_repo.refs.get_symrefs(),
  934. )
  935. def test_detached_head(self) -> None:
  936. f1_1 = make_object(Blob, data=b"f1")
  937. commit_spec = [[1], [2, 1], [3, 1, 2]]
  938. trees = {
  939. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  940. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  941. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  942. }
  943. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  944. self.repo.refs[b"refs/heads/master"] = c2.id
  945. self.repo.refs.remove_if_equals(b"HEAD", None)
  946. self.repo.refs[b"HEAD"] = c3.id
  947. target_path = tempfile.mkdtemp()
  948. self.addCleanup(shutil.rmtree, target_path)
  949. errstream = porcelain.NoneStream()
  950. with porcelain.clone(
  951. self.repo.path, target_path, checkout=True, errstream=errstream
  952. ) as r:
  953. self.assertEqual(c3.id, r.refs[b"HEAD"])
  954. def test_clone_pathlib(self) -> None:
  955. from pathlib import Path
  956. f1_1 = make_object(Blob, data=b"f1")
  957. commit_spec = [[1]]
  958. trees = {1: [(b"f1", f1_1)]}
  959. c1 = build_commit_graph(self.repo.object_store, commit_spec, trees)[0]
  960. self.repo.refs[b"refs/heads/master"] = c1.id
  961. target_dir = tempfile.mkdtemp()
  962. self.addCleanup(shutil.rmtree, target_dir)
  963. target_path = Path(target_dir) / "clone_repo"
  964. errstream = BytesIO()
  965. r = porcelain.clone(
  966. self.repo.path, target_path, checkout=False, errstream=errstream
  967. )
  968. self.addCleanup(r.close)
  969. self.assertEqual(r.path, str(target_path))
  970. self.assertTrue(os.path.exists(str(target_path)))
  971. def test_clone_with_recurse_submodules(self) -> None:
  972. # Create a submodule repository
  973. sub_repo_path = tempfile.mkdtemp()
  974. self.addCleanup(shutil.rmtree, sub_repo_path)
  975. sub_repo = Repo.init(sub_repo_path)
  976. self.addCleanup(sub_repo.close)
  977. # Add a file to the submodule repo
  978. sub_file = os.path.join(sub_repo_path, "subfile.txt")
  979. with open(sub_file, "w") as f:
  980. f.write("submodule content")
  981. porcelain.add(sub_repo, paths=[sub_file])
  982. sub_commit = porcelain.commit(
  983. sub_repo,
  984. message=b"Initial submodule commit",
  985. author=b"Test Author <test@example.com>",
  986. committer=b"Test Committer <test@example.com>",
  987. )
  988. # Create main repository with submodule
  989. main_file = os.path.join(self.repo.path, "main.txt")
  990. with open(main_file, "w") as f:
  991. f.write("main content")
  992. porcelain.add(self.repo, paths=[main_file])
  993. porcelain.submodule_add(self.repo, sub_repo_path, "sub")
  994. # Manually add the submodule to the index since submodule_add doesn't do it
  995. # when the repository is local (to maintain backward compatibility)
  996. from dulwich.index import IndexEntry
  997. from dulwich.objects import S_IFGITLINK
  998. index = self.repo.open_index()
  999. index[b"sub"] = IndexEntry(
  1000. ctime=0,
  1001. mtime=0,
  1002. dev=0,
  1003. ino=0,
  1004. mode=S_IFGITLINK,
  1005. uid=0,
  1006. gid=0,
  1007. size=0,
  1008. sha=sub_commit,
  1009. flags=0,
  1010. )
  1011. index.write()
  1012. porcelain.add(self.repo, paths=[".gitmodules"])
  1013. porcelain.commit(
  1014. self.repo,
  1015. message=b"Add submodule",
  1016. author=b"Test Author <test@example.com>",
  1017. committer=b"Test Committer <test@example.com>",
  1018. )
  1019. # Clone with recurse_submodules
  1020. target_path = tempfile.mkdtemp()
  1021. self.addCleanup(shutil.rmtree, target_path)
  1022. cloned = porcelain.clone(
  1023. self.repo.path,
  1024. target_path,
  1025. recurse_submodules=True,
  1026. )
  1027. self.addCleanup(cloned.close)
  1028. # Check main file exists
  1029. cloned_main = os.path.join(target_path, "main.txt")
  1030. self.assertTrue(os.path.exists(cloned_main))
  1031. with open(cloned_main) as f:
  1032. self.assertEqual(f.read(), "main content")
  1033. # Check submodule file exists
  1034. cloned_sub_file = os.path.join(target_path, "sub", "subfile.txt")
  1035. self.assertTrue(os.path.exists(cloned_sub_file))
  1036. with open(cloned_sub_file) as f:
  1037. self.assertEqual(f.read(), "submodule content")
  1038. class InitTests(TestCase):
  1039. def test_non_bare(self) -> None:
  1040. repo_dir = tempfile.mkdtemp()
  1041. self.addCleanup(shutil.rmtree, repo_dir)
  1042. porcelain.init(repo_dir)
  1043. def test_bare(self) -> None:
  1044. repo_dir = tempfile.mkdtemp()
  1045. self.addCleanup(shutil.rmtree, repo_dir)
  1046. porcelain.init(repo_dir, bare=True)
  1047. def test_init_pathlib(self) -> None:
  1048. from pathlib import Path
  1049. repo_dir = tempfile.mkdtemp()
  1050. self.addCleanup(shutil.rmtree, repo_dir)
  1051. repo_path = Path(repo_dir)
  1052. # Test non-bare repo with pathlib
  1053. repo = porcelain.init(repo_path)
  1054. self.assertTrue(os.path.exists(os.path.join(repo_dir, ".git")))
  1055. repo.close()
  1056. def test_init_bare_pathlib(self) -> None:
  1057. from pathlib import Path
  1058. repo_dir = tempfile.mkdtemp()
  1059. self.addCleanup(shutil.rmtree, repo_dir)
  1060. repo_path = Path(repo_dir)
  1061. # Test bare repo with pathlib
  1062. repo = porcelain.init(repo_path, bare=True)
  1063. self.assertTrue(os.path.exists(os.path.join(repo_dir, "refs")))
  1064. repo.close()
  1065. class AddTests(PorcelainTestCase):
  1066. def test_add_default_paths(self) -> None:
  1067. # create a file for initial commit
  1068. fullpath = os.path.join(self.repo.path, "blah")
  1069. with open(fullpath, "w") as f:
  1070. f.write("\n")
  1071. porcelain.add(repo=self.repo.path, paths=[fullpath])
  1072. porcelain.commit(
  1073. repo=self.repo.path,
  1074. message=b"test",
  1075. author=b"test <email>",
  1076. committer=b"test <email>",
  1077. )
  1078. # Add a second test file and a file in a directory
  1079. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1080. f.write("\n")
  1081. os.mkdir(os.path.join(self.repo.path, "adir"))
  1082. with open(os.path.join(self.repo.path, "adir", "afile"), "w") as f:
  1083. f.write("\n")
  1084. cwd = os.getcwd()
  1085. self.addCleanup(os.chdir, cwd)
  1086. os.chdir(self.repo.path)
  1087. self.assertEqual({"foo", "blah", "adir", ".git"}, set(os.listdir(".")))
  1088. added, ignored = porcelain.add(self.repo.path)
  1089. # Normalize paths to use forward slashes for comparison
  1090. added_normalized = [path.replace(os.sep, "/") for path in added]
  1091. self.assertEqual(
  1092. (added_normalized, ignored),
  1093. (["foo", "adir/afile"], set()),
  1094. )
  1095. # Check that foo was added and nothing in .git was modified
  1096. index = self.repo.open_index()
  1097. self.assertEqual(sorted(index), [b"adir/afile", b"blah", b"foo"])
  1098. def test_add_default_paths_subdir(self) -> None:
  1099. os.mkdir(os.path.join(self.repo.path, "foo"))
  1100. with open(os.path.join(self.repo.path, "blah"), "w") as f:
  1101. f.write("\n")
  1102. with open(os.path.join(self.repo.path, "foo", "blie"), "w") as f:
  1103. f.write("\n")
  1104. cwd = os.getcwd()
  1105. self.addCleanup(os.chdir, cwd)
  1106. os.chdir(os.path.join(self.repo.path, "foo"))
  1107. porcelain.add(repo=self.repo.path)
  1108. porcelain.commit(
  1109. repo=self.repo.path,
  1110. message=b"test",
  1111. author=b"test <email>",
  1112. committer=b"test <email>",
  1113. )
  1114. index = self.repo.open_index()
  1115. # After fix: add() with no paths should behave like git add -A (add everything)
  1116. self.assertEqual(sorted(index), [b"blah", b"foo/blie"])
  1117. def test_add_file(self) -> None:
  1118. fullpath = os.path.join(self.repo.path, "foo")
  1119. with open(fullpath, "w") as f:
  1120. f.write("BAR")
  1121. porcelain.add(self.repo.path, paths=[fullpath])
  1122. self.assertIn(b"foo", self.repo.open_index())
  1123. def test_add_ignored(self) -> None:
  1124. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1125. f.write("foo\nsubdir/")
  1126. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1127. f.write("BAR")
  1128. with open(os.path.join(self.repo.path, "bar"), "w") as f:
  1129. f.write("BAR")
  1130. os.mkdir(os.path.join(self.repo.path, "subdir"))
  1131. with open(os.path.join(self.repo.path, "subdir", "baz"), "w") as f:
  1132. f.write("BAZ")
  1133. (added, ignored) = porcelain.add(
  1134. self.repo.path,
  1135. paths=[
  1136. os.path.join(self.repo.path, "foo"),
  1137. os.path.join(self.repo.path, "bar"),
  1138. os.path.join(self.repo.path, "subdir"),
  1139. ],
  1140. )
  1141. self.assertIn(b"bar", self.repo.open_index())
  1142. self.assertEqual({"bar"}, set(added))
  1143. self.assertEqual({"foo", "subdir/"}, ignored)
  1144. def test_add_from_ignored_directory(self) -> None:
  1145. # Test for issue #550 - adding files when cwd is in ignored directory
  1146. # Create .gitignore that ignores build/
  1147. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1148. f.write("build/\n")
  1149. # Create ignored directory
  1150. build_dir = os.path.join(self.repo.path, "build")
  1151. os.mkdir(build_dir)
  1152. # Create a file in the repo (not in ignored directory)
  1153. src_file = os.path.join(self.repo.path, "source.py")
  1154. with open(src_file, "w") as f:
  1155. f.write("print('hello')\n")
  1156. # Save current directory and change to ignored directory
  1157. original_cwd = os.getcwd()
  1158. try:
  1159. os.chdir(build_dir)
  1160. # Add file using absolute path from within ignored directory
  1161. (added, ignored) = porcelain.add(self.repo.path, paths=[src_file])
  1162. self.assertIn(b"source.py", self.repo.open_index())
  1163. self.assertEqual({"source.py"}, set(added))
  1164. finally:
  1165. os.chdir(original_cwd)
  1166. def test_add_file_absolute_path(self) -> None:
  1167. # Absolute paths are (not yet) supported
  1168. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1169. f.write("BAR")
  1170. porcelain.add(self.repo, paths=[os.path.join(self.repo.path, "foo")])
  1171. self.assertIn(b"foo", self.repo.open_index())
  1172. def test_add_not_in_repo(self) -> None:
  1173. with open(os.path.join(self.test_dir, "foo"), "w") as f:
  1174. f.write("BAR")
  1175. self.assertRaises(
  1176. ValueError,
  1177. porcelain.add,
  1178. self.repo,
  1179. paths=[os.path.join(self.test_dir, "foo")],
  1180. )
  1181. self.assertRaises(
  1182. (ValueError, FileNotFoundError),
  1183. porcelain.add,
  1184. self.repo,
  1185. paths=["../foo"],
  1186. )
  1187. self.assertEqual([], list(self.repo.open_index()))
  1188. def test_add_file_clrf_conversion(self) -> None:
  1189. from dulwich.index import IndexEntry
  1190. # Set the right configuration to the repo
  1191. c = self.repo.get_config()
  1192. c.set("core", "autocrlf", "input")
  1193. c.write_to_path()
  1194. # Add a file with CRLF line-ending
  1195. fullpath = os.path.join(self.repo.path, "foo")
  1196. with open(fullpath, "wb") as f:
  1197. f.write(b"line1\r\nline2")
  1198. porcelain.add(self.repo.path, paths=[fullpath])
  1199. # The line-endings should have been converted to LF
  1200. index = self.repo.open_index()
  1201. self.assertIn(b"foo", index)
  1202. entry = index[b"foo"]
  1203. assert isinstance(entry, IndexEntry)
  1204. blob = self.repo[entry.sha]
  1205. self.assertEqual(blob.data, b"line1\nline2")
  1206. def test_add_symlink_outside_repo(self) -> None:
  1207. """Test adding a symlink that points outside the repository."""
  1208. # Create a symlink pointing outside the repository
  1209. symlink_path = os.path.join(self.repo.path, "symlink_to_nowhere")
  1210. os.symlink("/nonexistent/path", symlink_path)
  1211. # Adding the symlink should succeed (matching Git's behavior)
  1212. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1213. # Should successfully add the symlink
  1214. self.assertIn("symlink_to_nowhere", added)
  1215. self.assertEqual(len(ignored), 0)
  1216. # Verify symlink is actually staged
  1217. index = self.repo.open_index()
  1218. self.assertIn(b"symlink_to_nowhere", index)
  1219. def test_add_symlink_to_file_inside_repo(self) -> None:
  1220. """Test adding a symlink that points to a file inside the repository."""
  1221. # Create a regular file
  1222. target_file = os.path.join(self.repo.path, "target.txt")
  1223. with open(target_file, "w") as f:
  1224. f.write("target content")
  1225. # Create a symlink to the file
  1226. symlink_path = os.path.join(self.repo.path, "link_to_target")
  1227. os.symlink("target.txt", symlink_path)
  1228. # Add both the target and the symlink
  1229. added, ignored = porcelain.add(
  1230. self.repo.path, paths=[target_file, symlink_path]
  1231. )
  1232. # Both should be added successfully
  1233. self.assertIn("target.txt", added)
  1234. self.assertIn("link_to_target", added)
  1235. self.assertEqual(len(ignored), 0)
  1236. # Verify both are in the index
  1237. index = self.repo.open_index()
  1238. self.assertIn(b"target.txt", index)
  1239. self.assertIn(b"link_to_target", index)
  1240. def test_add_symlink_to_directory_inside_repo(self) -> None:
  1241. """Test adding a symlink that points to a directory inside the repository."""
  1242. # Create a directory with some files
  1243. target_dir = os.path.join(self.repo.path, "target_dir")
  1244. os.mkdir(target_dir)
  1245. with open(os.path.join(target_dir, "file1.txt"), "w") as f:
  1246. f.write("content1")
  1247. with open(os.path.join(target_dir, "file2.txt"), "w") as f:
  1248. f.write("content2")
  1249. # Create a symlink to the directory
  1250. symlink_path = os.path.join(self.repo.path, "link_to_dir")
  1251. os.symlink("target_dir", symlink_path)
  1252. # Add the symlink
  1253. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1254. # When adding a symlink to a directory, it follows the symlink and adds contents
  1255. self.assertEqual(len(added), 2)
  1256. self.assertIn("link_to_dir/file1.txt", added)
  1257. self.assertIn("link_to_dir/file2.txt", added)
  1258. self.assertEqual(len(ignored), 0)
  1259. # Verify files are added through the symlink path
  1260. index = self.repo.open_index()
  1261. self.assertIn(b"link_to_dir/file1.txt", index)
  1262. self.assertIn(b"link_to_dir/file2.txt", index)
  1263. # The original target directory files are not added
  1264. self.assertNotIn(b"target_dir/file1.txt", index)
  1265. self.assertNotIn(b"target_dir/file2.txt", index)
  1266. def test_add_symlink_chain(self) -> None:
  1267. """Test adding a chain of symlinks (symlink to symlink)."""
  1268. # Create a regular file
  1269. target_file = os.path.join(self.repo.path, "original.txt")
  1270. with open(target_file, "w") as f:
  1271. f.write("original content")
  1272. # Create first symlink
  1273. first_link = os.path.join(self.repo.path, "link1")
  1274. os.symlink("original.txt", first_link)
  1275. # Create second symlink pointing to first
  1276. second_link = os.path.join(self.repo.path, "link2")
  1277. os.symlink("link1", second_link)
  1278. # Add all files
  1279. added, ignored = porcelain.add(
  1280. self.repo.path, paths=[target_file, first_link, second_link]
  1281. )
  1282. # All should be added
  1283. self.assertEqual(len(added), 3)
  1284. self.assertIn("original.txt", added)
  1285. self.assertIn("link1", added)
  1286. self.assertIn("link2", added)
  1287. # Verify all are in the index
  1288. index = self.repo.open_index()
  1289. self.assertIn(b"original.txt", index)
  1290. self.assertIn(b"link1", index)
  1291. self.assertIn(b"link2", index)
  1292. def test_add_broken_symlink(self) -> None:
  1293. """Test adding a broken symlink (points to non-existent target)."""
  1294. # Create a symlink to a non-existent file
  1295. broken_link = os.path.join(self.repo.path, "broken_link")
  1296. os.symlink("does_not_exist.txt", broken_link)
  1297. # Add the broken symlink
  1298. added, ignored = porcelain.add(self.repo.path, paths=[broken_link])
  1299. # Should be added successfully (Git tracks the symlink, not its target)
  1300. self.assertIn("broken_link", added)
  1301. self.assertEqual(len(ignored), 0)
  1302. # Verify it's in the index
  1303. index = self.repo.open_index()
  1304. self.assertIn(b"broken_link", index)
  1305. def test_add_symlink_relative_outside_repo(self) -> None:
  1306. """Test adding a symlink that uses '..' to point outside the repository."""
  1307. # Create a file outside the repo
  1308. outside_file = os.path.join(self.test_dir, "outside.txt")
  1309. with open(outside_file, "w") as f:
  1310. f.write("outside content")
  1311. # Create a symlink using relative path to go outside
  1312. symlink_path = os.path.join(self.repo.path, "link_outside")
  1313. os.symlink("../outside.txt", symlink_path)
  1314. # Add the symlink
  1315. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1316. # Should be added successfully
  1317. self.assertIn("link_outside", added)
  1318. self.assertEqual(len(ignored), 0)
  1319. # Verify it's in the index
  1320. index = self.repo.open_index()
  1321. self.assertIn(b"link_outside", index)
  1322. def test_add_symlink_absolute_to_system(self) -> None:
  1323. """Test adding a symlink with absolute path to system directory."""
  1324. # Create a symlink to a system directory
  1325. symlink_path = os.path.join(self.repo.path, "link_to_tmp")
  1326. if os.name == "nt":
  1327. # On Windows, use a system directory like TEMP
  1328. symlink_target = os.environ["TEMP"]
  1329. else:
  1330. # On Unix-like systems, use /tmp
  1331. symlink_target = "/tmp"
  1332. os.symlink(symlink_target, symlink_path)
  1333. # Adding a symlink to a directory outside the repo should raise ValueError
  1334. with self.assertRaises(ValueError) as cm:
  1335. porcelain.add(self.repo.path, paths=[symlink_path])
  1336. # Check that the error indicates the path is outside the repository
  1337. self.assertIn("is not in the subpath of", str(cm.exception))
  1338. def test_add_file_through_symlink(self) -> None:
  1339. """Test adding a file through a symlinked directory."""
  1340. # Create a directory with a file
  1341. real_dir = os.path.join(self.repo.path, "real_dir")
  1342. os.mkdir(real_dir)
  1343. real_file = os.path.join(real_dir, "file.txt")
  1344. with open(real_file, "w") as f:
  1345. f.write("content")
  1346. # Create a symlink to the directory
  1347. link_dir = os.path.join(self.repo.path, "link_dir")
  1348. os.symlink("real_dir", link_dir)
  1349. # Try to add the file through the symlink path
  1350. symlink_file_path = os.path.join(link_dir, "file.txt")
  1351. # This should add the real file, not create a new entry
  1352. added, ignored = porcelain.add(self.repo.path, paths=[symlink_file_path])
  1353. # The real file should be added
  1354. self.assertIn("real_dir/file.txt", added)
  1355. self.assertEqual(len(added), 1)
  1356. # Verify correct path in index
  1357. index = self.repo.open_index()
  1358. self.assertIn(b"real_dir/file.txt", index)
  1359. # Should not create a separate entry for the symlink path
  1360. self.assertNotIn(b"link_dir/file.txt", index)
  1361. def test_add_repo_path(self) -> None:
  1362. """Test adding the repository path itself should add all untracked files."""
  1363. # Create some untracked files
  1364. with open(os.path.join(self.repo.path, "file1.txt"), "w") as f:
  1365. f.write("content1")
  1366. with open(os.path.join(self.repo.path, "file2.txt"), "w") as f:
  1367. f.write("content2")
  1368. # Add the repository path itself
  1369. added, ignored = porcelain.add(self.repo.path, paths=[self.repo.path])
  1370. # Should add all untracked files, not stage './'
  1371. self.assertIn("file1.txt", added)
  1372. self.assertIn("file2.txt", added)
  1373. self.assertNotIn("./", added)
  1374. # Verify files are actually staged
  1375. index = self.repo.open_index()
  1376. self.assertIn(b"file1.txt", index)
  1377. self.assertIn(b"file2.txt", index)
  1378. def test_add_directory_contents(self) -> None:
  1379. """Test adding a directory adds all files within it."""
  1380. # Create a subdirectory with multiple files
  1381. subdir = os.path.join(self.repo.path, "subdir")
  1382. os.mkdir(subdir)
  1383. with open(os.path.join(subdir, "file1.txt"), "w") as f:
  1384. f.write("content1")
  1385. with open(os.path.join(subdir, "file2.txt"), "w") as f:
  1386. f.write("content2")
  1387. with open(os.path.join(subdir, "file3.txt"), "w") as f:
  1388. f.write("content3")
  1389. # Add the directory
  1390. added, ignored = porcelain.add(self.repo.path, paths=["subdir"])
  1391. # Should add all files in the directory
  1392. self.assertEqual(len(added), 3)
  1393. # Normalize paths to use forward slashes for comparison
  1394. added_normalized = [path.replace(os.sep, "/") for path in added]
  1395. self.assertIn("subdir/file1.txt", added_normalized)
  1396. self.assertIn("subdir/file2.txt", added_normalized)
  1397. self.assertIn("subdir/file3.txt", added_normalized)
  1398. # Verify files are actually staged
  1399. index = self.repo.open_index()
  1400. self.assertIn(b"subdir/file1.txt", index)
  1401. self.assertIn(b"subdir/file2.txt", index)
  1402. self.assertIn(b"subdir/file3.txt", index)
  1403. def test_add_nested_directories(self) -> None:
  1404. """Test adding a directory with nested subdirectories."""
  1405. # Create nested directory structure
  1406. dir1 = os.path.join(self.repo.path, "dir1")
  1407. dir2 = os.path.join(dir1, "dir2")
  1408. dir3 = os.path.join(dir2, "dir3")
  1409. os.makedirs(dir3)
  1410. # Add files at each level
  1411. with open(os.path.join(dir1, "file1.txt"), "w") as f:
  1412. f.write("level1")
  1413. with open(os.path.join(dir2, "file2.txt"), "w") as f:
  1414. f.write("level2")
  1415. with open(os.path.join(dir3, "file3.txt"), "w") as f:
  1416. f.write("level3")
  1417. # Add the top-level directory
  1418. added, ignored = porcelain.add(self.repo.path, paths=["dir1"])
  1419. # Should add all files recursively
  1420. self.assertEqual(len(added), 3)
  1421. # Normalize paths to use forward slashes for comparison
  1422. added_normalized = [path.replace(os.sep, "/") for path in added]
  1423. self.assertIn("dir1/file1.txt", added_normalized)
  1424. self.assertIn("dir1/dir2/file2.txt", added_normalized)
  1425. self.assertIn("dir1/dir2/dir3/file3.txt", added_normalized)
  1426. # Verify files are actually staged
  1427. index = self.repo.open_index()
  1428. self.assertIn(b"dir1/file1.txt", index)
  1429. self.assertIn(b"dir1/dir2/file2.txt", index)
  1430. self.assertIn(b"dir1/dir2/dir3/file3.txt", index)
  1431. def test_add_directory_with_tracked_files(self) -> None:
  1432. """Test adding a directory with some files already tracked."""
  1433. # Create a subdirectory with files
  1434. subdir = os.path.join(self.repo.path, "mixed")
  1435. os.mkdir(subdir)
  1436. # Create and commit one file
  1437. tracked_file = os.path.join(subdir, "tracked.txt")
  1438. with open(tracked_file, "w") as f:
  1439. f.write("already tracked")
  1440. porcelain.add(self.repo.path, paths=[tracked_file])
  1441. porcelain.commit(
  1442. repo=self.repo.path,
  1443. message=b"Add tracked file",
  1444. author=b"test <email>",
  1445. committer=b"test <email>",
  1446. )
  1447. # Add more untracked files
  1448. with open(os.path.join(subdir, "untracked1.txt"), "w") as f:
  1449. f.write("new file 1")
  1450. with open(os.path.join(subdir, "untracked2.txt"), "w") as f:
  1451. f.write("new file 2")
  1452. # Add the directory
  1453. added, ignored = porcelain.add(self.repo.path, paths=["mixed"])
  1454. # Should only add the untracked files
  1455. self.assertEqual(len(added), 2)
  1456. # Normalize paths to use forward slashes for comparison
  1457. added_normalized = [path.replace(os.sep, "/") for path in added]
  1458. self.assertIn("mixed/untracked1.txt", added_normalized)
  1459. self.assertIn("mixed/untracked2.txt", added_normalized)
  1460. self.assertNotIn("mixed/tracked.txt", added)
  1461. # Verify the index contains all files
  1462. index = self.repo.open_index()
  1463. self.assertIn(b"mixed/tracked.txt", index)
  1464. self.assertIn(b"mixed/untracked1.txt", index)
  1465. self.assertIn(b"mixed/untracked2.txt", index)
  1466. def test_add_directory_with_gitignore(self) -> None:
  1467. """Test adding a directory respects .gitignore patterns."""
  1468. # Create .gitignore
  1469. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1470. f.write("*.log\n*.tmp\nbuild/\n")
  1471. # Create directory with mixed files
  1472. testdir = os.path.join(self.repo.path, "testdir")
  1473. os.mkdir(testdir)
  1474. # Create various files
  1475. with open(os.path.join(testdir, "important.txt"), "w") as f:
  1476. f.write("keep this")
  1477. with open(os.path.join(testdir, "debug.log"), "w") as f:
  1478. f.write("ignore this")
  1479. with open(os.path.join(testdir, "temp.tmp"), "w") as f:
  1480. f.write("ignore this too")
  1481. with open(os.path.join(testdir, "readme.md"), "w") as f:
  1482. f.write("keep this too")
  1483. # Create a build directory that should be ignored
  1484. builddir = os.path.join(testdir, "build")
  1485. os.mkdir(builddir)
  1486. with open(os.path.join(builddir, "output.txt"), "w") as f:
  1487. f.write("ignore entire directory")
  1488. # Add the directory
  1489. added, ignored = porcelain.add(self.repo.path, paths=["testdir"])
  1490. # Should only add non-ignored files
  1491. # Normalize paths to use forward slashes for comparison
  1492. added_normalized = {path.replace(os.sep, "/") for path in added}
  1493. self.assertEqual(
  1494. added_normalized, {"testdir/important.txt", "testdir/readme.md"}
  1495. )
  1496. # Check ignored files
  1497. # Normalize paths to use forward slashes for comparison
  1498. ignored_normalized = {path.replace(os.sep, "/") for path in ignored}
  1499. self.assertIn("testdir/debug.log", ignored_normalized)
  1500. self.assertIn("testdir/temp.tmp", ignored_normalized)
  1501. self.assertIn("testdir/build/", ignored_normalized)
  1502. def test_add_multiple_directories(self) -> None:
  1503. """Test adding multiple directories in one call."""
  1504. # Create multiple directories
  1505. for dirname in ["dir1", "dir2", "dir3"]:
  1506. dirpath = os.path.join(self.repo.path, dirname)
  1507. os.mkdir(dirpath)
  1508. # Add files to each directory
  1509. for i in range(2):
  1510. with open(os.path.join(dirpath, f"file{i}.txt"), "w") as f:
  1511. f.write(f"content {dirname} {i}")
  1512. # Add all directories at once
  1513. added, ignored = porcelain.add(self.repo.path, paths=["dir1", "dir2", "dir3"])
  1514. # Should add all files from all directories
  1515. self.assertEqual(len(added), 6)
  1516. # Normalize paths to use forward slashes for comparison
  1517. added_normalized = [path.replace(os.sep, "/") for path in added]
  1518. for dirname in ["dir1", "dir2", "dir3"]:
  1519. for i in range(2):
  1520. self.assertIn(f"{dirname}/file{i}.txt", added_normalized)
  1521. # Verify all files are staged
  1522. index = self.repo.open_index()
  1523. self.assertEqual(len(index), 6)
  1524. def test_add_default_paths_includes_modified_files(self) -> None:
  1525. """Test that add() with no paths includes both untracked and modified files."""
  1526. # Create and commit initial file
  1527. initial_file = os.path.join(self.repo.path, "existing.txt")
  1528. with open(initial_file, "w") as f:
  1529. f.write("initial content\n")
  1530. porcelain.add(repo=self.repo.path, paths=[initial_file])
  1531. porcelain.commit(
  1532. repo=self.repo.path,
  1533. message=b"initial commit",
  1534. author=b"test <email>",
  1535. committer=b"test <email>",
  1536. )
  1537. # Modify the existing file (this creates an unstaged change)
  1538. with open(initial_file, "w") as f:
  1539. f.write("modified content\n")
  1540. # Create a new untracked file
  1541. new_file = os.path.join(self.repo.path, "new.txt")
  1542. with open(new_file, "w") as f:
  1543. f.write("new file content\n")
  1544. # Call add() with no paths - should stage both modified and untracked files
  1545. added_files, ignored_files = porcelain.add(repo=self.repo.path)
  1546. # Verify both files were added
  1547. self.assertIn("existing.txt", added_files)
  1548. self.assertIn("new.txt", added_files)
  1549. self.assertEqual(len(ignored_files), 0)
  1550. # Verify both files are now staged
  1551. index = self.repo.open_index()
  1552. self.assertIn(b"existing.txt", index)
  1553. self.assertIn(b"new.txt", index)
  1554. class RemoveTests(PorcelainTestCase):
  1555. def test_remove_file(self) -> None:
  1556. fullpath = os.path.join(self.repo.path, "foo")
  1557. with open(fullpath, "w") as f:
  1558. f.write("BAR")
  1559. porcelain.add(self.repo.path, paths=[fullpath])
  1560. porcelain.commit(
  1561. repo=self.repo,
  1562. message=b"test",
  1563. author=b"test <email>",
  1564. committer=b"test <email>",
  1565. )
  1566. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "foo")))
  1567. cwd = os.getcwd()
  1568. self.addCleanup(os.chdir, cwd)
  1569. os.chdir(self.repo.path)
  1570. porcelain.remove(self.repo.path, paths=["foo"])
  1571. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1572. def test_remove_file_staged(self) -> None:
  1573. fullpath = os.path.join(self.repo.path, "foo")
  1574. with open(fullpath, "w") as f:
  1575. f.write("BAR")
  1576. cwd = os.getcwd()
  1577. self.addCleanup(os.chdir, cwd)
  1578. os.chdir(self.repo.path)
  1579. porcelain.add(self.repo.path, paths=[fullpath])
  1580. self.assertRaises(Exception, porcelain.rm, self.repo.path, paths=["foo"])
  1581. def test_remove_file_removed_on_disk(self) -> None:
  1582. fullpath = os.path.join(self.repo.path, "foo")
  1583. with open(fullpath, "w") as f:
  1584. f.write("BAR")
  1585. porcelain.add(self.repo.path, paths=[fullpath])
  1586. cwd = os.getcwd()
  1587. self.addCleanup(os.chdir, cwd)
  1588. os.chdir(self.repo.path)
  1589. os.remove(fullpath)
  1590. porcelain.remove(self.repo.path, paths=["foo"])
  1591. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1592. def test_remove_from_different_directory(self) -> None:
  1593. # Create a subdirectory with a file
  1594. subdir = os.path.join(self.repo.path, "mydir")
  1595. os.makedirs(subdir)
  1596. fullpath = os.path.join(subdir, "myfile")
  1597. with open(fullpath, "w") as f:
  1598. f.write("BAR")
  1599. # Add and commit the file
  1600. porcelain.add(self.repo.path, paths=[fullpath])
  1601. porcelain.commit(
  1602. repo=self.repo,
  1603. message=b"test",
  1604. author=b"test <email>",
  1605. committer=b"test <email>",
  1606. )
  1607. # Change to a different directory
  1608. cwd = os.getcwd()
  1609. tempdir = tempfile.mkdtemp()
  1610. def cleanup():
  1611. os.chdir(cwd)
  1612. shutil.rmtree(tempdir)
  1613. self.addCleanup(cleanup)
  1614. os.chdir(tempdir)
  1615. # Remove the file using relative path from repository root
  1616. porcelain.remove(self.repo.path, paths=["mydir/myfile"])
  1617. # Verify file was removed
  1618. self.assertFalse(os.path.exists(fullpath))
  1619. def test_remove_with_absolute_path(self) -> None:
  1620. # Create a file
  1621. fullpath = os.path.join(self.repo.path, "foo")
  1622. with open(fullpath, "w") as f:
  1623. f.write("BAR")
  1624. # Add and commit the file
  1625. porcelain.add(self.repo.path, paths=[fullpath])
  1626. porcelain.commit(
  1627. repo=self.repo,
  1628. message=b"test",
  1629. author=b"test <email>",
  1630. committer=b"test <email>",
  1631. )
  1632. # Change to a different directory
  1633. cwd = os.getcwd()
  1634. tempdir = tempfile.mkdtemp()
  1635. def cleanup():
  1636. os.chdir(cwd)
  1637. shutil.rmtree(tempdir)
  1638. self.addCleanup(cleanup)
  1639. os.chdir(tempdir)
  1640. # Remove the file using absolute path
  1641. porcelain.remove(self.repo.path, paths=[fullpath])
  1642. # Verify file was removed
  1643. self.assertFalse(os.path.exists(fullpath))
  1644. def test_remove_with_filter_normalization(self) -> None:
  1645. # Enable autocrlf to normalize line endings
  1646. config = self.repo.get_config()
  1647. config.set(("core",), "autocrlf", b"true")
  1648. config.write_to_path()
  1649. # Create a file with LF line endings (will be stored with LF in index)
  1650. fullpath = os.path.join(self.repo.path, "foo.txt")
  1651. with open(fullpath, "wb") as f:
  1652. f.write(b"line1\nline2\nline3")
  1653. # Add and commit the file (stored with LF in index)
  1654. porcelain.add(self.repo.path, paths=[fullpath])
  1655. porcelain.commit(
  1656. repo=self.repo,
  1657. message=b"Add file with LF",
  1658. author=b"test <email>",
  1659. committer=b"test <email>",
  1660. )
  1661. # Simulate checkout with CRLF conversion (as would happen on Windows)
  1662. with open(fullpath, "wb") as f:
  1663. f.write(b"line1\r\nline2\r\nline3")
  1664. # Verify file exists
  1665. self.assertTrue(os.path.exists(fullpath))
  1666. # Remove the file - this should not fail even though working tree has CRLF
  1667. # and index has LF (thanks to the normalization in the commit)
  1668. cwd = os.getcwd()
  1669. os.chdir(self.repo.path)
  1670. self.addCleanup(os.chdir, cwd)
  1671. porcelain.remove(self.repo.path, paths=["foo.txt"])
  1672. # Verify file was removed
  1673. self.assertFalse(os.path.exists(fullpath))
  1674. class MvTests(PorcelainTestCase):
  1675. def test_mv_file(self) -> None:
  1676. # Create a file
  1677. fullpath = os.path.join(self.repo.path, "foo")
  1678. with open(fullpath, "w") as f:
  1679. f.write("BAR")
  1680. # Add and commit the file
  1681. porcelain.add(self.repo.path, paths=[fullpath])
  1682. porcelain.commit(
  1683. repo=self.repo,
  1684. message=b"test",
  1685. author=b"test <email>",
  1686. committer=b"test <email>",
  1687. )
  1688. # Move the file
  1689. porcelain.mv(self.repo.path, "foo", "bar")
  1690. # Verify old path doesn't exist and new path does
  1691. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1692. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "bar")))
  1693. # Verify index was updated
  1694. index = self.repo.open_index()
  1695. self.assertNotIn(b"foo", index)
  1696. self.assertIn(b"bar", index)
  1697. def test_mv_file_to_existing_directory(self) -> None:
  1698. # Create a file and a directory
  1699. fullpath = os.path.join(self.repo.path, "foo")
  1700. with open(fullpath, "w") as f:
  1701. f.write("BAR")
  1702. dirpath = os.path.join(self.repo.path, "mydir")
  1703. os.makedirs(dirpath)
  1704. # Add and commit the file
  1705. porcelain.add(self.repo.path, paths=[fullpath])
  1706. porcelain.commit(
  1707. repo=self.repo,
  1708. message=b"test",
  1709. author=b"test <email>",
  1710. committer=b"test <email>",
  1711. )
  1712. # Move the file into the directory
  1713. porcelain.mv(self.repo.path, "foo", "mydir")
  1714. # Verify file moved into directory
  1715. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1716. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "mydir", "foo")))
  1717. # Verify index was updated
  1718. index = self.repo.open_index()
  1719. self.assertNotIn(b"foo", index)
  1720. self.assertIn(b"mydir/foo", index)
  1721. def test_mv_file_force_overwrite(self) -> None:
  1722. # Create two files
  1723. fullpath1 = os.path.join(self.repo.path, "foo")
  1724. with open(fullpath1, "w") as f:
  1725. f.write("FOO")
  1726. fullpath2 = os.path.join(self.repo.path, "bar")
  1727. with open(fullpath2, "w") as f:
  1728. f.write("BAR")
  1729. # Add and commit both files
  1730. porcelain.add(self.repo.path, paths=[fullpath1, fullpath2])
  1731. porcelain.commit(
  1732. repo=self.repo,
  1733. message=b"test",
  1734. author=b"test <email>",
  1735. committer=b"test <email>",
  1736. )
  1737. # Try to move without force (should fail)
  1738. self.assertRaises(porcelain.Error, porcelain.mv, self.repo.path, "foo", "bar")
  1739. # Move with force
  1740. porcelain.mv(self.repo.path, "foo", "bar", force=True)
  1741. # Verify foo doesn't exist and bar has foo's content
  1742. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1743. with open(os.path.join(self.repo.path, "bar")) as f:
  1744. self.assertEqual(f.read(), "FOO")
  1745. def test_mv_file_not_tracked(self) -> None:
  1746. # Create an untracked file
  1747. fullpath = os.path.join(self.repo.path, "untracked")
  1748. with open(fullpath, "w") as f:
  1749. f.write("UNTRACKED")
  1750. # Try to move it (should fail)
  1751. self.assertRaises(
  1752. porcelain.Error, porcelain.mv, self.repo.path, "untracked", "tracked"
  1753. )
  1754. def test_mv_file_not_exists(self) -> None:
  1755. # Try to move a non-existent file
  1756. self.assertRaises(
  1757. porcelain.Error, porcelain.mv, self.repo.path, "nonexistent", "destination"
  1758. )
  1759. def test_mv_absolute_paths(self) -> None:
  1760. # Create a file
  1761. fullpath = os.path.join(self.repo.path, "foo")
  1762. with open(fullpath, "w") as f:
  1763. f.write("BAR")
  1764. # Add and commit the file
  1765. porcelain.add(self.repo.path, paths=[fullpath])
  1766. porcelain.commit(
  1767. repo=self.repo,
  1768. message=b"test",
  1769. author=b"test <email>",
  1770. committer=b"test <email>",
  1771. )
  1772. # Move using absolute paths
  1773. dest_path = os.path.join(self.repo.path, "bar")
  1774. porcelain.mv(self.repo.path, fullpath, dest_path)
  1775. # Verify file moved
  1776. self.assertFalse(os.path.exists(fullpath))
  1777. self.assertTrue(os.path.exists(dest_path))
  1778. def test_mv_from_different_directory(self) -> None:
  1779. # Create a subdirectory with a file
  1780. subdir = os.path.join(self.repo.path, "mydir")
  1781. os.makedirs(subdir)
  1782. fullpath = os.path.join(subdir, "myfile")
  1783. with open(fullpath, "w") as f:
  1784. f.write("BAR")
  1785. # Add and commit the file
  1786. porcelain.add(self.repo.path, paths=[fullpath])
  1787. porcelain.commit(
  1788. repo=self.repo,
  1789. message=b"test",
  1790. author=b"test <email>",
  1791. committer=b"test <email>",
  1792. )
  1793. # Change to a different directory and move the file
  1794. cwd = os.getcwd()
  1795. tempdir = tempfile.mkdtemp()
  1796. def cleanup():
  1797. os.chdir(cwd)
  1798. shutil.rmtree(tempdir)
  1799. self.addCleanup(cleanup)
  1800. os.chdir(tempdir)
  1801. # Move the file using relative path from repository root
  1802. porcelain.mv(self.repo.path, "mydir/myfile", "renamed")
  1803. # Verify file was moved
  1804. self.assertFalse(os.path.exists(fullpath))
  1805. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "renamed")))
  1806. class LogTests(PorcelainTestCase):
  1807. def test_simple(self) -> None:
  1808. c1, c2, c3 = build_commit_graph(
  1809. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1810. )
  1811. self.repo.refs[b"HEAD"] = c3.id
  1812. self.maxDiff = None
  1813. outstream = StringIO()
  1814. porcelain.log(self.repo.path, outstream=outstream)
  1815. self.assertEqual(
  1816. outstream.getvalue(),
  1817. """\
  1818. --------------------------------------------------
  1819. commit: 4a3b887baa9ecb2d054d2469b628aef84e2d74f0
  1820. merge: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  1821. Author: Test Author <test@nodomain.com>
  1822. Committer: Test Committer <test@nodomain.com>
  1823. Date: Fri Jan 01 2010 00:00:00 +0000
  1824. Commit 3
  1825. --------------------------------------------------
  1826. commit: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  1827. Author: Test Author <test@nodomain.com>
  1828. Committer: Test Committer <test@nodomain.com>
  1829. Date: Fri Jan 01 2010 00:00:00 +0000
  1830. Commit 2
  1831. --------------------------------------------------
  1832. commit: 11d3cf672a19366435c1983c7340b008ec6b8bf3
  1833. Author: Test Author <test@nodomain.com>
  1834. Committer: Test Committer <test@nodomain.com>
  1835. Date: Fri Jan 01 2010 00:00:00 +0000
  1836. Commit 1
  1837. """,
  1838. )
  1839. def test_max_entries(self) -> None:
  1840. c1, c2, c3 = build_commit_graph(
  1841. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1842. )
  1843. self.repo.refs[b"HEAD"] = c3.id
  1844. outstream = StringIO()
  1845. porcelain.log(self.repo.path, outstream=outstream, max_entries=1)
  1846. self.assertEqual(1, outstream.getvalue().count("-" * 50))
  1847. def test_no_revisions(self) -> None:
  1848. outstream = StringIO()
  1849. porcelain.log(self.repo.path, outstream=outstream)
  1850. self.assertEqual("", outstream.getvalue())
  1851. def test_empty_message(self) -> None:
  1852. c1 = make_commit(message="")
  1853. self.repo.object_store.add_object(c1)
  1854. self.repo.refs[b"HEAD"] = c1.id
  1855. outstream = StringIO()
  1856. porcelain.log(self.repo.path, outstream=outstream)
  1857. self.assertEqual(
  1858. outstream.getvalue(),
  1859. """\
  1860. --------------------------------------------------
  1861. commit: 4a7ad5552fad70647a81fb9a4a923ccefcca4b76
  1862. Author: Test Author <test@nodomain.com>
  1863. Committer: Test Committer <test@nodomain.com>
  1864. Date: Fri Jan 01 2010 00:00:00 +0000
  1865. """,
  1866. )
  1867. class ShowTests(PorcelainTestCase):
  1868. def test_nolist(self) -> None:
  1869. c1, c2, c3 = build_commit_graph(
  1870. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1871. )
  1872. self.repo.refs[b"HEAD"] = c3.id
  1873. outstream = StringIO()
  1874. porcelain.show(self.repo.path, objects=c3.id, outstream=outstream)
  1875. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  1876. def test_simple(self) -> None:
  1877. c1, c2, c3 = build_commit_graph(
  1878. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1879. )
  1880. self.repo.refs[b"HEAD"] = c3.id
  1881. outstream = StringIO()
  1882. porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream)
  1883. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  1884. def test_blob(self) -> None:
  1885. b = Blob.from_string(b"The Foo\n")
  1886. self.repo.object_store.add_object(b)
  1887. outstream = StringIO()
  1888. porcelain.show(self.repo.path, objects=[b.id], outstream=outstream)
  1889. self.assertEqual(outstream.getvalue(), "The Foo\n")
  1890. def test_commit_no_parent(self) -> None:
  1891. a = Blob.from_string(b"The Foo\n")
  1892. ta = Tree()
  1893. ta.add(b"somename", 0o100644, a.id)
  1894. ca = make_commit(tree=ta.id)
  1895. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  1896. outstream = StringIO()
  1897. porcelain.show(self.repo.path, objects=[ca.id], outstream=outstream)
  1898. self.assertMultiLineEqual(
  1899. outstream.getvalue(),
  1900. """\
  1901. --------------------------------------------------
  1902. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  1903. Author: Test Author <test@nodomain.com>
  1904. Committer: Test Committer <test@nodomain.com>
  1905. Date: Fri Jan 01 2010 00:00:00 +0000
  1906. Test message.
  1907. diff --git a/somename b/somename
  1908. new file mode 100644
  1909. index 0000000..ea5c7bf
  1910. --- /dev/null
  1911. +++ b/somename
  1912. @@ -0,0 +1 @@
  1913. +The Foo
  1914. """,
  1915. )
  1916. def test_tag(self) -> None:
  1917. a = Blob.from_string(b"The Foo\n")
  1918. ta = Tree()
  1919. ta.add(b"somename", 0o100644, a.id)
  1920. ca = make_commit(tree=ta.id)
  1921. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  1922. porcelain.tag_create(
  1923. self.repo.path,
  1924. b"tryme",
  1925. b"foo <foo@bar.com>",
  1926. b"bar",
  1927. annotated=True,
  1928. objectish=ca.id,
  1929. tag_time=1552854211,
  1930. tag_timezone=0,
  1931. )
  1932. outstream = StringIO()
  1933. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  1934. self.maxDiff = None
  1935. self.assertMultiLineEqual(
  1936. outstream.getvalue(),
  1937. """\
  1938. Tagger: foo <foo@bar.com>
  1939. Date: Sun Mar 17 2019 20:23:31 +0000
  1940. bar
  1941. --------------------------------------------------
  1942. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  1943. Author: Test Author <test@nodomain.com>
  1944. Committer: Test Committer <test@nodomain.com>
  1945. Date: Fri Jan 01 2010 00:00:00 +0000
  1946. Test message.
  1947. diff --git a/somename b/somename
  1948. new file mode 100644
  1949. index 0000000..ea5c7bf
  1950. --- /dev/null
  1951. +++ b/somename
  1952. @@ -0,0 +1 @@
  1953. +The Foo
  1954. """,
  1955. )
  1956. def test_tag_unicode(self) -> None:
  1957. a = Blob.from_string(b"The Foo\n")
  1958. ta = Tree()
  1959. ta.add(b"somename", 0o100644, a.id)
  1960. ca = make_commit(tree=ta.id)
  1961. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  1962. porcelain.tag_create(
  1963. self.repo.path,
  1964. "tryme",
  1965. "foo <foo@bar.com>",
  1966. "bar",
  1967. annotated=True,
  1968. objectish=ca.id,
  1969. tag_time=1552854211,
  1970. tag_timezone=0,
  1971. )
  1972. outstream = StringIO()
  1973. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  1974. self.maxDiff = None
  1975. self.assertMultiLineEqual(
  1976. outstream.getvalue(),
  1977. """\
  1978. Tagger: foo <foo@bar.com>
  1979. Date: Sun Mar 17 2019 20:23:31 +0000
  1980. bar
  1981. --------------------------------------------------
  1982. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  1983. Author: Test Author <test@nodomain.com>
  1984. Committer: Test Committer <test@nodomain.com>
  1985. Date: Fri Jan 01 2010 00:00:00 +0000
  1986. Test message.
  1987. diff --git a/somename b/somename
  1988. new file mode 100644
  1989. index 0000000..ea5c7bf
  1990. --- /dev/null
  1991. +++ b/somename
  1992. @@ -0,0 +1 @@
  1993. +The Foo
  1994. """,
  1995. )
  1996. def test_commit_with_change(self) -> None:
  1997. a = Blob.from_string(b"The Foo\n")
  1998. ta = Tree()
  1999. ta.add(b"somename", 0o100644, a.id)
  2000. ca = make_commit(tree=ta.id)
  2001. b = Blob.from_string(b"The Bar\n")
  2002. tb = Tree()
  2003. tb.add(b"somename", 0o100644, b.id)
  2004. cb = make_commit(tree=tb.id, parents=[ca.id])
  2005. self.repo.object_store.add_objects(
  2006. [
  2007. (a, None),
  2008. (b, None),
  2009. (ta, None),
  2010. (tb, None),
  2011. (ca, None),
  2012. (cb, None),
  2013. ]
  2014. )
  2015. outstream = StringIO()
  2016. porcelain.show(self.repo.path, objects=[cb.id], outstream=outstream)
  2017. self.assertMultiLineEqual(
  2018. outstream.getvalue(),
  2019. """\
  2020. --------------------------------------------------
  2021. commit: 2c6b6c9cb72c130956657e1fdae58e5b103744fa
  2022. Author: Test Author <test@nodomain.com>
  2023. Committer: Test Committer <test@nodomain.com>
  2024. Date: Fri Jan 01 2010 00:00:00 +0000
  2025. Test message.
  2026. diff --git a/somename b/somename
  2027. index ea5c7bf..fd38bcb 100644
  2028. --- a/somename
  2029. +++ b/somename
  2030. @@ -1 +1 @@
  2031. -The Foo
  2032. +The Bar
  2033. """,
  2034. )
  2035. class FormatPatchTests(PorcelainTestCase):
  2036. def test_format_patch_single_commit(self) -> None:
  2037. # Create initial commit
  2038. tree1 = Tree()
  2039. c1 = make_commit(
  2040. tree=tree1,
  2041. message=b"Initial commit",
  2042. )
  2043. self.repo.object_store.add_objects([(tree1, None), (c1, None)])
  2044. # Create second commit
  2045. b = Blob.from_string(b"modified")
  2046. tree = Tree()
  2047. tree.add(b"test.txt", 0o100644, b.id)
  2048. c2 = make_commit(
  2049. tree=tree,
  2050. parents=[c1.id],
  2051. message=b"Add test.txt",
  2052. )
  2053. self.repo.object_store.add_objects([(b, None), (tree, None), (c2, None)])
  2054. self.repo[b"HEAD"] = c2.id
  2055. # Generate patch for single commit
  2056. with tempfile.TemporaryDirectory() as tmpdir:
  2057. patches = porcelain.format_patch(
  2058. self.repo.path,
  2059. committish=c2.id,
  2060. outdir=tmpdir,
  2061. )
  2062. self.assertEqual(len(patches), 1)
  2063. self.assertTrue(patches[0].endswith("-Add-test.txt.patch"))
  2064. # Verify patch content
  2065. with open(patches[0], "rb") as f:
  2066. content = f.read()
  2067. self.assertIn(b"Subject: [PATCH 1/1] Add test.txt", content)
  2068. self.assertIn(b"+modified", content)
  2069. def test_format_patch_multiple_commits(self) -> None:
  2070. # Create commit chain
  2071. commits = []
  2072. for i in range(3):
  2073. blob = Blob.from_string(f"content {i}".encode())
  2074. tree = Tree()
  2075. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  2076. parents = [commits[-1].id] if commits else []
  2077. commit = make_commit(
  2078. tree=tree,
  2079. parents=parents,
  2080. message=f"Commit {i}".encode(),
  2081. )
  2082. self.repo.object_store.add_objects(
  2083. [(blob, None), (tree, None), (commit, None)]
  2084. )
  2085. commits.append(commit)
  2086. self.repo[b"HEAD"] = commits[-1].id
  2087. # Test generating last 2 commits
  2088. with tempfile.TemporaryDirectory() as tmpdir:
  2089. patches = porcelain.format_patch(
  2090. self.repo.path,
  2091. n=2,
  2092. outdir=tmpdir,
  2093. )
  2094. self.assertEqual(len(patches), 2)
  2095. self.assertTrue(patches[0].endswith("-Commit-1.patch"))
  2096. self.assertTrue(patches[1].endswith("-Commit-2.patch"))
  2097. # Check patch numbering
  2098. with open(patches[0], "rb") as f:
  2099. self.assertIn(b"Subject: [PATCH 1/2] Commit 1", f.read())
  2100. with open(patches[1], "rb") as f:
  2101. self.assertIn(b"Subject: [PATCH 2/2] Commit 2", f.read())
  2102. def test_format_patch_range(self) -> None:
  2103. # Create commit chain
  2104. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  2105. self.repo[b"HEAD"] = c3.id
  2106. # Test commit range
  2107. with tempfile.TemporaryDirectory() as tmpdir:
  2108. patches = porcelain.format_patch(
  2109. self.repo.path,
  2110. committish=(c1.id, c3.id),
  2111. outdir=tmpdir,
  2112. )
  2113. # Should include c2 and c3
  2114. self.assertEqual(len(patches), 2)
  2115. def test_format_patch_stdout(self) -> None:
  2116. # Create a commit
  2117. blob = Blob.from_string(b"test content")
  2118. tree = Tree()
  2119. tree.add(b"test.txt", 0o100644, blob.id)
  2120. commit = make_commit(
  2121. tree=tree,
  2122. message=b"Test commit",
  2123. )
  2124. self.repo.object_store.add_objects([(blob, None), (tree, None), (commit, None)])
  2125. self.repo[b"HEAD"] = commit.id
  2126. # Test stdout output
  2127. outstream = BytesIO()
  2128. patches = porcelain.format_patch(
  2129. self.repo.path,
  2130. committish=commit.id,
  2131. stdout=True,
  2132. outstream=outstream,
  2133. )
  2134. # Should return empty list when writing to stdout
  2135. self.assertEqual(patches, [])
  2136. # Check stdout content
  2137. outstream.seek(0)
  2138. content = outstream.read()
  2139. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  2140. self.assertIn(b"diff --git", content)
  2141. def test_format_patch_no_commits(self) -> None:
  2142. # Test with a new repository with no commits
  2143. # Just remove HEAD to simulate empty repo
  2144. patches = porcelain.format_patch(
  2145. self.repo.path,
  2146. n=5,
  2147. )
  2148. self.assertEqual(patches, [])
  2149. class SymbolicRefTests(PorcelainTestCase):
  2150. def test_set_wrong_symbolic_ref(self) -> None:
  2151. c1, c2, c3 = build_commit_graph(
  2152. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2153. )
  2154. self.repo.refs[b"HEAD"] = c3.id
  2155. self.assertRaises(
  2156. porcelain.Error, porcelain.symbolic_ref, self.repo.path, b"foobar"
  2157. )
  2158. def test_set_force_wrong_symbolic_ref(self) -> None:
  2159. c1, c2, c3 = build_commit_graph(
  2160. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2161. )
  2162. self.repo.refs[b"HEAD"] = c3.id
  2163. porcelain.symbolic_ref(self.repo.path, b"force_foobar", force=True)
  2164. # test if we actually changed the file
  2165. with self.repo.get_named_file("HEAD") as f:
  2166. new_ref = f.read()
  2167. self.assertEqual(new_ref, b"ref: refs/heads/force_foobar\n")
  2168. def test_set_symbolic_ref(self) -> None:
  2169. c1, c2, c3 = build_commit_graph(
  2170. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2171. )
  2172. self.repo.refs[b"HEAD"] = c3.id
  2173. porcelain.symbolic_ref(self.repo.path, b"master")
  2174. def test_set_symbolic_ref_other_than_master(self) -> None:
  2175. c1, c2, c3 = build_commit_graph(
  2176. self.repo.object_store,
  2177. [[1], [2, 1], [3, 1, 2]],
  2178. attrs=dict(refs="develop"),
  2179. )
  2180. self.repo.refs[b"HEAD"] = c3.id
  2181. self.repo.refs[b"refs/heads/develop"] = c3.id
  2182. porcelain.symbolic_ref(self.repo.path, b"develop")
  2183. # test if we actually changed the file
  2184. with self.repo.get_named_file("HEAD") as f:
  2185. new_ref = f.read()
  2186. self.assertEqual(new_ref, b"ref: refs/heads/develop\n")
  2187. class DiffTreeTests(PorcelainTestCase):
  2188. def test_empty(self) -> None:
  2189. c1, c2, c3 = build_commit_graph(
  2190. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2191. )
  2192. self.repo.refs[b"HEAD"] = c3.id
  2193. outstream = BytesIO()
  2194. porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream)
  2195. self.assertEqual(outstream.getvalue(), b"")
  2196. class DiffTests(PorcelainTestCase):
  2197. def test_diff_uncommitted_stage(self) -> None:
  2198. # Test diff in repository with no commits yet
  2199. fullpath = os.path.join(self.repo.path, "test.txt")
  2200. with open(fullpath, "w") as f:
  2201. f.write("Hello, world!\n")
  2202. porcelain.add(self.repo.path, paths=["test.txt"])
  2203. outstream = BytesIO()
  2204. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2205. diff_output = outstream.getvalue()
  2206. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2207. self.assertIn(b"new file mode", diff_output)
  2208. self.assertIn(b"+Hello, world!", diff_output)
  2209. def test_diff_uncommitted_working_tree(self) -> None:
  2210. # Test unstaged changes in repository with no commits
  2211. fullpath = os.path.join(self.repo.path, "test.txt")
  2212. with open(fullpath, "w") as f:
  2213. f.write("Hello, world!\n")
  2214. porcelain.add(self.repo.path, paths=["test.txt"])
  2215. # Modify file in working tree
  2216. with open(fullpath, "w") as f:
  2217. f.write("Hello, world!\nNew line\n")
  2218. outstream = BytesIO()
  2219. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2220. diff_output = outstream.getvalue()
  2221. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2222. self.assertIn(b"+New line", diff_output)
  2223. def test_diff_with_commits_staged(self) -> None:
  2224. # Test staged changes with existing commits
  2225. fullpath = os.path.join(self.repo.path, "test.txt")
  2226. with open(fullpath, "w") as f:
  2227. f.write("Initial content\n")
  2228. porcelain.add(self.repo.path, paths=["test.txt"])
  2229. porcelain.commit(self.repo.path, message=b"Initial commit")
  2230. # Modify and stage
  2231. with open(fullpath, "w") as f:
  2232. f.write("Initial content\nModified\n")
  2233. porcelain.add(self.repo.path, paths=["test.txt"])
  2234. outstream = BytesIO()
  2235. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2236. diff_output = outstream.getvalue()
  2237. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2238. self.assertIn(b"+Modified", diff_output)
  2239. def test_diff_with_commits_unstaged(self) -> None:
  2240. # Test unstaged changes with existing commits
  2241. fullpath = os.path.join(self.repo.path, "test.txt")
  2242. with open(fullpath, "w") as f:
  2243. f.write("Initial content\n")
  2244. porcelain.add(self.repo.path, paths=["test.txt"])
  2245. porcelain.commit(self.repo.path, message=b"Initial commit")
  2246. # Modify without staging
  2247. with open(fullpath, "w") as f:
  2248. f.write("Initial content\nModified\n")
  2249. outstream = BytesIO()
  2250. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2251. diff_output = outstream.getvalue()
  2252. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2253. self.assertIn(b"+Modified", diff_output)
  2254. def test_diff_file_deletion(self) -> None:
  2255. # Test showing file deletion
  2256. fullpath = os.path.join(self.repo.path, "test.txt")
  2257. with open(fullpath, "w") as f:
  2258. f.write("Content to delete\n")
  2259. porcelain.add(self.repo.path, paths=["test.txt"])
  2260. porcelain.commit(self.repo.path, message=b"Add file")
  2261. # Delete file
  2262. os.unlink(fullpath)
  2263. outstream = BytesIO()
  2264. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2265. diff_output = outstream.getvalue()
  2266. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2267. self.assertIn(b"deleted file mode", diff_output)
  2268. self.assertIn(b"-Content to delete", diff_output)
  2269. def test_diff_with_paths(self) -> None:
  2270. # Test diff with specific paths
  2271. # Create two files
  2272. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2273. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2274. with open(fullpath1, "w") as f:
  2275. f.write("File 1 content\n")
  2276. with open(fullpath2, "w") as f:
  2277. f.write("File 2 content\n")
  2278. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2279. porcelain.commit(self.repo.path, message=b"Add two files")
  2280. # Modify both files
  2281. with open(fullpath1, "w") as f:
  2282. f.write("File 1 modified\n")
  2283. with open(fullpath2, "w") as f:
  2284. f.write("File 2 modified\n")
  2285. # Test diff with specific path
  2286. outstream = BytesIO()
  2287. porcelain.diff(self.repo.path, paths=["file1.txt"], outstream=outstream)
  2288. diff_output = outstream.getvalue()
  2289. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2290. self.assertIn(b"-File 1 content", diff_output)
  2291. self.assertIn(b"+File 1 modified", diff_output)
  2292. # file2.txt should not appear in diff
  2293. self.assertNotIn(b"file2.txt", diff_output)
  2294. def test_diff_with_paths_multiple(self) -> None:
  2295. # Test diff with multiple paths
  2296. # Create three files
  2297. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2298. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2299. fullpath3 = os.path.join(self.repo.path, "file3.txt")
  2300. with open(fullpath1, "w") as f:
  2301. f.write("File 1 content\n")
  2302. with open(fullpath2, "w") as f:
  2303. f.write("File 2 content\n")
  2304. with open(fullpath3, "w") as f:
  2305. f.write("File 3 content\n")
  2306. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt", "file3.txt"])
  2307. porcelain.commit(self.repo.path, message=b"Add three files")
  2308. # Modify all files
  2309. with open(fullpath1, "w") as f:
  2310. f.write("File 1 modified\n")
  2311. with open(fullpath2, "w") as f:
  2312. f.write("File 2 modified\n")
  2313. with open(fullpath3, "w") as f:
  2314. f.write("File 3 modified\n")
  2315. # Test diff with two specific paths
  2316. outstream = BytesIO()
  2317. porcelain.diff(
  2318. self.repo.path, paths=["file1.txt", "file3.txt"], outstream=outstream
  2319. )
  2320. diff_output = outstream.getvalue()
  2321. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2322. self.assertIn(b"diff --git a/file3.txt b/file3.txt", diff_output)
  2323. # file2.txt should not appear in diff
  2324. self.assertNotIn(b"file2.txt", diff_output)
  2325. def test_diff_with_paths_directory(self) -> None:
  2326. # Test diff with directory paths
  2327. # Create files in subdirectory
  2328. os.mkdir(os.path.join(self.repo.path, "subdir"))
  2329. fullpath1 = os.path.join(self.repo.path, "subdir", "file1.txt")
  2330. fullpath2 = os.path.join(self.repo.path, "subdir", "file2.txt")
  2331. fullpath3 = os.path.join(self.repo.path, "root.txt")
  2332. with open(fullpath1, "w") as f:
  2333. f.write("Subdir file 1\n")
  2334. with open(fullpath2, "w") as f:
  2335. f.write("Subdir file 2\n")
  2336. with open(fullpath3, "w") as f:
  2337. f.write("Root file\n")
  2338. porcelain.add(
  2339. self.repo.path, paths=["subdir/file1.txt", "subdir/file2.txt", "root.txt"]
  2340. )
  2341. porcelain.commit(self.repo.path, message=b"Add files in subdir")
  2342. # Modify all files
  2343. with open(fullpath1, "w") as f:
  2344. f.write("Subdir file 1 modified\n")
  2345. with open(fullpath2, "w") as f:
  2346. f.write("Subdir file 2 modified\n")
  2347. with open(fullpath3, "w") as f:
  2348. f.write("Root file modified\n")
  2349. # Test diff with directory path
  2350. outstream = BytesIO()
  2351. porcelain.diff(self.repo.path, paths=["subdir"], outstream=outstream)
  2352. diff_output = outstream.getvalue()
  2353. self.assertIn(b"subdir/file1.txt", diff_output)
  2354. self.assertIn(b"subdir/file2.txt", diff_output)
  2355. # root.txt should not appear in diff
  2356. self.assertNotIn(b"root.txt", diff_output)
  2357. def test_diff_staged_with_paths(self) -> None:
  2358. # Test staged diff with specific paths
  2359. # Create two files
  2360. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2361. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2362. with open(fullpath1, "w") as f:
  2363. f.write("File 1 content\n")
  2364. with open(fullpath2, "w") as f:
  2365. f.write("File 2 content\n")
  2366. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2367. porcelain.commit(self.repo.path, message=b"Add two files")
  2368. # Modify and stage both files
  2369. with open(fullpath1, "w") as f:
  2370. f.write("File 1 staged\n")
  2371. with open(fullpath2, "w") as f:
  2372. f.write("File 2 staged\n")
  2373. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2374. # Test staged diff with specific path
  2375. outstream = BytesIO()
  2376. porcelain.diff(
  2377. self.repo.path, staged=True, paths=["file1.txt"], outstream=outstream
  2378. )
  2379. diff_output = outstream.getvalue()
  2380. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2381. self.assertIn(b"-File 1 content", diff_output)
  2382. self.assertIn(b"+File 1 staged", diff_output)
  2383. # file2.txt should not appear in diff
  2384. self.assertNotIn(b"file2.txt", diff_output)
  2385. def test_diff_with_commit_and_paths(self) -> None:
  2386. # Test diff against specific commit with paths
  2387. # Create initial file
  2388. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2389. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2390. with open(fullpath1, "w") as f:
  2391. f.write("Initial content 1\n")
  2392. with open(fullpath2, "w") as f:
  2393. f.write("Initial content 2\n")
  2394. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2395. first_commit = porcelain.commit(self.repo.path, message=b"Initial commit")
  2396. # Make second commit
  2397. with open(fullpath1, "w") as f:
  2398. f.write("Second content 1\n")
  2399. with open(fullpath2, "w") as f:
  2400. f.write("Second content 2\n")
  2401. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2402. porcelain.commit(self.repo.path, message=b"Second commit")
  2403. # Modify working tree
  2404. with open(fullpath1, "w") as f:
  2405. f.write("Working content 1\n")
  2406. with open(fullpath2, "w") as f:
  2407. f.write("Working content 2\n")
  2408. # Test diff against first commit with specific path
  2409. outstream = BytesIO()
  2410. porcelain.diff(
  2411. self.repo.path,
  2412. commit=first_commit,
  2413. paths=["file1.txt"],
  2414. outstream=outstream,
  2415. )
  2416. diff_output = outstream.getvalue()
  2417. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2418. self.assertIn(b"-Initial content 1", diff_output)
  2419. self.assertIn(b"+Working content 1", diff_output)
  2420. # file2.txt should not appear in diff
  2421. self.assertNotIn(b"file2.txt", diff_output)
  2422. class CommitTreeTests(PorcelainTestCase):
  2423. def test_simple(self) -> None:
  2424. c1, c2, c3 = build_commit_graph(
  2425. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2426. )
  2427. b = Blob()
  2428. b.data = b"foo the bar"
  2429. t = Tree()
  2430. t.add(b"somename", 0o100644, b.id)
  2431. self.repo.object_store.add_object(t)
  2432. self.repo.object_store.add_object(b)
  2433. sha = porcelain.commit_tree(
  2434. self.repo.path,
  2435. t.id,
  2436. message=b"Withcommit.",
  2437. author=b"Joe <joe@example.com>",
  2438. committer=b"Jane <jane@example.com>",
  2439. )
  2440. self.assertIsInstance(sha, bytes)
  2441. self.assertEqual(len(sha), 40)
  2442. class RevListTests(PorcelainTestCase):
  2443. def test_simple(self) -> None:
  2444. c1, c2, c3 = build_commit_graph(
  2445. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2446. )
  2447. outstream = BytesIO()
  2448. porcelain.rev_list(self.repo.path, [c3.id], outstream=outstream)
  2449. self.assertEqual(
  2450. c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue()
  2451. )
  2452. @skipIf(
  2453. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  2454. "gpgme not easily available or supported on Windows and PyPy",
  2455. )
  2456. class TagCreateSignTests(PorcelainGpgTestCase):
  2457. def test_default_key(self) -> None:
  2458. c1, c2, c3 = build_commit_graph(
  2459. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2460. )
  2461. self.repo.refs[b"HEAD"] = c3.id
  2462. cfg = self.repo.get_config()
  2463. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2464. self.import_default_key()
  2465. porcelain.tag_create(
  2466. self.repo.path,
  2467. b"tryme",
  2468. b"foo <foo@bar.com>",
  2469. b"bar",
  2470. annotated=True,
  2471. sign=True,
  2472. )
  2473. tags = self.repo.refs.as_dict(b"refs/tags")
  2474. self.assertEqual(list(tags.keys()), [b"tryme"])
  2475. tag = self.repo[b"refs/tags/tryme"]
  2476. self.assertIsInstance(tag, Tag)
  2477. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2478. self.assertEqual(b"bar\n", tag.message)
  2479. self.assertRecentTimestamp(tag.tag_time)
  2480. tag = self.repo[b"refs/tags/tryme"]
  2481. assert isinstance(tag, Tag)
  2482. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2483. tag.verify()
  2484. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2485. self.import_non_default_key()
  2486. self.assertRaises(
  2487. gpg.errors.MissingSignatures,
  2488. tag.verify,
  2489. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  2490. )
  2491. assert tag.signature is not None
  2492. tag._chunked_text = [b"bad data", tag.signature]
  2493. self.assertRaises(
  2494. gpg.errors.BadSignatures,
  2495. tag.verify,
  2496. )
  2497. def test_non_default_key(self) -> None:
  2498. c1, c2, c3 = build_commit_graph(
  2499. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2500. )
  2501. self.repo.refs[b"HEAD"] = c3.id
  2502. cfg = self.repo.get_config()
  2503. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2504. self.import_non_default_key()
  2505. porcelain.tag_create(
  2506. self.repo.path,
  2507. b"tryme",
  2508. b"foo <foo@bar.com>",
  2509. b"bar",
  2510. annotated=True,
  2511. sign=True,
  2512. )
  2513. tags = self.repo.refs.as_dict(b"refs/tags")
  2514. self.assertEqual(list(tags.keys()), [b"tryme"])
  2515. tag = self.repo[b"refs/tags/tryme"]
  2516. self.assertIsInstance(tag, Tag)
  2517. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2518. self.assertEqual(b"bar\n", tag.message)
  2519. self.assertRecentTimestamp(tag.tag_time)
  2520. tag = self.repo[b"refs/tags/tryme"]
  2521. assert isinstance(tag, Tag)
  2522. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2523. tag.verify()
  2524. def test_sign_uses_config_signingkey(self) -> None:
  2525. """Test that sign=True uses user.signingKey from config."""
  2526. c1, c2, c3 = build_commit_graph(
  2527. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2528. )
  2529. self.repo.refs[b"HEAD"] = c3.id
  2530. # Set up user.signingKey in config
  2531. cfg = self.repo.get_config()
  2532. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2533. cfg.write_to_path()
  2534. self.import_default_key()
  2535. # Create tag with sign=True (should use signingKey from config)
  2536. porcelain.tag_create(
  2537. self.repo.path,
  2538. b"signed-tag",
  2539. b"foo <foo@bar.com>",
  2540. b"Tag with configured key",
  2541. annotated=True,
  2542. sign=True, # This should read user.signingKey from config
  2543. )
  2544. tags = self.repo.refs.as_dict(b"refs/tags")
  2545. self.assertEqual(list(tags.keys()), [b"signed-tag"])
  2546. tag = self.repo[b"refs/tags/signed-tag"]
  2547. self.assertIsInstance(tag, Tag)
  2548. # Verify the tag is signed with the configured key
  2549. tag.verify()
  2550. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2551. def test_tag_gpg_sign_config_enabled(self) -> None:
  2552. """Test that tag.gpgSign=true automatically signs tags."""
  2553. c1, c2, c3 = build_commit_graph(
  2554. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2555. )
  2556. self.repo.refs[b"HEAD"] = c3.id
  2557. # Set up user.signingKey and tag.gpgSign in config
  2558. cfg = self.repo.get_config()
  2559. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2560. cfg.set(("tag",), "gpgSign", True)
  2561. cfg.write_to_path()
  2562. self.import_default_key()
  2563. # Create tag without explicit sign parameter (should auto-sign due to config)
  2564. porcelain.tag_create(
  2565. self.repo.path,
  2566. b"auto-signed-tag",
  2567. b"foo <foo@bar.com>",
  2568. b"Auto-signed tag",
  2569. annotated=True,
  2570. # No sign parameter - should use tag.gpgSign config
  2571. )
  2572. tags = self.repo.refs.as_dict(b"refs/tags")
  2573. self.assertEqual(list(tags.keys()), [b"auto-signed-tag"])
  2574. tag = self.repo[b"refs/tags/auto-signed-tag"]
  2575. self.assertIsInstance(tag, Tag)
  2576. # Verify the tag is signed due to config
  2577. tag.verify()
  2578. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2579. def test_tag_gpg_sign_config_disabled(self) -> None:
  2580. """Test that tag.gpgSign=false does not sign tags."""
  2581. c1, c2, c3 = build_commit_graph(
  2582. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2583. )
  2584. self.repo.refs[b"HEAD"] = c3.id
  2585. # Set up user.signingKey and tag.gpgSign=false in config
  2586. cfg = self.repo.get_config()
  2587. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2588. cfg.set(("tag",), "gpgSign", False)
  2589. cfg.write_to_path()
  2590. self.import_default_key()
  2591. # Create tag without explicit sign parameter (should not sign)
  2592. porcelain.tag_create(
  2593. self.repo.path,
  2594. b"unsigned-tag",
  2595. b"foo <foo@bar.com>",
  2596. b"Unsigned tag",
  2597. annotated=True,
  2598. # No sign parameter - should use tag.gpgSign=false config
  2599. )
  2600. tags = self.repo.refs.as_dict(b"refs/tags")
  2601. self.assertEqual(list(tags.keys()), [b"unsigned-tag"])
  2602. tag = self.repo[b"refs/tags/unsigned-tag"]
  2603. self.assertIsInstance(tag, Tag)
  2604. # Verify the tag is not signed
  2605. self.assertIsNone(tag._signature)
  2606. def test_tag_gpg_sign_config_no_signing_key(self) -> None:
  2607. """Test that tag.gpgSign=true works without user.signingKey (uses default)."""
  2608. c1, c2, c3 = build_commit_graph(
  2609. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2610. )
  2611. self.repo.refs[b"HEAD"] = c3.id
  2612. # Set up tag.gpgSign but no user.signingKey
  2613. cfg = self.repo.get_config()
  2614. cfg.set(("tag",), "gpgSign", True)
  2615. cfg.write_to_path()
  2616. self.import_default_key()
  2617. # Create tag without explicit sign parameter (should auto-sign with default key)
  2618. porcelain.tag_create(
  2619. self.repo.path,
  2620. b"default-signed-tag",
  2621. b"foo <foo@bar.com>",
  2622. b"Default signed tag",
  2623. annotated=True,
  2624. # No sign parameter - should use tag.gpgSign config with default key
  2625. )
  2626. tags = self.repo.refs.as_dict(b"refs/tags")
  2627. self.assertEqual(list(tags.keys()), [b"default-signed-tag"])
  2628. tag = self.repo[b"refs/tags/default-signed-tag"]
  2629. self.assertIsInstance(tag, Tag)
  2630. # Verify the tag is signed with default key
  2631. tag.verify()
  2632. def test_explicit_sign_overrides_config(self) -> None:
  2633. """Test that explicit sign parameter overrides tag.gpgSign config."""
  2634. c1, c2, c3 = build_commit_graph(
  2635. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2636. )
  2637. self.repo.refs[b"HEAD"] = c3.id
  2638. # Set up tag.gpgSign=false but explicitly pass sign=True
  2639. cfg = self.repo.get_config()
  2640. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2641. cfg.set(("tag",), "gpgSign", False)
  2642. cfg.write_to_path()
  2643. self.import_default_key()
  2644. # Create tag with explicit sign=True (should override config)
  2645. porcelain.tag_create(
  2646. self.repo.path,
  2647. b"explicit-signed-tag",
  2648. b"foo <foo@bar.com>",
  2649. b"Explicitly signed tag",
  2650. annotated=True,
  2651. sign=True, # This should override tag.gpgSign=false
  2652. )
  2653. tags = self.repo.refs.as_dict(b"refs/tags")
  2654. self.assertEqual(list(tags.keys()), [b"explicit-signed-tag"])
  2655. tag = self.repo[b"refs/tags/explicit-signed-tag"]
  2656. self.assertIsInstance(tag, Tag)
  2657. # Verify the tag is signed despite config=false
  2658. tag.verify()
  2659. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2660. def test_explicit_false_disables_tag_signing(self) -> None:
  2661. """Test that explicit sign=False disables signing even with config=true."""
  2662. c1, c2, c3 = build_commit_graph(
  2663. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2664. )
  2665. self.repo.refs[b"HEAD"] = c3.id
  2666. # Set up tag.gpgSign=true but explicitly pass sign=False
  2667. cfg = self.repo.get_config()
  2668. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2669. cfg.set(("tag",), "gpgSign", True)
  2670. cfg.write_to_path()
  2671. self.import_default_key()
  2672. # Create tag with explicit sign=False (should disable signing)
  2673. porcelain.tag_create(
  2674. self.repo.path,
  2675. b"explicit-unsigned-tag",
  2676. b"foo <foo@bar.com>",
  2677. b"Explicitly unsigned tag",
  2678. annotated=True,
  2679. sign=False, # This should override tag.gpgSign=true
  2680. )
  2681. tags = self.repo.refs.as_dict(b"refs/tags")
  2682. self.assertEqual(list(tags.keys()), [b"explicit-unsigned-tag"])
  2683. tag = self.repo[b"refs/tags/explicit-unsigned-tag"]
  2684. self.assertIsInstance(tag, Tag)
  2685. # Verify the tag is NOT signed despite config=true
  2686. self.assertIsNone(tag._signature)
  2687. class TagCreateTests(PorcelainTestCase):
  2688. def test_annotated(self) -> None:
  2689. c1, c2, c3 = build_commit_graph(
  2690. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2691. )
  2692. self.repo.refs[b"HEAD"] = c3.id
  2693. porcelain.tag_create(
  2694. self.repo.path,
  2695. b"tryme",
  2696. b"foo <foo@bar.com>",
  2697. b"bar",
  2698. annotated=True,
  2699. )
  2700. tags = self.repo.refs.as_dict(b"refs/tags")
  2701. self.assertEqual(list(tags.keys()), [b"tryme"])
  2702. tag = self.repo[b"refs/tags/tryme"]
  2703. self.assertIsInstance(tag, Tag)
  2704. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2705. self.assertEqual(b"bar\n", tag.message)
  2706. self.assertRecentTimestamp(tag.tag_time)
  2707. def test_unannotated(self) -> None:
  2708. c1, c2, c3 = build_commit_graph(
  2709. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2710. )
  2711. self.repo.refs[b"HEAD"] = c3.id
  2712. porcelain.tag_create(self.repo.path, b"tryme", annotated=False)
  2713. tags = self.repo.refs.as_dict(b"refs/tags")
  2714. self.assertEqual(list(tags.keys()), [b"tryme"])
  2715. self.repo[b"refs/tags/tryme"]
  2716. self.assertEqual(list(tags.values()), [self.repo.head()])
  2717. def test_unannotated_unicode(self) -> None:
  2718. c1, c2, c3 = build_commit_graph(
  2719. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2720. )
  2721. self.repo.refs[b"HEAD"] = c3.id
  2722. porcelain.tag_create(self.repo.path, "tryme", annotated=False)
  2723. tags = self.repo.refs.as_dict(b"refs/tags")
  2724. self.assertEqual(list(tags.keys()), [b"tryme"])
  2725. self.repo[b"refs/tags/tryme"]
  2726. self.assertEqual(list(tags.values()), [self.repo.head()])
  2727. class TagListTests(PorcelainTestCase):
  2728. def test_empty(self) -> None:
  2729. tags = porcelain.tag_list(self.repo.path)
  2730. self.assertEqual([], tags)
  2731. def test_simple(self) -> None:
  2732. self.repo.refs[b"refs/tags/foo"] = b"aa" * 20
  2733. self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20
  2734. tags = porcelain.tag_list(self.repo.path)
  2735. self.assertEqual([b"bar/bla", b"foo"], tags)
  2736. class TagDeleteTests(PorcelainTestCase):
  2737. def test_simple(self) -> None:
  2738. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  2739. self.repo[b"HEAD"] = c1.id
  2740. porcelain.tag_create(self.repo, b"foo")
  2741. self.assertIn(b"foo", porcelain.tag_list(self.repo))
  2742. porcelain.tag_delete(self.repo, b"foo")
  2743. self.assertNotIn(b"foo", porcelain.tag_list(self.repo))
  2744. class ResetTests(PorcelainTestCase):
  2745. def test_hard_head(self) -> None:
  2746. fullpath = os.path.join(self.repo.path, "foo")
  2747. with open(fullpath, "w") as f:
  2748. f.write("BAR")
  2749. porcelain.add(self.repo.path, paths=[fullpath])
  2750. porcelain.commit(
  2751. self.repo.path,
  2752. message=b"Some message",
  2753. committer=b"Jane <jane@example.com>",
  2754. author=b"John <john@example.com>",
  2755. )
  2756. with open(os.path.join(self.repo.path, "foo"), "wb") as f:
  2757. f.write(b"OOH")
  2758. porcelain.reset(self.repo, "hard", b"HEAD")
  2759. index = self.repo.open_index()
  2760. changes = list(
  2761. tree_changes(
  2762. self.repo.object_store,
  2763. index.commit(self.repo.object_store),
  2764. self.repo[b"HEAD"].tree,
  2765. )
  2766. )
  2767. self.assertEqual([], changes)
  2768. def test_hard_commit(self) -> None:
  2769. fullpath = os.path.join(self.repo.path, "foo")
  2770. with open(fullpath, "w") as f:
  2771. f.write("BAR")
  2772. porcelain.add(self.repo.path, paths=[fullpath])
  2773. sha = porcelain.commit(
  2774. self.repo.path,
  2775. message=b"Some message",
  2776. committer=b"Jane <jane@example.com>",
  2777. author=b"John <john@example.com>",
  2778. )
  2779. with open(fullpath, "wb") as f:
  2780. f.write(b"BAZ")
  2781. porcelain.add(self.repo.path, paths=[fullpath])
  2782. porcelain.commit(
  2783. self.repo.path,
  2784. message=b"Some other message",
  2785. committer=b"Jane <jane@example.com>",
  2786. author=b"John <john@example.com>",
  2787. )
  2788. porcelain.reset(self.repo, "hard", sha)
  2789. index = self.repo.open_index()
  2790. changes = list(
  2791. tree_changes(
  2792. self.repo.object_store,
  2793. index.commit(self.repo.object_store),
  2794. self.repo[sha].tree,
  2795. )
  2796. )
  2797. self.assertEqual([], changes)
  2798. def test_hard_commit_short_hash(self) -> None:
  2799. fullpath = os.path.join(self.repo.path, "foo")
  2800. with open(fullpath, "w") as f:
  2801. f.write("BAR")
  2802. porcelain.add(self.repo.path, paths=[fullpath])
  2803. sha = porcelain.commit(
  2804. self.repo.path,
  2805. message=b"Some message",
  2806. committer=b"Jane <jane@example.com>",
  2807. author=b"John <john@example.com>",
  2808. )
  2809. with open(fullpath, "wb") as f:
  2810. f.write(b"BAZ")
  2811. porcelain.add(self.repo.path, paths=[fullpath])
  2812. porcelain.commit(
  2813. self.repo.path,
  2814. message=b"Some other message",
  2815. committer=b"Jane <jane@example.com>",
  2816. author=b"John <john@example.com>",
  2817. )
  2818. # Test with short hash (7 characters)
  2819. short_sha = sha[:7].decode("ascii")
  2820. porcelain.reset(self.repo, "hard", short_sha)
  2821. index = self.repo.open_index()
  2822. changes = list(
  2823. tree_changes(
  2824. self.repo.object_store,
  2825. index.commit(self.repo.object_store),
  2826. self.repo[sha].tree,
  2827. )
  2828. )
  2829. self.assertEqual([], changes)
  2830. def test_hard_deletes_untracked_files(self) -> None:
  2831. """Test that reset --hard deletes files that don't exist in target tree."""
  2832. # Create and commit a file
  2833. fullpath = os.path.join(self.repo.path, "foo")
  2834. with open(fullpath, "w") as f:
  2835. f.write("BAR")
  2836. porcelain.add(self.repo.path, paths=[fullpath])
  2837. sha1 = porcelain.commit(
  2838. self.repo.path,
  2839. message=b"First commit",
  2840. committer=b"Jane <jane@example.com>",
  2841. author=b"John <john@example.com>",
  2842. )
  2843. # Create another file and commit
  2844. fullpath2 = os.path.join(self.repo.path, "bar")
  2845. with open(fullpath2, "w") as f:
  2846. f.write("BAZ")
  2847. porcelain.add(self.repo.path, paths=[fullpath2])
  2848. porcelain.commit(
  2849. self.repo.path,
  2850. message=b"Second commit",
  2851. committer=b"Jane <jane@example.com>",
  2852. author=b"John <john@example.com>",
  2853. )
  2854. # Reset hard to first commit - this should delete 'bar'
  2855. porcelain.reset(self.repo, "hard", sha1)
  2856. # Check that 'foo' still exists and 'bar' is deleted
  2857. self.assertTrue(os.path.exists(fullpath))
  2858. self.assertFalse(os.path.exists(fullpath2))
  2859. # Check index matches first commit
  2860. index = self.repo.open_index()
  2861. self.assertIn(b"foo", index)
  2862. self.assertNotIn(b"bar", index)
  2863. def test_hard_deletes_files_in_subdirs(self) -> None:
  2864. """Test that reset --hard deletes files in subdirectories."""
  2865. # Create and commit files in subdirectory
  2866. subdir = os.path.join(self.repo.path, "subdir")
  2867. os.makedirs(subdir)
  2868. file1 = os.path.join(subdir, "file1")
  2869. file2 = os.path.join(subdir, "file2")
  2870. with open(file1, "w") as f:
  2871. f.write("content1")
  2872. with open(file2, "w") as f:
  2873. f.write("content2")
  2874. porcelain.add(self.repo.path, paths=[file1, file2])
  2875. porcelain.commit(
  2876. self.repo.path,
  2877. message=b"First commit",
  2878. committer=b"Jane <jane@example.com>",
  2879. author=b"John <john@example.com>",
  2880. )
  2881. # Remove one file from subdirectory and commit
  2882. porcelain.rm(self.repo.path, paths=[file2])
  2883. sha2 = porcelain.commit(
  2884. self.repo.path,
  2885. message=b"Remove file2",
  2886. committer=b"Jane <jane@example.com>",
  2887. author=b"John <john@example.com>",
  2888. )
  2889. # Create file2 again (untracked)
  2890. with open(file2, "w") as f:
  2891. f.write("new content")
  2892. # Reset to commit that has file2 removed - should delete untracked file2
  2893. porcelain.reset(self.repo, "hard", sha2)
  2894. self.assertTrue(os.path.exists(file1))
  2895. self.assertFalse(os.path.exists(file2))
  2896. def test_hard_reset_to_remote_branch(self) -> None:
  2897. """Test reset --hard to remote branch deletes local files not in remote."""
  2898. # Create a file and commit
  2899. file1 = os.path.join(self.repo.path, "file1")
  2900. with open(file1, "w") as f:
  2901. f.write("content1")
  2902. porcelain.add(self.repo.path, paths=[file1])
  2903. sha1 = porcelain.commit(
  2904. self.repo.path,
  2905. message=b"Initial commit",
  2906. committer=b"Jane <jane@example.com>",
  2907. author=b"John <john@example.com>",
  2908. )
  2909. # Create a "remote" ref that doesn't have additional files
  2910. self.repo.refs[b"refs/remotes/origin/master"] = sha1
  2911. # Add another file locally and commit
  2912. file2 = os.path.join(self.repo.path, "file2")
  2913. with open(file2, "w") as f:
  2914. f.write("content2")
  2915. porcelain.add(self.repo.path, paths=[file2])
  2916. porcelain.commit(
  2917. self.repo.path,
  2918. message=b"Add file2",
  2919. committer=b"Jane <jane@example.com>",
  2920. author=b"John <john@example.com>",
  2921. )
  2922. # Both files should exist
  2923. self.assertTrue(os.path.exists(file1))
  2924. self.assertTrue(os.path.exists(file2))
  2925. # Reset to remote branch - should delete file2
  2926. porcelain.reset(self.repo, "hard", b"refs/remotes/origin/master")
  2927. # file1 should exist, file2 should be deleted
  2928. self.assertTrue(os.path.exists(file1))
  2929. self.assertFalse(os.path.exists(file2))
  2930. def test_mixed_reset(self) -> None:
  2931. # Create initial commit
  2932. fullpath = os.path.join(self.repo.path, "foo")
  2933. with open(fullpath, "w") as f:
  2934. f.write("BAR")
  2935. porcelain.add(self.repo.path, paths=[fullpath])
  2936. first_sha = porcelain.commit(
  2937. self.repo.path,
  2938. message=b"First commit",
  2939. committer=b"Jane <jane@example.com>",
  2940. author=b"John <john@example.com>",
  2941. )
  2942. # Make second commit with modified content
  2943. with open(fullpath, "w") as f:
  2944. f.write("BAZ")
  2945. porcelain.add(self.repo.path, paths=[fullpath])
  2946. porcelain.commit(
  2947. self.repo.path,
  2948. message=b"Second commit",
  2949. committer=b"Jane <jane@example.com>",
  2950. author=b"John <john@example.com>",
  2951. )
  2952. # Modify working tree without staging
  2953. with open(fullpath, "w") as f:
  2954. f.write("MODIFIED")
  2955. # Mixed reset to first commit
  2956. porcelain.reset(self.repo, "mixed", first_sha)
  2957. # Check that HEAD points to first commit
  2958. self.assertEqual(self.repo.head(), first_sha)
  2959. # Check that index matches first commit
  2960. index = self.repo.open_index()
  2961. changes = list(
  2962. tree_changes(
  2963. self.repo.object_store,
  2964. index.commit(self.repo.object_store),
  2965. self.repo[first_sha].tree,
  2966. )
  2967. )
  2968. self.assertEqual([], changes)
  2969. # Check that working tree is unchanged (still has "MODIFIED")
  2970. with open(fullpath) as f:
  2971. self.assertEqual(f.read(), "MODIFIED")
  2972. def test_soft_reset(self) -> None:
  2973. # Create initial commit
  2974. fullpath = os.path.join(self.repo.path, "foo")
  2975. with open(fullpath, "w") as f:
  2976. f.write("BAR")
  2977. porcelain.add(self.repo.path, paths=[fullpath])
  2978. first_sha = porcelain.commit(
  2979. self.repo.path,
  2980. message=b"First commit",
  2981. committer=b"Jane <jane@example.com>",
  2982. author=b"John <john@example.com>",
  2983. )
  2984. # Make second commit with modified content
  2985. with open(fullpath, "w") as f:
  2986. f.write("BAZ")
  2987. porcelain.add(self.repo.path, paths=[fullpath])
  2988. porcelain.commit(
  2989. self.repo.path,
  2990. message=b"Second commit",
  2991. committer=b"Jane <jane@example.com>",
  2992. author=b"John <john@example.com>",
  2993. )
  2994. # Stage a new change
  2995. with open(fullpath, "w") as f:
  2996. f.write("STAGED")
  2997. porcelain.add(self.repo.path, paths=[fullpath])
  2998. # Soft reset to first commit
  2999. porcelain.reset(self.repo, "soft", first_sha)
  3000. # Check that HEAD points to first commit
  3001. self.assertEqual(self.repo.head(), first_sha)
  3002. # Check that index still has the staged change (not reset)
  3003. index = self.repo.open_index()
  3004. # The index should still contain the staged content, not the first commit's content
  3005. self.assertIn(b"foo", index)
  3006. # Check that working tree is unchanged
  3007. with open(fullpath) as f:
  3008. self.assertEqual(f.read(), "STAGED")
  3009. class ResetFileTests(PorcelainTestCase):
  3010. def test_reset_modify_file_to_commit(self) -> None:
  3011. file = "foo"
  3012. full_path = os.path.join(self.repo.path, file)
  3013. with open(full_path, "w") as f:
  3014. f.write("hello")
  3015. porcelain.add(self.repo, paths=[full_path])
  3016. sha = porcelain.commit(
  3017. self.repo,
  3018. message=b"unitest",
  3019. committer=b"Jane <jane@example.com>",
  3020. author=b"John <john@example.com>",
  3021. )
  3022. with open(full_path, "a") as f:
  3023. f.write("something new")
  3024. porcelain.reset_file(self.repo, file, target=sha)
  3025. with open(full_path) as f:
  3026. self.assertEqual("hello", f.read())
  3027. def test_reset_remove_file_to_commit(self) -> None:
  3028. file = "foo"
  3029. full_path = os.path.join(self.repo.path, file)
  3030. with open(full_path, "w") as f:
  3031. f.write("hello")
  3032. porcelain.add(self.repo, paths=[full_path])
  3033. sha = porcelain.commit(
  3034. self.repo,
  3035. message=b"unitest",
  3036. committer=b"Jane <jane@example.com>",
  3037. author=b"John <john@example.com>",
  3038. )
  3039. os.remove(full_path)
  3040. porcelain.reset_file(self.repo, file, target=sha)
  3041. with open(full_path) as f:
  3042. self.assertEqual("hello", f.read())
  3043. def test_resetfile_with_dir(self) -> None:
  3044. os.mkdir(os.path.join(self.repo.path, "new_dir"))
  3045. full_path = os.path.join(self.repo.path, "new_dir", "foo")
  3046. with open(full_path, "w") as f:
  3047. f.write("hello")
  3048. porcelain.add(self.repo, paths=[full_path])
  3049. sha = porcelain.commit(
  3050. self.repo,
  3051. message=b"unitest",
  3052. committer=b"Jane <jane@example.com>",
  3053. author=b"John <john@example.com>",
  3054. )
  3055. with open(full_path, "a") as f:
  3056. f.write("something new")
  3057. porcelain.commit(
  3058. self.repo,
  3059. message=b"unitest 2",
  3060. committer=b"Jane <jane@example.com>",
  3061. author=b"John <john@example.com>",
  3062. )
  3063. porcelain.reset_file(self.repo, os.path.join("new_dir", "foo"), target=sha)
  3064. with open(full_path) as f:
  3065. self.assertEqual("hello", f.read())
  3066. def _commit_file_with_content(repo, filename, content):
  3067. file_path = os.path.join(repo.path, filename)
  3068. with open(file_path, "w") as f:
  3069. f.write(content)
  3070. porcelain.add(repo, paths=[file_path])
  3071. sha = porcelain.commit(
  3072. repo,
  3073. message=b"add " + filename.encode(),
  3074. committer=b"Jane <jane@example.com>",
  3075. author=b"John <john@example.com>",
  3076. )
  3077. return sha, file_path
  3078. class RevertTests(PorcelainTestCase):
  3079. def test_revert_simple(self) -> None:
  3080. # Create initial commit
  3081. fullpath = os.path.join(self.repo.path, "foo")
  3082. with open(fullpath, "w") as f:
  3083. f.write("initial content\n")
  3084. porcelain.add(self.repo.path, paths=[fullpath])
  3085. porcelain.commit(
  3086. self.repo.path,
  3087. message=b"Initial commit",
  3088. committer=b"Jane <jane@example.com>",
  3089. author=b"John <john@example.com>",
  3090. )
  3091. # Make a change
  3092. with open(fullpath, "w") as f:
  3093. f.write("modified content\n")
  3094. porcelain.add(self.repo.path, paths=[fullpath])
  3095. change_sha = porcelain.commit(
  3096. self.repo.path,
  3097. message=b"Change content",
  3098. committer=b"Jane <jane@example.com>",
  3099. author=b"John <john@example.com>",
  3100. )
  3101. # Revert the change
  3102. revert_sha = porcelain.revert(self.repo.path, commits=[change_sha])
  3103. # Check the file content is back to initial
  3104. with open(fullpath) as f:
  3105. self.assertEqual("initial content\n", f.read())
  3106. # Check the revert commit message
  3107. revert_commit = self.repo[revert_sha]
  3108. self.assertIn(b'Revert "Change content"', revert_commit.message)
  3109. self.assertIn(change_sha[:7], revert_commit.message)
  3110. def test_revert_multiple(self) -> None:
  3111. # Create initial commit
  3112. fullpath = os.path.join(self.repo.path, "foo")
  3113. with open(fullpath, "w") as f:
  3114. f.write("line1\n")
  3115. porcelain.add(self.repo.path, paths=[fullpath])
  3116. porcelain.commit(
  3117. self.repo.path,
  3118. message=b"Initial commit",
  3119. committer=b"Jane <jane@example.com>",
  3120. author=b"John <john@example.com>",
  3121. )
  3122. # Add line2
  3123. with open(fullpath, "a") as f:
  3124. f.write("line2\n")
  3125. porcelain.add(self.repo.path, paths=[fullpath])
  3126. commit1 = porcelain.commit(
  3127. self.repo.path,
  3128. message=b"Add line2",
  3129. committer=b"Jane <jane@example.com>",
  3130. author=b"John <john@example.com>",
  3131. )
  3132. # Add line3
  3133. with open(fullpath, "a") as f:
  3134. f.write("line3\n")
  3135. porcelain.add(self.repo.path, paths=[fullpath])
  3136. commit2 = porcelain.commit(
  3137. self.repo.path,
  3138. message=b"Add line3",
  3139. committer=b"Jane <jane@example.com>",
  3140. author=b"John <john@example.com>",
  3141. )
  3142. # Revert both commits (in reverse order)
  3143. porcelain.revert(self.repo.path, commits=[commit2, commit1])
  3144. # Check file is back to initial state
  3145. with open(fullpath) as f:
  3146. self.assertEqual("line1\n", f.read())
  3147. def test_revert_no_commit(self) -> None:
  3148. # Create initial commit
  3149. fullpath = os.path.join(self.repo.path, "foo")
  3150. with open(fullpath, "w") as f:
  3151. f.write("initial\n")
  3152. porcelain.add(self.repo.path, paths=[fullpath])
  3153. porcelain.commit(
  3154. self.repo.path,
  3155. message=b"Initial",
  3156. committer=b"Jane <jane@example.com>",
  3157. author=b"John <john@example.com>",
  3158. )
  3159. # Make a change
  3160. with open(fullpath, "w") as f:
  3161. f.write("changed\n")
  3162. porcelain.add(self.repo.path, paths=[fullpath])
  3163. change_sha = porcelain.commit(
  3164. self.repo.path,
  3165. message=b"Change",
  3166. committer=b"Jane <jane@example.com>",
  3167. author=b"John <john@example.com>",
  3168. )
  3169. # Revert with no_commit
  3170. result = porcelain.revert(self.repo.path, commits=[change_sha], no_commit=True)
  3171. # Should return None
  3172. self.assertIsNone(result)
  3173. # File should be reverted
  3174. with open(fullpath) as f:
  3175. self.assertEqual("initial\n", f.read())
  3176. # HEAD should still point to the change commit
  3177. self.assertEqual(self.repo.refs[b"HEAD"], change_sha)
  3178. def test_revert_custom_message(self) -> None:
  3179. # Create commits
  3180. fullpath = os.path.join(self.repo.path, "foo")
  3181. with open(fullpath, "w") as f:
  3182. f.write("initial\n")
  3183. porcelain.add(self.repo.path, paths=[fullpath])
  3184. porcelain.commit(
  3185. self.repo.path,
  3186. message=b"Initial",
  3187. committer=b"Jane <jane@example.com>",
  3188. author=b"John <john@example.com>",
  3189. )
  3190. with open(fullpath, "w") as f:
  3191. f.write("changed\n")
  3192. porcelain.add(self.repo.path, paths=[fullpath])
  3193. change_sha = porcelain.commit(
  3194. self.repo.path,
  3195. message=b"Change",
  3196. committer=b"Jane <jane@example.com>",
  3197. author=b"John <john@example.com>",
  3198. )
  3199. # Revert with custom message
  3200. custom_msg = "Custom revert message"
  3201. revert_sha = porcelain.revert(
  3202. self.repo.path, commits=[change_sha], message=custom_msg
  3203. )
  3204. # Check the message
  3205. revert_commit = self.repo[revert_sha]
  3206. self.assertEqual(custom_msg.encode("utf-8"), revert_commit.message)
  3207. def test_revert_no_parent(self) -> None:
  3208. # Try to revert the initial commit (no parent)
  3209. fullpath = os.path.join(self.repo.path, "foo")
  3210. with open(fullpath, "w") as f:
  3211. f.write("content\n")
  3212. porcelain.add(self.repo.path, paths=[fullpath])
  3213. initial_sha = porcelain.commit(
  3214. self.repo.path,
  3215. message=b"Initial",
  3216. committer=b"Jane <jane@example.com>",
  3217. author=b"John <john@example.com>",
  3218. )
  3219. # Should raise an error
  3220. with self.assertRaises(porcelain.Error) as cm:
  3221. porcelain.revert(self.repo.path, commits=[initial_sha])
  3222. self.assertIn("no parents", str(cm.exception))
  3223. class CheckoutTests(PorcelainTestCase):
  3224. def setUp(self) -> None:
  3225. super().setUp()
  3226. self._sha, self._foo_path = _commit_file_with_content(
  3227. self.repo, "foo", "hello\n"
  3228. )
  3229. porcelain.branch_create(self.repo, "uni")
  3230. def test_checkout_to_existing_branch(self) -> None:
  3231. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3232. porcelain.checkout(self.repo, b"uni")
  3233. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3234. def test_checkout_to_non_existing_branch(self) -> None:
  3235. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3236. with self.assertRaises(KeyError):
  3237. porcelain.checkout(self.repo, b"bob")
  3238. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3239. def test_checkout_to_branch_with_modified_files(self) -> None:
  3240. with open(self._foo_path, "a") as f:
  3241. f.write("new message\n")
  3242. porcelain.add(self.repo, paths=[self._foo_path])
  3243. status = list(porcelain.status(self.repo))
  3244. self.assertEqual(
  3245. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  3246. )
  3247. # The new checkout behavior prevents switching with staged changes
  3248. with self.assertRaises(porcelain.CheckoutError):
  3249. porcelain.checkout(self.repo, b"uni")
  3250. # Should still be on master
  3251. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3252. # Force checkout should work
  3253. porcelain.checkout(self.repo, b"uni", force=True)
  3254. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3255. def test_checkout_with_deleted_files(self) -> None:
  3256. porcelain.remove(self.repo.path, [os.path.join(self.repo.path, "foo")])
  3257. status = list(porcelain.status(self.repo))
  3258. self.assertEqual(
  3259. [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status
  3260. )
  3261. # The new checkout behavior prevents switching with staged deletions
  3262. with self.assertRaises(porcelain.CheckoutError):
  3263. porcelain.checkout(self.repo, b"uni")
  3264. # Should still be on master
  3265. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3266. # Force checkout should work
  3267. porcelain.checkout(self.repo, b"uni", force=True)
  3268. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3269. def test_checkout_to_branch_with_added_files(self) -> None:
  3270. file_path = os.path.join(self.repo.path, "bar")
  3271. with open(file_path, "w") as f:
  3272. f.write("bar content\n")
  3273. porcelain.add(self.repo, paths=[file_path])
  3274. status = list(porcelain.status(self.repo))
  3275. self.assertEqual(
  3276. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3277. )
  3278. # Both branches have file 'foo' checkout should be fine.
  3279. porcelain.checkout(self.repo, b"uni")
  3280. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3281. status = list(porcelain.status(self.repo))
  3282. self.assertEqual(
  3283. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3284. )
  3285. def test_checkout_to_branch_with_modified_file_not_present(self) -> None:
  3286. # Commit a new file that the other branch doesn't have.
  3287. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3288. # Modify the file the other branch doesn't have.
  3289. with open(nee_path, "a") as f:
  3290. f.write("bar content\n")
  3291. porcelain.add(self.repo, paths=[nee_path])
  3292. status = list(porcelain.status(self.repo))
  3293. self.assertEqual(
  3294. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3295. )
  3296. # The new checkout behavior allows switching if the file doesn't exist in target branch
  3297. # (changes can be preserved)
  3298. porcelain.checkout(self.repo, b"uni")
  3299. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3300. # The staged changes are lost and the file is removed from working tree
  3301. # because it doesn't exist in the target branch
  3302. status = list(porcelain.status(self.repo))
  3303. # File 'nee' is gone completely
  3304. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3305. self.assertFalse(os.path.exists(nee_path))
  3306. def test_checkout_to_branch_with_modified_file_not_present_forced(self) -> None:
  3307. # Commit a new file that the other branch doesn't have.
  3308. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3309. # Modify the file the other branch doesn't have.
  3310. with open(nee_path, "a") as f:
  3311. f.write("bar content\n")
  3312. porcelain.add(self.repo, paths=[nee_path])
  3313. status = list(porcelain.status(self.repo))
  3314. self.assertEqual(
  3315. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3316. )
  3317. # 'uni' branch doesn't have 'nee' and it has been modified, but we force to reset the entire index.
  3318. porcelain.checkout(self.repo, b"uni", force=True)
  3319. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3320. status = list(porcelain.status(self.repo))
  3321. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3322. def test_checkout_to_branch_with_unstaged_files(self) -> None:
  3323. # Edit `foo`.
  3324. with open(self._foo_path, "a") as f:
  3325. f.write("new message")
  3326. status = list(porcelain.status(self.repo))
  3327. self.assertEqual(
  3328. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  3329. )
  3330. # The new checkout behavior prevents switching with unstaged changes
  3331. with self.assertRaises(porcelain.CheckoutError):
  3332. porcelain.checkout(self.repo, b"uni")
  3333. # Should still be on master
  3334. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3335. # Force checkout should work
  3336. porcelain.checkout(self.repo, b"uni", force=True)
  3337. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3338. def test_checkout_to_branch_with_untracked_files(self) -> None:
  3339. with open(os.path.join(self.repo.path, "neu"), "a") as f:
  3340. f.write("new message\n")
  3341. status = list(porcelain.status(self.repo))
  3342. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3343. porcelain.checkout(self.repo, b"uni")
  3344. status = list(porcelain.status(self.repo))
  3345. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3346. def test_checkout_to_branch_with_new_files(self) -> None:
  3347. porcelain.checkout(self.repo, b"uni")
  3348. sub_directory = os.path.join(self.repo.path, "sub1")
  3349. os.mkdir(sub_directory)
  3350. for index in range(5):
  3351. _commit_file_with_content(
  3352. self.repo, "new_file_" + str(index + 1), "Some content\n"
  3353. )
  3354. _commit_file_with_content(
  3355. self.repo,
  3356. os.path.join("sub1", "new_file_" + str(index + 10)),
  3357. "Good content\n",
  3358. )
  3359. status = list(porcelain.status(self.repo))
  3360. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3361. porcelain.checkout(self.repo, b"master")
  3362. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3363. status = list(porcelain.status(self.repo))
  3364. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3365. porcelain.checkout(self.repo, b"uni")
  3366. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3367. status = list(porcelain.status(self.repo))
  3368. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3369. def test_checkout_to_branch_with_file_in_sub_directory(self) -> None:
  3370. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3371. os.makedirs(sub_directory)
  3372. sub_directory_file = os.path.join(sub_directory, "neu")
  3373. with open(sub_directory_file, "w") as f:
  3374. f.write("new message\n")
  3375. porcelain.add(self.repo, paths=[sub_directory_file])
  3376. porcelain.commit(
  3377. self.repo,
  3378. message=b"add " + sub_directory_file.encode(),
  3379. committer=b"Jane <jane@example.com>",
  3380. author=b"John <john@example.com>",
  3381. )
  3382. status = list(porcelain.status(self.repo))
  3383. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3384. self.assertTrue(os.path.isdir(sub_directory))
  3385. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3386. porcelain.checkout(self.repo, b"uni")
  3387. status = list(porcelain.status(self.repo))
  3388. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3389. self.assertFalse(os.path.isdir(sub_directory))
  3390. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3391. porcelain.checkout(self.repo, b"master")
  3392. self.assertTrue(os.path.isdir(sub_directory))
  3393. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3394. def test_checkout_to_branch_with_multiple_files_in_sub_directory(self) -> None:
  3395. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3396. os.makedirs(sub_directory)
  3397. sub_directory_file_1 = os.path.join(sub_directory, "neu")
  3398. with open(sub_directory_file_1, "w") as f:
  3399. f.write("new message\n")
  3400. sub_directory_file_2 = os.path.join(sub_directory, "gus")
  3401. with open(sub_directory_file_2, "w") as f:
  3402. f.write("alternative message\n")
  3403. porcelain.add(self.repo, paths=[sub_directory_file_1, sub_directory_file_2])
  3404. porcelain.commit(
  3405. self.repo,
  3406. message=b"add files neu and gus.",
  3407. committer=b"Jane <jane@example.com>",
  3408. author=b"John <john@example.com>",
  3409. )
  3410. status = list(porcelain.status(self.repo))
  3411. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3412. self.assertTrue(os.path.isdir(sub_directory))
  3413. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3414. porcelain.checkout(self.repo, b"uni")
  3415. status = list(porcelain.status(self.repo))
  3416. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3417. self.assertFalse(os.path.isdir(sub_directory))
  3418. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3419. def _commit_something_wrong(self):
  3420. with open(self._foo_path, "a") as f:
  3421. f.write("something wrong")
  3422. porcelain.add(self.repo, paths=[self._foo_path])
  3423. return porcelain.commit(
  3424. self.repo,
  3425. message=b"I may added something wrong",
  3426. committer=b"Jane <jane@example.com>",
  3427. author=b"John <john@example.com>",
  3428. )
  3429. def test_checkout_to_commit_sha(self) -> None:
  3430. self._commit_something_wrong()
  3431. porcelain.checkout(self.repo, self._sha)
  3432. self.assertEqual(self._sha, self.repo.head())
  3433. def test_checkout_to_head(self) -> None:
  3434. new_sha = self._commit_something_wrong()
  3435. porcelain.checkout(self.repo, b"HEAD")
  3436. self.assertEqual(new_sha, self.repo.head())
  3437. def _checkout_remote_branch(self):
  3438. errstream = BytesIO()
  3439. outstream = BytesIO()
  3440. porcelain.commit(
  3441. repo=self.repo.path,
  3442. message=b"init",
  3443. author=b"author <email>",
  3444. committer=b"committer <email>",
  3445. )
  3446. # Setup target repo cloned from temp test repo
  3447. clone_path = tempfile.mkdtemp()
  3448. self.addCleanup(shutil.rmtree, clone_path)
  3449. target_repo = porcelain.clone(
  3450. self.repo.path, target=clone_path, errstream=errstream
  3451. )
  3452. self.addCleanup(target_repo.close)
  3453. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  3454. # create a second file to be pushed back to origin
  3455. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3456. os.close(handle)
  3457. porcelain.add(repo=clone_path, paths=[fullpath])
  3458. porcelain.commit(
  3459. repo=clone_path,
  3460. message=b"push",
  3461. author=b"author <email>",
  3462. committer=b"committer <email>",
  3463. )
  3464. # Setup a non-checked out branch in the remote
  3465. refs_path = b"refs/heads/foo"
  3466. new_id = self.repo[b"HEAD"].id
  3467. self.assertNotEqual(new_id, ZERO_SHA)
  3468. self.repo.refs[refs_path] = new_id
  3469. # Push to the remote
  3470. porcelain.push(
  3471. clone_path,
  3472. "origin",
  3473. b"HEAD:" + refs_path,
  3474. outstream=outstream,
  3475. errstream=errstream,
  3476. )
  3477. self.assertEqual(
  3478. target_repo.refs[b"refs/remotes/origin/foo"],
  3479. target_repo.refs[b"HEAD"],
  3480. )
  3481. # The new checkout behavior treats origin/foo as a ref and creates detached HEAD
  3482. porcelain.checkout(target_repo, b"origin/foo")
  3483. original_id = target_repo[b"HEAD"].id
  3484. uni_id = target_repo[b"refs/remotes/origin/uni"].id
  3485. # Should be in detached HEAD state
  3486. with self.assertRaises((ValueError, IndexError)):
  3487. porcelain.active_branch(target_repo)
  3488. expected_refs = {
  3489. b"HEAD": original_id,
  3490. b"refs/heads/master": original_id,
  3491. # No local foo branch is created anymore
  3492. b"refs/remotes/origin/foo": original_id,
  3493. b"refs/remotes/origin/uni": uni_id,
  3494. b"refs/remotes/origin/HEAD": new_id,
  3495. b"refs/remotes/origin/master": new_id,
  3496. }
  3497. self.assertEqual(expected_refs, target_repo.get_refs())
  3498. return target_repo
  3499. def test_checkout_remote_branch(self) -> None:
  3500. repo = self._checkout_remote_branch()
  3501. repo.close()
  3502. def test_checkout_remote_branch_then_master_then_remote_branch_again(self) -> None:
  3503. target_repo = self._checkout_remote_branch()
  3504. # Should be in detached HEAD state
  3505. with self.assertRaises((ValueError, IndexError)):
  3506. porcelain.active_branch(target_repo)
  3507. # Save the commit SHA before adding bar
  3508. detached_commit_sha, _ = _commit_file_with_content(
  3509. target_repo, "bar", "something\n"
  3510. )
  3511. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3512. porcelain.checkout(target_repo, b"master")
  3513. self.assertEqual(b"master", porcelain.active_branch(target_repo))
  3514. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3515. # Going back to origin/foo won't have bar because the commit was made in detached state
  3516. porcelain.checkout(target_repo, b"origin/foo")
  3517. # Should be in detached HEAD state again
  3518. with self.assertRaises((ValueError, IndexError)):
  3519. porcelain.active_branch(target_repo)
  3520. # bar is NOT there because we're back at the original origin/foo commit
  3521. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3522. # But we can checkout the specific commit to get bar back
  3523. porcelain.checkout(target_repo, detached_commit_sha.decode())
  3524. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3525. target_repo.close()
  3526. def test_checkout_new_branch_from_remote_sets_tracking(self) -> None:
  3527. # Create a "remote" repository
  3528. remote_path = tempfile.mkdtemp()
  3529. self.addCleanup(shutil.rmtree, remote_path)
  3530. remote_repo = porcelain.init(remote_path)
  3531. # Add a commit to the remote
  3532. remote_sha, _ = _commit_file_with_content(
  3533. remote_repo, "bar", "remote content\n"
  3534. )
  3535. # Clone the remote repository
  3536. target_path = tempfile.mkdtemp()
  3537. self.addCleanup(shutil.rmtree, target_path)
  3538. target_repo = porcelain.clone(remote_path, target_path)
  3539. self.addCleanup(target_repo.close)
  3540. # Create a remote tracking branch reference
  3541. remote_branch_ref = b"refs/remotes/origin/feature"
  3542. target_repo.refs[remote_branch_ref] = remote_sha
  3543. # Checkout a new branch from the remote branch
  3544. porcelain.checkout(target_repo, remote_branch_ref, new_branch=b"local-feature")
  3545. # Verify the branch was created and is active
  3546. self.assertEqual(b"local-feature", porcelain.active_branch(target_repo))
  3547. # Verify tracking configuration was set
  3548. config = target_repo.get_config()
  3549. self.assertEqual(
  3550. b"origin", config.get((b"branch", b"local-feature"), b"remote")
  3551. )
  3552. self.assertEqual(
  3553. b"refs/heads/feature", config.get((b"branch", b"local-feature"), b"merge")
  3554. )
  3555. target_repo.close()
  3556. remote_repo.close()
  3557. class GeneralCheckoutTests(PorcelainTestCase):
  3558. """Tests for the general checkout function that handles branches, tags, and commits."""
  3559. def setUp(self) -> None:
  3560. super().setUp()
  3561. # Create initial commit
  3562. self._sha1, self._foo_path = _commit_file_with_content(
  3563. self.repo, "foo", "initial content\n"
  3564. )
  3565. # Create a branch
  3566. porcelain.branch_create(self.repo, "feature")
  3567. # Create another commit on master
  3568. self._sha2, self._bar_path = _commit_file_with_content(
  3569. self.repo, "bar", "bar content\n"
  3570. )
  3571. # Create a tag
  3572. porcelain.tag_create(self.repo, "v1.0", objectish=self._sha1)
  3573. def test_checkout_branch(self) -> None:
  3574. """Test checking out a branch."""
  3575. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3576. # Checkout feature branch
  3577. porcelain.checkout(self.repo, "feature")
  3578. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3579. # File 'bar' should not exist in feature branch
  3580. self.assertFalse(os.path.exists(self._bar_path))
  3581. # Go back to master
  3582. porcelain.checkout(self.repo, "master")
  3583. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3584. # File 'bar' should exist again
  3585. self.assertTrue(os.path.exists(self._bar_path))
  3586. def test_checkout_commit(self) -> None:
  3587. """Test checking out a specific commit (detached HEAD)."""
  3588. # Checkout first commit by SHA
  3589. porcelain.checkout(self.repo, self._sha1.decode("ascii"))
  3590. # Should be in detached HEAD state - active_branch raises IndexError
  3591. with self.assertRaises((ValueError, IndexError)):
  3592. porcelain.active_branch(self.repo)
  3593. # File 'bar' should not exist
  3594. self.assertFalse(os.path.exists(self._bar_path))
  3595. # HEAD should point to the commit
  3596. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3597. def test_checkout_tag(self) -> None:
  3598. """Test checking out a tag (detached HEAD)."""
  3599. # Checkout tag
  3600. porcelain.checkout(self.repo, "v1.0")
  3601. # Should be in detached HEAD state - active_branch raises IndexError
  3602. with self.assertRaises((ValueError, IndexError)):
  3603. porcelain.active_branch(self.repo)
  3604. # File 'bar' should not exist (tag points to first commit)
  3605. self.assertFalse(os.path.exists(self._bar_path))
  3606. # HEAD should point to the tagged commit
  3607. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3608. def test_checkout_new_branch(self) -> None:
  3609. """Test creating a new branch during checkout (like git checkout -b)."""
  3610. # Create and checkout new branch from current HEAD
  3611. porcelain.checkout(self.repo, "master", new_branch="new-feature")
  3612. self.assertEqual(b"new-feature", porcelain.active_branch(self.repo))
  3613. self.assertTrue(os.path.exists(self._bar_path))
  3614. # Create and checkout new branch from specific commit
  3615. porcelain.checkout(self.repo, self._sha1.decode("ascii"), new_branch="from-old")
  3616. self.assertEqual(b"from-old", porcelain.active_branch(self.repo))
  3617. self.assertFalse(os.path.exists(self._bar_path))
  3618. def test_checkout_with_uncommitted_changes(self) -> None:
  3619. """Test checkout behavior with uncommitted changes."""
  3620. # Modify a file
  3621. with open(self._foo_path, "w") as f:
  3622. f.write("modified content\n")
  3623. # Should raise error when trying to checkout
  3624. with self.assertRaises(porcelain.CheckoutError) as cm:
  3625. porcelain.checkout(self.repo, "feature")
  3626. self.assertIn("local changes", str(cm.exception))
  3627. self.assertIn("foo", str(cm.exception))
  3628. # Should still be on master
  3629. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3630. def test_checkout_force(self) -> None:
  3631. """Test forced checkout discards local changes."""
  3632. # Modify a file
  3633. with open(self._foo_path, "w") as f:
  3634. f.write("modified content\n")
  3635. # Force checkout should succeed
  3636. porcelain.checkout(self.repo, "feature", force=True)
  3637. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3638. # Local changes should be discarded
  3639. with open(self._foo_path) as f:
  3640. content = f.read()
  3641. self.assertEqual("initial content\n", content)
  3642. def test_checkout_nonexistent_ref(self) -> None:
  3643. """Test checkout of non-existent branch/commit."""
  3644. with self.assertRaises(KeyError):
  3645. porcelain.checkout(self.repo, "nonexistent")
  3646. def test_checkout_partial_sha(self) -> None:
  3647. """Test checkout with partial SHA."""
  3648. # Git typically allows checkout with partial SHA
  3649. partial_sha = self._sha1.decode("ascii")[:7]
  3650. porcelain.checkout(self.repo, partial_sha)
  3651. # Should be in detached HEAD state at the right commit
  3652. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3653. def test_checkout_preserves_untracked_files(self) -> None:
  3654. """Test that checkout preserves untracked files."""
  3655. # Create an untracked file
  3656. untracked_path = os.path.join(self.repo.path, "untracked.txt")
  3657. with open(untracked_path, "w") as f:
  3658. f.write("untracked content\n")
  3659. # Checkout another branch
  3660. porcelain.checkout(self.repo, "feature")
  3661. # Untracked file should still exist
  3662. self.assertTrue(os.path.exists(untracked_path))
  3663. with open(untracked_path) as f:
  3664. content = f.read()
  3665. self.assertEqual("untracked content\n", content)
  3666. def test_checkout_full_ref_paths(self) -> None:
  3667. """Test checkout with full ref paths."""
  3668. # Test checkout with full branch ref path
  3669. porcelain.checkout(self.repo, "refs/heads/feature")
  3670. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3671. # Test checkout with full tag ref path
  3672. porcelain.checkout(self.repo, "refs/tags/v1.0")
  3673. # Should be in detached HEAD state
  3674. with self.assertRaises((ValueError, IndexError)):
  3675. porcelain.active_branch(self.repo)
  3676. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3677. def test_checkout_bytes_vs_string_target(self) -> None:
  3678. """Test that checkout works with both bytes and string targets."""
  3679. # Test with string target
  3680. porcelain.checkout(self.repo, "feature")
  3681. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3682. # Test with bytes target
  3683. porcelain.checkout(self.repo, b"master")
  3684. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3685. def test_checkout_new_branch_from_commit(self) -> None:
  3686. """Test creating a new branch from a specific commit."""
  3687. # Create new branch from first commit
  3688. porcelain.checkout(self.repo, self._sha1.decode(), new_branch="from-commit")
  3689. self.assertEqual(b"from-commit", porcelain.active_branch(self.repo))
  3690. # Should be at the first commit (no bar file)
  3691. self.assertFalse(os.path.exists(self._bar_path))
  3692. def test_checkout_with_staged_addition(self) -> None:
  3693. """Test checkout behavior with staged file additions."""
  3694. # Create and stage a new file that doesn't exist in target branch
  3695. new_file_path = os.path.join(self.repo.path, "new.txt")
  3696. with open(new_file_path, "w") as f:
  3697. f.write("new file content\n")
  3698. porcelain.add(self.repo, [new_file_path])
  3699. # This should succeed because the file doesn't exist in target branch
  3700. porcelain.checkout(self.repo, "feature")
  3701. # Should be on feature branch
  3702. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3703. # The new file should still exist and be staged
  3704. self.assertTrue(os.path.exists(new_file_path))
  3705. status = porcelain.status(self.repo)
  3706. self.assertIn(b"new.txt", status.staged["add"])
  3707. def test_checkout_with_staged_modification_conflict(self) -> None:
  3708. """Test checkout behavior with staged modifications that would conflict."""
  3709. # Stage changes to a file that exists in both branches
  3710. with open(self._foo_path, "w") as f:
  3711. f.write("modified content\n")
  3712. porcelain.add(self.repo, [self._foo_path])
  3713. # Should prevent checkout due to staged changes to existing file
  3714. with self.assertRaises(porcelain.CheckoutError) as cm:
  3715. porcelain.checkout(self.repo, "feature")
  3716. self.assertIn("local changes", str(cm.exception))
  3717. self.assertIn("foo", str(cm.exception))
  3718. def test_checkout_head_reference(self) -> None:
  3719. """Test checkout of HEAD reference."""
  3720. # Move to feature branch first
  3721. porcelain.checkout(self.repo, "feature")
  3722. # Checkout HEAD creates detached HEAD state
  3723. porcelain.checkout(self.repo, "HEAD")
  3724. # Should be in detached HEAD state
  3725. with self.assertRaises((ValueError, IndexError)):
  3726. porcelain.active_branch(self.repo)
  3727. def test_checkout_error_messages(self) -> None:
  3728. """Test that checkout error messages are helpful."""
  3729. # Create uncommitted changes
  3730. with open(self._foo_path, "w") as f:
  3731. f.write("uncommitted changes\n")
  3732. # Try to checkout
  3733. with self.assertRaises(porcelain.CheckoutError) as cm:
  3734. porcelain.checkout(self.repo, "feature")
  3735. error_msg = str(cm.exception)
  3736. self.assertIn("local changes", error_msg)
  3737. self.assertIn("foo", error_msg)
  3738. self.assertIn("overwritten", error_msg)
  3739. self.assertIn("commit or stash", error_msg)
  3740. class SubmoduleTests(PorcelainTestCase):
  3741. def test_empty(self) -> None:
  3742. porcelain.commit(
  3743. repo=self.repo.path,
  3744. message=b"init",
  3745. author=b"author <email>",
  3746. committer=b"committer <email>",
  3747. )
  3748. self.assertEqual([], list(porcelain.submodule_list(self.repo)))
  3749. def test_add(self) -> None:
  3750. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  3751. with open(f"{self.repo.path}/.gitmodules") as f:
  3752. self.assertEqual(
  3753. """\
  3754. [submodule "bar"]
  3755. \turl = ../bar.git
  3756. \tpath = bar
  3757. """,
  3758. f.read(),
  3759. )
  3760. def test_init(self) -> None:
  3761. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  3762. porcelain.submodule_init(self.repo)
  3763. def test_update(self) -> None:
  3764. # Create a submodule repository
  3765. sub_repo_path = tempfile.mkdtemp()
  3766. self.addCleanup(shutil.rmtree, sub_repo_path)
  3767. sub_repo = Repo.init(sub_repo_path)
  3768. self.addCleanup(sub_repo.close)
  3769. # Add a file to the submodule repo
  3770. sub_file = os.path.join(sub_repo_path, "test.txt")
  3771. with open(sub_file, "w") as f:
  3772. f.write("submodule content")
  3773. porcelain.add(sub_repo, paths=[sub_file])
  3774. sub_commit = porcelain.commit(
  3775. sub_repo,
  3776. message=b"Initial submodule commit",
  3777. author=b"Test Author <test@example.com>",
  3778. committer=b"Test Committer <test@example.com>",
  3779. )
  3780. # Add the submodule to the main repository
  3781. porcelain.submodule_add(self.repo, sub_repo_path, "test_submodule")
  3782. # Manually add the submodule to the index
  3783. from dulwich.index import IndexEntry
  3784. from dulwich.objects import S_IFGITLINK
  3785. index = self.repo.open_index()
  3786. index[b"test_submodule"] = IndexEntry(
  3787. ctime=0,
  3788. mtime=0,
  3789. dev=0,
  3790. ino=0,
  3791. mode=S_IFGITLINK,
  3792. uid=0,
  3793. gid=0,
  3794. size=0,
  3795. sha=sub_commit,
  3796. flags=0,
  3797. )
  3798. index.write()
  3799. porcelain.add(self.repo, paths=[".gitmodules"])
  3800. porcelain.commit(
  3801. self.repo,
  3802. message=b"Add submodule",
  3803. author=b"Test Author <test@example.com>",
  3804. committer=b"Test Committer <test@example.com>",
  3805. )
  3806. # Initialize and update the submodule
  3807. porcelain.submodule_init(self.repo)
  3808. porcelain.submodule_update(self.repo)
  3809. # Check that the submodule directory exists
  3810. submodule_path = os.path.join(self.repo.path, "test_submodule")
  3811. self.assertTrue(os.path.exists(submodule_path))
  3812. # Check that the submodule file exists
  3813. submodule_file = os.path.join(submodule_path, "test.txt")
  3814. self.assertTrue(os.path.exists(submodule_file))
  3815. with open(submodule_file) as f:
  3816. self.assertEqual(f.read(), "submodule content")
  3817. class PushTests(PorcelainTestCase):
  3818. def test_simple(self) -> None:
  3819. """Basic test of porcelain push where self.repo is the remote. First
  3820. clone the remote, commit a file to the clone, then push the changes
  3821. back to the remote.
  3822. """
  3823. outstream = BytesIO()
  3824. errstream = BytesIO()
  3825. porcelain.commit(
  3826. repo=self.repo.path,
  3827. message=b"init",
  3828. author=b"author <email>",
  3829. committer=b"committer <email>",
  3830. )
  3831. # Setup target repo cloned from temp test repo
  3832. clone_path = tempfile.mkdtemp()
  3833. self.addCleanup(shutil.rmtree, clone_path)
  3834. target_repo = porcelain.clone(
  3835. self.repo.path, target=clone_path, errstream=errstream
  3836. )
  3837. self.addCleanup(target_repo.close)
  3838. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  3839. # create a second file to be pushed back to origin
  3840. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3841. os.close(handle)
  3842. porcelain.add(repo=clone_path, paths=[fullpath])
  3843. porcelain.commit(
  3844. repo=clone_path,
  3845. message=b"push",
  3846. author=b"author <email>",
  3847. committer=b"committer <email>",
  3848. )
  3849. # Setup a non-checked out branch in the remote
  3850. refs_path = b"refs/heads/foo"
  3851. new_id = self.repo[b"HEAD"].id
  3852. self.assertNotEqual(new_id, ZERO_SHA)
  3853. self.repo.refs[refs_path] = new_id
  3854. # Push to the remote
  3855. porcelain.push(
  3856. clone_path,
  3857. "origin",
  3858. b"HEAD:" + refs_path,
  3859. outstream=outstream,
  3860. errstream=errstream,
  3861. )
  3862. self.assertEqual(
  3863. target_repo.refs[b"refs/remotes/origin/foo"],
  3864. target_repo.refs[b"HEAD"],
  3865. )
  3866. # Check that the target and source
  3867. with Repo(clone_path) as r_clone:
  3868. self.assertEqual(
  3869. {
  3870. b"HEAD": new_id,
  3871. b"refs/heads/foo": r_clone[b"HEAD"].id,
  3872. b"refs/heads/master": new_id,
  3873. },
  3874. self.repo.get_refs(),
  3875. )
  3876. self.assertEqual(r_clone[b"HEAD"].id, self.repo[refs_path].id)
  3877. # Get the change in the target repo corresponding to the add
  3878. # this will be in the foo branch.
  3879. change = next(
  3880. iter(
  3881. tree_changes(
  3882. self.repo.object_store,
  3883. self.repo[b"HEAD"].tree,
  3884. self.repo[b"refs/heads/foo"].tree,
  3885. )
  3886. )
  3887. )
  3888. self.assertEqual(
  3889. os.path.basename(fullpath), change.new.path.decode("ascii")
  3890. )
  3891. def test_local_missing(self) -> None:
  3892. """Pushing a new branch."""
  3893. outstream = BytesIO()
  3894. errstream = BytesIO()
  3895. # Setup target repo cloned from temp test repo
  3896. clone_path = tempfile.mkdtemp()
  3897. self.addCleanup(shutil.rmtree, clone_path)
  3898. target_repo = porcelain.init(clone_path)
  3899. target_repo.close()
  3900. self.assertRaises(
  3901. porcelain.Error,
  3902. porcelain.push,
  3903. self.repo,
  3904. clone_path,
  3905. b"HEAD:refs/heads/master",
  3906. outstream=outstream,
  3907. errstream=errstream,
  3908. )
  3909. def test_new(self) -> None:
  3910. """Pushing a new branch."""
  3911. outstream = BytesIO()
  3912. errstream = BytesIO()
  3913. # Setup target repo cloned from temp test repo
  3914. clone_path = tempfile.mkdtemp()
  3915. self.addCleanup(shutil.rmtree, clone_path)
  3916. target_repo = porcelain.init(clone_path)
  3917. target_repo.close()
  3918. # create a second file to be pushed back to origin
  3919. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3920. os.close(handle)
  3921. porcelain.add(repo=clone_path, paths=[fullpath])
  3922. new_id = porcelain.commit(
  3923. repo=self.repo,
  3924. message=b"push",
  3925. author=b"author <email>",
  3926. committer=b"committer <email>",
  3927. )
  3928. # Push to the remote
  3929. porcelain.push(
  3930. self.repo,
  3931. clone_path,
  3932. b"HEAD:refs/heads/master",
  3933. outstream=outstream,
  3934. errstream=errstream,
  3935. )
  3936. with Repo(clone_path) as r_clone:
  3937. self.assertEqual(
  3938. {
  3939. b"HEAD": new_id,
  3940. b"refs/heads/master": new_id,
  3941. },
  3942. r_clone.get_refs(),
  3943. )
  3944. def test_delete(self) -> None:
  3945. """Basic test of porcelain push, removing a branch."""
  3946. outstream = BytesIO()
  3947. errstream = BytesIO()
  3948. porcelain.commit(
  3949. repo=self.repo.path,
  3950. message=b"init",
  3951. author=b"author <email>",
  3952. committer=b"committer <email>",
  3953. )
  3954. # Setup target repo cloned from temp test repo
  3955. clone_path = tempfile.mkdtemp()
  3956. self.addCleanup(shutil.rmtree, clone_path)
  3957. target_repo = porcelain.clone(
  3958. self.repo.path, target=clone_path, errstream=errstream
  3959. )
  3960. target_repo.close()
  3961. # Setup a non-checked out branch in the remote
  3962. refs_path = b"refs/heads/foo"
  3963. new_id = self.repo[b"HEAD"].id
  3964. self.assertNotEqual(new_id, ZERO_SHA)
  3965. self.repo.refs[refs_path] = new_id
  3966. # Push to the remote
  3967. porcelain.push(
  3968. clone_path,
  3969. self.repo.path,
  3970. b":" + refs_path,
  3971. outstream=outstream,
  3972. errstream=errstream,
  3973. )
  3974. self.assertEqual(
  3975. {
  3976. b"HEAD": new_id,
  3977. b"refs/heads/master": new_id,
  3978. },
  3979. self.repo.get_refs(),
  3980. )
  3981. def test_diverged(self) -> None:
  3982. outstream = BytesIO()
  3983. errstream = BytesIO()
  3984. porcelain.commit(
  3985. repo=self.repo.path,
  3986. message=b"init",
  3987. author=b"author <email>",
  3988. committer=b"committer <email>",
  3989. )
  3990. # Setup target repo cloned from temp test repo
  3991. clone_path = tempfile.mkdtemp()
  3992. self.addCleanup(shutil.rmtree, clone_path)
  3993. target_repo = porcelain.clone(
  3994. self.repo.path, target=clone_path, errstream=errstream
  3995. )
  3996. target_repo.close()
  3997. remote_id = porcelain.commit(
  3998. repo=self.repo.path,
  3999. message=b"remote change",
  4000. author=b"author <email>",
  4001. committer=b"committer <email>",
  4002. )
  4003. local_id = porcelain.commit(
  4004. repo=clone_path,
  4005. message=b"local change",
  4006. author=b"author <email>",
  4007. committer=b"committer <email>",
  4008. )
  4009. outstream = BytesIO()
  4010. errstream = BytesIO()
  4011. # Push to the remote
  4012. self.assertRaises(
  4013. porcelain.DivergedBranches,
  4014. porcelain.push,
  4015. clone_path,
  4016. self.repo.path,
  4017. b"refs/heads/master",
  4018. outstream=outstream,
  4019. errstream=errstream,
  4020. )
  4021. self.assertEqual(
  4022. {
  4023. b"HEAD": remote_id,
  4024. b"refs/heads/master": remote_id,
  4025. },
  4026. self.repo.get_refs(),
  4027. )
  4028. self.assertEqual(b"", outstream.getvalue())
  4029. self.assertEqual(b"", errstream.getvalue())
  4030. outstream = BytesIO()
  4031. errstream = BytesIO()
  4032. # Push to the remote with --force
  4033. porcelain.push(
  4034. clone_path,
  4035. self.repo.path,
  4036. b"refs/heads/master",
  4037. outstream=outstream,
  4038. errstream=errstream,
  4039. force=True,
  4040. )
  4041. self.assertEqual(
  4042. {
  4043. b"HEAD": local_id,
  4044. b"refs/heads/master": local_id,
  4045. },
  4046. self.repo.get_refs(),
  4047. )
  4048. self.assertEqual(b"", outstream.getvalue())
  4049. self.assertTrue(re.match(b"Push to .* successful.\n", errstream.getvalue()))
  4050. def test_push_returns_sendpackresult(self) -> None:
  4051. """Test that push returns a SendPackResult with per-ref information."""
  4052. outstream = BytesIO()
  4053. errstream = BytesIO()
  4054. # Create initial commit
  4055. porcelain.commit(
  4056. repo=self.repo.path,
  4057. message=b"init",
  4058. author=b"author <email>",
  4059. committer=b"committer <email>",
  4060. )
  4061. # Setup target repo cloned from temp test repo
  4062. clone_path = tempfile.mkdtemp()
  4063. self.addCleanup(shutil.rmtree, clone_path)
  4064. target_repo = porcelain.clone(
  4065. self.repo.path, target=clone_path, errstream=errstream
  4066. )
  4067. target_repo.close()
  4068. # Create a commit in the clone
  4069. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4070. os.close(handle)
  4071. porcelain.add(repo=clone_path, paths=[fullpath])
  4072. porcelain.commit(
  4073. repo=clone_path,
  4074. message=b"push",
  4075. author=b"author <email>",
  4076. committer=b"committer <email>",
  4077. )
  4078. # Push and check the return value
  4079. result = porcelain.push(
  4080. clone_path,
  4081. "origin",
  4082. b"HEAD:refs/heads/new-branch",
  4083. outstream=outstream,
  4084. errstream=errstream,
  4085. )
  4086. # Verify that we get a SendPackResult
  4087. self.assertIsInstance(result, SendPackResult)
  4088. # Verify that it contains refs
  4089. self.assertIsNotNone(result.refs)
  4090. self.assertIn(b"refs/heads/new-branch", result.refs)
  4091. # Verify ref_status - should be None for successful updates
  4092. if result.ref_status:
  4093. self.assertIsNone(result.ref_status.get(b"refs/heads/new-branch"))
  4094. def test_mirror_mode(self) -> None:
  4095. """Test push with remote.<name>.mirror configuration."""
  4096. outstream = BytesIO()
  4097. errstream = BytesIO()
  4098. # Create initial commit
  4099. porcelain.commit(
  4100. repo=self.repo.path,
  4101. message=b"init",
  4102. author=b"author <email>",
  4103. committer=b"committer <email>",
  4104. )
  4105. # Setup target repo cloned from temp test repo
  4106. clone_path = tempfile.mkdtemp()
  4107. self.addCleanup(shutil.rmtree, clone_path)
  4108. target_repo = porcelain.clone(
  4109. self.repo.path, target=clone_path, errstream=errstream
  4110. )
  4111. target_repo.close()
  4112. # Create multiple refs in the clone
  4113. with Repo(clone_path) as r_clone:
  4114. # Create a new branch
  4115. r_clone.refs[b"refs/heads/feature"] = r_clone[b"HEAD"].id
  4116. # Create a tag
  4117. r_clone.refs[b"refs/tags/v1.0"] = r_clone[b"HEAD"].id
  4118. # Create a remote tracking branch
  4119. r_clone.refs[b"refs/remotes/upstream/main"] = r_clone[b"HEAD"].id
  4120. # Create a branch in the remote that doesn't exist in clone
  4121. self.repo.refs[b"refs/heads/to-be-deleted"] = self.repo[b"HEAD"].id
  4122. # Configure mirror mode
  4123. with Repo(clone_path) as r_clone:
  4124. config = r_clone.get_config()
  4125. config.set((b"remote", b"origin"), b"mirror", True)
  4126. config.write_to_path()
  4127. # Push with mirror mode
  4128. porcelain.push(
  4129. clone_path,
  4130. "origin",
  4131. outstream=outstream,
  4132. errstream=errstream,
  4133. )
  4134. # Verify refs were properly mirrored
  4135. with Repo(clone_path) as r_clone:
  4136. # All local branches should be pushed
  4137. self.assertEqual(
  4138. r_clone.refs[b"refs/heads/feature"],
  4139. self.repo.refs[b"refs/heads/feature"],
  4140. )
  4141. # All tags should be pushed
  4142. self.assertEqual(
  4143. r_clone.refs[b"refs/tags/v1.0"], self.repo.refs[b"refs/tags/v1.0"]
  4144. )
  4145. # Remote tracking branches should be pushed
  4146. self.assertEqual(
  4147. r_clone.refs[b"refs/remotes/upstream/main"],
  4148. self.repo.refs[b"refs/remotes/upstream/main"],
  4149. )
  4150. # Verify the extra branch was deleted
  4151. self.assertNotIn(b"refs/heads/to-be-deleted", self.repo.refs)
  4152. def test_mirror_mode_disabled(self) -> None:
  4153. """Test that mirror mode is properly disabled when set to false."""
  4154. outstream = BytesIO()
  4155. errstream = BytesIO()
  4156. # Create initial commit
  4157. porcelain.commit(
  4158. repo=self.repo.path,
  4159. message=b"init",
  4160. author=b"author <email>",
  4161. committer=b"committer <email>",
  4162. )
  4163. # Setup target repo cloned from temp test repo
  4164. clone_path = tempfile.mkdtemp()
  4165. self.addCleanup(shutil.rmtree, clone_path)
  4166. target_repo = porcelain.clone(
  4167. self.repo.path, target=clone_path, errstream=errstream
  4168. )
  4169. target_repo.close()
  4170. # Create a branch in the remote that doesn't exist in clone
  4171. self.repo.refs[b"refs/heads/should-not-be-deleted"] = self.repo[b"HEAD"].id
  4172. # Explicitly set mirror mode to false
  4173. with Repo(clone_path) as r_clone:
  4174. config = r_clone.get_config()
  4175. config.set((b"remote", b"origin"), b"mirror", False)
  4176. config.write_to_path()
  4177. # Push normally (not mirror mode)
  4178. porcelain.push(
  4179. clone_path,
  4180. "origin",
  4181. outstream=outstream,
  4182. errstream=errstream,
  4183. )
  4184. # Verify the extra branch was NOT deleted
  4185. self.assertIn(b"refs/heads/should-not-be-deleted", self.repo.refs)
  4186. class PullTests(PorcelainTestCase):
  4187. def setUp(self) -> None:
  4188. super().setUp()
  4189. # create a file for initial commit
  4190. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4191. os.close(handle)
  4192. porcelain.add(repo=self.repo.path, paths=fullpath)
  4193. porcelain.commit(
  4194. repo=self.repo.path,
  4195. message=b"test",
  4196. author=b"test <email>",
  4197. committer=b"test <email>",
  4198. )
  4199. # Setup target repo
  4200. self.target_path = tempfile.mkdtemp()
  4201. self.addCleanup(shutil.rmtree, self.target_path)
  4202. target_repo = porcelain.clone(
  4203. self.repo.path, target=self.target_path, errstream=BytesIO()
  4204. )
  4205. target_repo.close()
  4206. # create a second file to be pushed
  4207. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4208. os.close(handle)
  4209. porcelain.add(repo=self.repo.path, paths=fullpath)
  4210. porcelain.commit(
  4211. repo=self.repo.path,
  4212. message=b"test2",
  4213. author=b"test2 <email>",
  4214. committer=b"test2 <email>",
  4215. )
  4216. self.assertIn(b"refs/heads/master", self.repo.refs)
  4217. self.assertIn(b"refs/heads/master", target_repo.refs)
  4218. def test_simple(self) -> None:
  4219. outstream = BytesIO()
  4220. errstream = BytesIO()
  4221. # Pull changes into the cloned repo
  4222. porcelain.pull(
  4223. self.target_path,
  4224. self.repo.path,
  4225. b"refs/heads/master",
  4226. outstream=outstream,
  4227. errstream=errstream,
  4228. )
  4229. # Check the target repo for pushed changes
  4230. with Repo(self.target_path) as r:
  4231. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4232. def test_diverged(self) -> None:
  4233. outstream = BytesIO()
  4234. errstream = BytesIO()
  4235. c3a = porcelain.commit(
  4236. repo=self.target_path,
  4237. message=b"test3a",
  4238. author=b"test2 <email>",
  4239. committer=b"test2 <email>",
  4240. )
  4241. porcelain.commit(
  4242. repo=self.repo.path,
  4243. message=b"test3b",
  4244. author=b"test2 <email>",
  4245. committer=b"test2 <email>",
  4246. )
  4247. # Pull changes into the cloned repo
  4248. self.assertRaises(
  4249. porcelain.DivergedBranches,
  4250. porcelain.pull,
  4251. self.target_path,
  4252. self.repo.path,
  4253. b"refs/heads/master",
  4254. outstream=outstream,
  4255. errstream=errstream,
  4256. )
  4257. # Check the target repo for pushed changes
  4258. with Repo(self.target_path) as r:
  4259. self.assertEqual(r[b"refs/heads/master"].id, c3a)
  4260. # Pull with merge should now work
  4261. porcelain.pull(
  4262. self.target_path,
  4263. self.repo.path,
  4264. b"refs/heads/master",
  4265. outstream=outstream,
  4266. errstream=errstream,
  4267. fast_forward=False,
  4268. )
  4269. # Check the target repo for merged changes
  4270. with Repo(self.target_path) as r:
  4271. # HEAD should now be a merge commit
  4272. head = r[b"HEAD"]
  4273. # It should have two parents
  4274. self.assertEqual(len(head.parents), 2)
  4275. # One parent should be the previous HEAD (c3a)
  4276. self.assertIn(c3a, head.parents)
  4277. # The other parent should be from the source repo
  4278. self.assertIn(self.repo[b"HEAD"].id, head.parents)
  4279. def test_no_refspec(self) -> None:
  4280. outstream = BytesIO()
  4281. errstream = BytesIO()
  4282. # Pull changes into the cloned repo
  4283. porcelain.pull(
  4284. self.target_path,
  4285. self.repo.path,
  4286. outstream=outstream,
  4287. errstream=errstream,
  4288. )
  4289. # Check the target repo for pushed changes
  4290. with Repo(self.target_path) as r:
  4291. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4292. def test_no_remote_location(self) -> None:
  4293. outstream = BytesIO()
  4294. errstream = BytesIO()
  4295. # Pull changes into the cloned repo
  4296. porcelain.pull(
  4297. self.target_path,
  4298. refspecs=b"refs/heads/master",
  4299. outstream=outstream,
  4300. errstream=errstream,
  4301. )
  4302. # Check the target repo for pushed changes
  4303. with Repo(self.target_path) as r:
  4304. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4305. def test_pull_updates_working_tree(self) -> None:
  4306. """Test that pull updates the working tree with new files."""
  4307. outstream = BytesIO()
  4308. errstream = BytesIO()
  4309. # Create a new file with content in the source repo
  4310. new_file = os.path.join(self.repo.path, "newfile.txt")
  4311. with open(new_file, "w") as f:
  4312. f.write("This is new content")
  4313. porcelain.add(repo=self.repo.path, paths=[new_file])
  4314. porcelain.commit(
  4315. repo=self.repo.path,
  4316. message=b"Add new file",
  4317. author=b"test <email>",
  4318. committer=b"test <email>",
  4319. )
  4320. # Before pull, the file should not exist in target
  4321. target_file = os.path.join(self.target_path, "newfile.txt")
  4322. self.assertFalse(os.path.exists(target_file))
  4323. # Pull changes into the cloned repo
  4324. porcelain.pull(
  4325. self.target_path,
  4326. self.repo.path,
  4327. b"refs/heads/master",
  4328. outstream=outstream,
  4329. errstream=errstream,
  4330. )
  4331. # After pull, the file should exist with correct content
  4332. self.assertTrue(os.path.exists(target_file))
  4333. with open(target_file) as f:
  4334. self.assertEqual(f.read(), "This is new content")
  4335. # Check the HEAD is updated too
  4336. with Repo(self.target_path) as r:
  4337. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4338. class StatusTests(PorcelainTestCase):
  4339. def test_empty(self) -> None:
  4340. results = porcelain.status(self.repo)
  4341. self.assertEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4342. self.assertEqual([], results.unstaged)
  4343. def test_status_base(self) -> None:
  4344. """Integration test for `status` functionality."""
  4345. # Commit a dummy file then modify it
  4346. fullpath = os.path.join(self.repo.path, "foo")
  4347. with open(fullpath, "w") as f:
  4348. f.write("origstuff")
  4349. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4350. porcelain.commit(
  4351. repo=self.repo.path,
  4352. message=b"test status",
  4353. author=b"author <email>",
  4354. committer=b"committer <email>",
  4355. )
  4356. # modify access and modify time of path
  4357. os.utime(fullpath, (0, 0))
  4358. with open(fullpath, "wb") as f:
  4359. f.write(b"stuff")
  4360. # Make a dummy file and stage it
  4361. filename_add = "bar"
  4362. fullpath = os.path.join(self.repo.path, filename_add)
  4363. with open(fullpath, "w") as f:
  4364. f.write("stuff")
  4365. porcelain.add(repo=self.repo.path, paths=fullpath)
  4366. results = porcelain.status(self.repo)
  4367. self.assertEqual(results.staged["add"][0], filename_add.encode("ascii"))
  4368. self.assertEqual(results.unstaged, [b"foo"])
  4369. def test_status_all(self) -> None:
  4370. del_path = os.path.join(self.repo.path, "foo")
  4371. mod_path = os.path.join(self.repo.path, "bar")
  4372. add_path = os.path.join(self.repo.path, "baz")
  4373. us_path = os.path.join(self.repo.path, "blye")
  4374. ut_path = os.path.join(self.repo.path, "blyat")
  4375. with open(del_path, "w") as f:
  4376. f.write("origstuff")
  4377. with open(mod_path, "w") as f:
  4378. f.write("origstuff")
  4379. with open(us_path, "w") as f:
  4380. f.write("origstuff")
  4381. porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path])
  4382. porcelain.commit(
  4383. repo=self.repo.path,
  4384. message=b"test status",
  4385. author=b"author <email>",
  4386. committer=b"committer <email>",
  4387. )
  4388. porcelain.remove(self.repo.path, [del_path])
  4389. with open(add_path, "w") as f:
  4390. f.write("origstuff")
  4391. with open(mod_path, "w") as f:
  4392. f.write("more_origstuff")
  4393. with open(us_path, "w") as f:
  4394. f.write("more_origstuff")
  4395. porcelain.add(repo=self.repo.path, paths=[add_path, mod_path])
  4396. with open(us_path, "w") as f:
  4397. f.write("\norigstuff")
  4398. with open(ut_path, "w") as f:
  4399. f.write("origstuff")
  4400. results = porcelain.status(self.repo.path)
  4401. self.assertDictEqual(
  4402. {"add": [b"baz"], "delete": [b"foo"], "modify": [b"bar"]},
  4403. results.staged,
  4404. )
  4405. self.assertListEqual(results.unstaged, [b"blye"])
  4406. results_no_untracked = porcelain.status(self.repo.path, untracked_files="no")
  4407. self.assertListEqual(results_no_untracked.untracked, [])
  4408. def test_status_wrong_untracked_files_value(self) -> None:
  4409. with self.assertRaises(ValueError):
  4410. porcelain.status(self.repo.path, untracked_files="antani")
  4411. def test_status_untracked_path(self) -> None:
  4412. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  4413. os.mkdir(untracked_dir)
  4414. untracked_file = os.path.join(untracked_dir, "untracked_file")
  4415. with open(untracked_file, "w") as fh:
  4416. fh.write("untracked")
  4417. _, _, untracked = porcelain.status(self.repo.path, untracked_files="all")
  4418. self.assertEqual(untracked, ["untracked_dir/untracked_file"])
  4419. def test_status_untracked_path_normal(self) -> None:
  4420. # Create an untracked directory with multiple files
  4421. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  4422. os.mkdir(untracked_dir)
  4423. untracked_file1 = os.path.join(untracked_dir, "file1")
  4424. untracked_file2 = os.path.join(untracked_dir, "file2")
  4425. with open(untracked_file1, "w") as fh:
  4426. fh.write("untracked1")
  4427. with open(untracked_file2, "w") as fh:
  4428. fh.write("untracked2")
  4429. # Create a nested untracked directory
  4430. nested_dir = os.path.join(untracked_dir, "nested")
  4431. os.mkdir(nested_dir)
  4432. nested_file = os.path.join(nested_dir, "file3")
  4433. with open(nested_file, "w") as fh:
  4434. fh.write("untracked3")
  4435. # Test "normal" mode - should only show the directory, not individual files
  4436. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  4437. self.assertEqual(untracked, ["untracked_dir/"])
  4438. # Test "all" mode - should show all files
  4439. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  4440. self.assertEqual(
  4441. sorted(untracked_all),
  4442. [
  4443. "untracked_dir/file1",
  4444. "untracked_dir/file2",
  4445. "untracked_dir/nested/file3",
  4446. ],
  4447. )
  4448. def test_status_mixed_tracked_untracked(self) -> None:
  4449. # Create a directory with both tracked and untracked files
  4450. mixed_dir = os.path.join(self.repo_path, "mixed_dir")
  4451. os.mkdir(mixed_dir)
  4452. # Add a tracked file
  4453. tracked_file = os.path.join(mixed_dir, "tracked.txt")
  4454. with open(tracked_file, "w") as fh:
  4455. fh.write("tracked content")
  4456. porcelain.add(self.repo.path, paths=[tracked_file])
  4457. porcelain.commit(
  4458. repo=self.repo.path,
  4459. message=b"add tracked file",
  4460. author=b"author <email>",
  4461. committer=b"committer <email>",
  4462. )
  4463. # Add untracked files to the same directory
  4464. untracked_file = os.path.join(mixed_dir, "untracked.txt")
  4465. with open(untracked_file, "w") as fh:
  4466. fh.write("untracked content")
  4467. # In "normal" mode, should show individual untracked files in mixed dirs
  4468. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  4469. self.assertEqual(untracked, ["mixed_dir/untracked.txt"])
  4470. # In "all" mode, should be the same for mixed directories
  4471. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  4472. self.assertEqual(untracked_all, ["mixed_dir/untracked.txt"])
  4473. def test_status_crlf_mismatch(self) -> None:
  4474. # First make a commit as if the file has been added on a Linux system
  4475. # or with core.autocrlf=True
  4476. file_path = os.path.join(self.repo.path, "crlf")
  4477. with open(file_path, "wb") as f:
  4478. f.write(b"line1\nline2")
  4479. porcelain.add(repo=self.repo.path, paths=[file_path])
  4480. porcelain.commit(
  4481. repo=self.repo.path,
  4482. message=b"test status",
  4483. author=b"author <email>",
  4484. committer=b"committer <email>",
  4485. )
  4486. # Then update the file as if it was created by CGit on a Windows
  4487. # system with core.autocrlf=true
  4488. with open(file_path, "wb") as f:
  4489. f.write(b"line1\r\nline2")
  4490. results = porcelain.status(self.repo)
  4491. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4492. self.assertListEqual(results.unstaged, [b"crlf"])
  4493. self.assertListEqual(results.untracked, [])
  4494. def test_status_autocrlf_true(self) -> None:
  4495. # First make a commit as if the file has been added on a Linux system
  4496. # or with core.autocrlf=True
  4497. file_path = os.path.join(self.repo.path, "crlf")
  4498. with open(file_path, "wb") as f:
  4499. f.write(b"line1\nline2")
  4500. porcelain.add(repo=self.repo.path, paths=[file_path])
  4501. porcelain.commit(
  4502. repo=self.repo.path,
  4503. message=b"test status",
  4504. author=b"author <email>",
  4505. committer=b"committer <email>",
  4506. )
  4507. # Then update the file as if it was created by CGit on a Windows
  4508. # system with core.autocrlf=true
  4509. with open(file_path, "wb") as f:
  4510. f.write(b"line1\r\nline2")
  4511. # TODO: It should be set automatically by looking at the configuration
  4512. c = self.repo.get_config()
  4513. c.set("core", "autocrlf", True)
  4514. c.write_to_path()
  4515. results = porcelain.status(self.repo)
  4516. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4517. self.assertListEqual(results.unstaged, [])
  4518. self.assertListEqual(results.untracked, [])
  4519. def test_status_autocrlf_input(self) -> None:
  4520. # Commit existing file with CRLF
  4521. file_path = os.path.join(self.repo.path, "crlf-exists")
  4522. with open(file_path, "wb") as f:
  4523. f.write(b"line1\r\nline2")
  4524. porcelain.add(repo=self.repo.path, paths=[file_path])
  4525. porcelain.commit(
  4526. repo=self.repo.path,
  4527. message=b"test status",
  4528. author=b"author <email>",
  4529. committer=b"committer <email>",
  4530. )
  4531. c = self.repo.get_config()
  4532. c.set("core", "autocrlf", "input")
  4533. c.write_to_path()
  4534. # Add new (untracked) file
  4535. file_path = os.path.join(self.repo.path, "crlf-new")
  4536. with open(file_path, "wb") as f:
  4537. f.write(b"line1\r\nline2")
  4538. porcelain.add(repo=self.repo.path, paths=[file_path])
  4539. results = porcelain.status(self.repo)
  4540. self.assertDictEqual(
  4541. {"add": [b"crlf-new"], "delete": [], "modify": []}, results.staged
  4542. )
  4543. self.assertListEqual(results.unstaged, [b"crlf-exists"])
  4544. self.assertListEqual(results.untracked, [])
  4545. def test_get_tree_changes_add(self) -> None:
  4546. """Unit test for get_tree_changes add."""
  4547. # Make a dummy file, stage
  4548. filename = "bar"
  4549. fullpath = os.path.join(self.repo.path, filename)
  4550. with open(fullpath, "w") as f:
  4551. f.write("stuff")
  4552. porcelain.add(repo=self.repo.path, paths=fullpath)
  4553. porcelain.commit(
  4554. repo=self.repo.path,
  4555. message=b"test status",
  4556. author=b"author <email>",
  4557. committer=b"committer <email>",
  4558. )
  4559. filename = "foo"
  4560. fullpath = os.path.join(self.repo.path, filename)
  4561. with open(fullpath, "w") as f:
  4562. f.write("stuff")
  4563. porcelain.add(repo=self.repo.path, paths=fullpath)
  4564. changes = porcelain.get_tree_changes(self.repo.path)
  4565. self.assertEqual(changes["add"][0], filename.encode("ascii"))
  4566. self.assertEqual(len(changes["add"]), 1)
  4567. self.assertEqual(len(changes["modify"]), 0)
  4568. self.assertEqual(len(changes["delete"]), 0)
  4569. def test_get_tree_changes_modify(self) -> None:
  4570. """Unit test for get_tree_changes modify."""
  4571. # Make a dummy file, stage, commit, modify
  4572. filename = "foo"
  4573. fullpath = os.path.join(self.repo.path, filename)
  4574. with open(fullpath, "w") as f:
  4575. f.write("stuff")
  4576. porcelain.add(repo=self.repo.path, paths=fullpath)
  4577. porcelain.commit(
  4578. repo=self.repo.path,
  4579. message=b"test status",
  4580. author=b"author <email>",
  4581. committer=b"committer <email>",
  4582. )
  4583. with open(fullpath, "w") as f:
  4584. f.write("otherstuff")
  4585. porcelain.add(repo=self.repo.path, paths=fullpath)
  4586. changes = porcelain.get_tree_changes(self.repo.path)
  4587. self.assertEqual(changes["modify"][0], filename.encode("ascii"))
  4588. self.assertEqual(len(changes["add"]), 0)
  4589. self.assertEqual(len(changes["modify"]), 1)
  4590. self.assertEqual(len(changes["delete"]), 0)
  4591. def test_get_tree_changes_delete(self) -> None:
  4592. """Unit test for get_tree_changes delete."""
  4593. # Make a dummy file, stage, commit, remove
  4594. filename = "foo"
  4595. fullpath = os.path.join(self.repo.path, filename)
  4596. with open(fullpath, "w") as f:
  4597. f.write("stuff")
  4598. porcelain.add(repo=self.repo.path, paths=fullpath)
  4599. porcelain.commit(
  4600. repo=self.repo.path,
  4601. message=b"test status",
  4602. author=b"author <email>",
  4603. committer=b"committer <email>",
  4604. )
  4605. cwd = os.getcwd()
  4606. self.addCleanup(os.chdir, cwd)
  4607. os.chdir(self.repo.path)
  4608. porcelain.remove(repo=self.repo.path, paths=[filename])
  4609. changes = porcelain.get_tree_changes(self.repo.path)
  4610. self.assertEqual(changes["delete"][0], filename.encode("ascii"))
  4611. self.assertEqual(len(changes["add"]), 0)
  4612. self.assertEqual(len(changes["modify"]), 0)
  4613. self.assertEqual(len(changes["delete"]), 1)
  4614. def test_get_untracked_paths(self) -> None:
  4615. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  4616. f.write("ignored\n")
  4617. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  4618. f.write("blah\n")
  4619. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  4620. f.write("blah\n")
  4621. os.symlink(
  4622. os.path.join(self.repo.path, os.pardir, "external_target"),
  4623. os.path.join(self.repo.path, "link"),
  4624. )
  4625. self.assertEqual(
  4626. {"ignored", "notignored", ".gitignore", "link"},
  4627. set(
  4628. porcelain.get_untracked_paths(
  4629. self.repo.path, self.repo.path, self.repo.open_index()
  4630. )
  4631. ),
  4632. )
  4633. self.assertEqual(
  4634. {".gitignore", "notignored", "link"},
  4635. set(porcelain.status(self.repo).untracked),
  4636. )
  4637. self.assertEqual(
  4638. {".gitignore", "notignored", "ignored", "link"},
  4639. set(porcelain.status(self.repo, ignored=True).untracked),
  4640. )
  4641. def test_get_untracked_paths_subrepo(self) -> None:
  4642. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  4643. f.write("nested/\n")
  4644. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  4645. f.write("blah\n")
  4646. subrepo = Repo.init(os.path.join(self.repo.path, "nested"), mkdir=True)
  4647. with open(os.path.join(subrepo.path, "ignored"), "w") as f:
  4648. f.write("bleep\n")
  4649. with open(os.path.join(subrepo.path, "with"), "w") as f:
  4650. f.write("bloop\n")
  4651. with open(os.path.join(subrepo.path, "manager"), "w") as f:
  4652. f.write("blop\n")
  4653. self.assertEqual(
  4654. {".gitignore", "notignored", os.path.join("nested", "")},
  4655. set(
  4656. porcelain.get_untracked_paths(
  4657. self.repo.path, self.repo.path, self.repo.open_index()
  4658. )
  4659. ),
  4660. )
  4661. self.assertEqual(
  4662. {".gitignore", "notignored"},
  4663. set(
  4664. porcelain.get_untracked_paths(
  4665. self.repo.path,
  4666. self.repo.path,
  4667. self.repo.open_index(),
  4668. exclude_ignored=True,
  4669. )
  4670. ),
  4671. )
  4672. self.assertEqual(
  4673. {"ignored", "with", "manager"},
  4674. set(
  4675. porcelain.get_untracked_paths(
  4676. subrepo.path, subrepo.path, subrepo.open_index()
  4677. )
  4678. ),
  4679. )
  4680. self.assertEqual(
  4681. set(),
  4682. set(
  4683. porcelain.get_untracked_paths(
  4684. subrepo.path,
  4685. self.repo.path,
  4686. self.repo.open_index(),
  4687. )
  4688. ),
  4689. )
  4690. self.assertEqual(
  4691. {
  4692. os.path.join("nested", "ignored"),
  4693. os.path.join("nested", "with"),
  4694. os.path.join("nested", "manager"),
  4695. },
  4696. set(
  4697. porcelain.get_untracked_paths(
  4698. self.repo.path,
  4699. subrepo.path,
  4700. self.repo.open_index(),
  4701. )
  4702. ),
  4703. )
  4704. def test_get_untracked_paths_subdir(self) -> None:
  4705. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  4706. f.write("subdir/\nignored")
  4707. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  4708. f.write("blah\n")
  4709. os.mkdir(os.path.join(self.repo.path, "subdir"))
  4710. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  4711. f.write("foo")
  4712. with open(os.path.join(self.repo.path, "subdir", "ignored"), "w") as f:
  4713. f.write("foo")
  4714. self.assertEqual(
  4715. {
  4716. ".gitignore",
  4717. "notignored",
  4718. "ignored",
  4719. os.path.join("subdir", ""),
  4720. },
  4721. set(
  4722. porcelain.get_untracked_paths(
  4723. self.repo.path,
  4724. self.repo.path,
  4725. self.repo.open_index(),
  4726. )
  4727. ),
  4728. )
  4729. self.assertEqual(
  4730. {".gitignore", "notignored"},
  4731. set(
  4732. porcelain.get_untracked_paths(
  4733. self.repo.path,
  4734. self.repo.path,
  4735. self.repo.open_index(),
  4736. exclude_ignored=True,
  4737. )
  4738. ),
  4739. )
  4740. def test_get_untracked_paths_invalid_untracked_files(self) -> None:
  4741. with self.assertRaises(ValueError):
  4742. list(
  4743. porcelain.get_untracked_paths(
  4744. self.repo.path,
  4745. self.repo.path,
  4746. self.repo.open_index(),
  4747. untracked_files="invalid_value",
  4748. )
  4749. )
  4750. def test_get_untracked_paths_normal(self) -> None:
  4751. # Create an untracked directory with files
  4752. untracked_dir = os.path.join(self.repo.path, "untracked_dir")
  4753. os.mkdir(untracked_dir)
  4754. with open(os.path.join(untracked_dir, "file1.txt"), "w") as f:
  4755. f.write("untracked content")
  4756. with open(os.path.join(untracked_dir, "file2.txt"), "w") as f:
  4757. f.write("more untracked content")
  4758. # Test that "normal" mode works and returns only the directory
  4759. _, _, untracked = porcelain.status(
  4760. repo=self.repo.path, untracked_files="normal"
  4761. )
  4762. self.assertEqual(untracked, ["untracked_dir/"])
  4763. def test_get_untracked_paths_top_level_issue_1247(self) -> None:
  4764. """Test for issue #1247: ensure top-level untracked files are detected."""
  4765. # Create a single top-level untracked file
  4766. with open(os.path.join(self.repo.path, "sample.txt"), "w") as f:
  4767. f.write("test content")
  4768. # Test get_untracked_paths directly
  4769. untracked = list(
  4770. porcelain.get_untracked_paths(
  4771. self.repo.path, self.repo.path, self.repo.open_index()
  4772. )
  4773. )
  4774. self.assertIn(
  4775. "sample.txt",
  4776. untracked,
  4777. "Top-level file 'sample.txt' should be in untracked list",
  4778. )
  4779. # Test via status
  4780. status = porcelain.status(self.repo)
  4781. self.assertIn(
  4782. "sample.txt",
  4783. status.untracked,
  4784. "Top-level file 'sample.txt' should be in status.untracked",
  4785. )
  4786. # TODO(jelmer): Add test for dulwich.porcelain.daemon
  4787. class UploadPackTests(PorcelainTestCase):
  4788. """Tests for upload_pack."""
  4789. def test_upload_pack(self) -> None:
  4790. outf = BytesIO()
  4791. exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf)
  4792. outlines = outf.getvalue().splitlines()
  4793. self.assertEqual([b"0000"], outlines)
  4794. self.assertEqual(0, exitcode)
  4795. class ReceivePackTests(PorcelainTestCase):
  4796. """Tests for receive_pack."""
  4797. def test_receive_pack(self) -> None:
  4798. filename = "foo"
  4799. fullpath = os.path.join(self.repo.path, filename)
  4800. with open(fullpath, "w") as f:
  4801. f.write("stuff")
  4802. porcelain.add(repo=self.repo.path, paths=fullpath)
  4803. self.repo.do_commit(
  4804. message=b"test status",
  4805. author=b"author <email>",
  4806. committer=b"committer <email>",
  4807. author_timestamp=1402354300,
  4808. commit_timestamp=1402354300,
  4809. author_timezone=0,
  4810. commit_timezone=0,
  4811. )
  4812. outf = BytesIO()
  4813. exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf)
  4814. outlines = outf.getvalue().splitlines()
  4815. self.assertEqual(
  4816. [
  4817. b"0091319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status "
  4818. b"delete-refs quiet ofs-delta side-band-64k "
  4819. b"no-done symref=HEAD:refs/heads/master",
  4820. b"003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master",
  4821. b"0000",
  4822. ],
  4823. outlines,
  4824. )
  4825. self.assertEqual(0, exitcode)
  4826. class BranchListTests(PorcelainTestCase):
  4827. def test_standard(self) -> None:
  4828. self.assertEqual(set(), set(porcelain.branch_list(self.repo)))
  4829. def test_new_branch(self) -> None:
  4830. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4831. self.repo[b"HEAD"] = c1.id
  4832. porcelain.branch_create(self.repo, b"foo")
  4833. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  4834. def test_sort_by_refname(self) -> None:
  4835. """Test branch.sort=refname (default alphabetical)."""
  4836. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4837. self.repo[b"HEAD"] = c1.id
  4838. # Create branches in non-alphabetical order
  4839. porcelain.branch_create(self.repo, b"zebra")
  4840. porcelain.branch_create(self.repo, b"alpha")
  4841. porcelain.branch_create(self.repo, b"beta")
  4842. # Set branch.sort to refname (though it's the default)
  4843. config = self.repo.get_config()
  4844. config.set((b"branch",), b"sort", b"refname")
  4845. config.write_to_path()
  4846. # Should be sorted alphabetically
  4847. branches = porcelain.branch_list(self.repo)
  4848. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  4849. def test_sort_by_refname_reverse(self) -> None:
  4850. """Test branch.sort=-refname (reverse alphabetical)."""
  4851. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4852. self.repo[b"HEAD"] = c1.id
  4853. # Create branches
  4854. porcelain.branch_create(self.repo, b"zebra")
  4855. porcelain.branch_create(self.repo, b"alpha")
  4856. porcelain.branch_create(self.repo, b"beta")
  4857. # Set branch.sort to -refname
  4858. config = self.repo.get_config()
  4859. config.set((b"branch",), b"sort", b"-refname")
  4860. config.write_to_path()
  4861. # Should be sorted reverse alphabetically
  4862. branches = porcelain.branch_list(self.repo)
  4863. self.assertEqual([b"zebra", b"master", b"beta", b"alpha"], branches)
  4864. def test_sort_by_committerdate(self) -> None:
  4865. """Test branch.sort=committerdate."""
  4866. # Use build_commit_graph to create proper commits with specific times
  4867. c1, c2, c3 = build_commit_graph(
  4868. self.repo.object_store,
  4869. [[1], [2], [3]],
  4870. attrs={
  4871. 1: {"commit_time": 1000}, # oldest
  4872. 2: {"commit_time": 2000}, # newest
  4873. 3: {"commit_time": 1500}, # middle
  4874. },
  4875. )
  4876. self.repo[b"HEAD"] = c1.id
  4877. # Create branches pointing to different commits
  4878. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  4879. self.repo.refs[b"refs/heads/oldest"] = c1.id
  4880. self.repo.refs[b"refs/heads/newest"] = c2.id
  4881. self.repo.refs[b"refs/heads/middle"] = c3.id
  4882. # Set branch.sort to committerdate
  4883. config = self.repo.get_config()
  4884. config.set((b"branch",), b"sort", b"committerdate")
  4885. config.write_to_path()
  4886. # Should be sorted by commit time (oldest first)
  4887. branches = porcelain.branch_list(self.repo)
  4888. self.assertEqual([b"master", b"oldest", b"middle", b"newest"], branches)
  4889. def test_sort_by_committerdate_reverse(self) -> None:
  4890. """Test branch.sort=-committerdate."""
  4891. # Use build_commit_graph to create proper commits with specific times
  4892. c1, c2, c3 = build_commit_graph(
  4893. self.repo.object_store,
  4894. [[1], [2], [3]],
  4895. attrs={
  4896. 1: {"commit_time": 1000}, # oldest
  4897. 2: {"commit_time": 2000}, # newest
  4898. 3: {"commit_time": 1500}, # middle
  4899. },
  4900. )
  4901. self.repo[b"HEAD"] = c1.id
  4902. # Create branches pointing to different commits
  4903. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  4904. self.repo.refs[b"refs/heads/oldest"] = c1.id
  4905. self.repo.refs[b"refs/heads/newest"] = c2.id
  4906. self.repo.refs[b"refs/heads/middle"] = c3.id
  4907. # Set branch.sort to -committerdate
  4908. config = self.repo.get_config()
  4909. config.set((b"branch",), b"sort", b"-committerdate")
  4910. config.write_to_path()
  4911. # Should be sorted by commit time (newest first)
  4912. branches = porcelain.branch_list(self.repo)
  4913. self.assertEqual([b"newest", b"middle", b"master", b"oldest"], branches)
  4914. def test_sort_default(self) -> None:
  4915. """Test default sorting (no config)."""
  4916. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4917. self.repo[b"HEAD"] = c1.id
  4918. # Create branches in non-alphabetical order
  4919. porcelain.branch_create(self.repo, b"zebra")
  4920. porcelain.branch_create(self.repo, b"alpha")
  4921. porcelain.branch_create(self.repo, b"beta")
  4922. # No config set - should default to alphabetical
  4923. branches = porcelain.branch_list(self.repo)
  4924. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  4925. class BranchCreateTests(PorcelainTestCase):
  4926. def test_branch_exists(self) -> None:
  4927. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4928. self.repo[b"HEAD"] = c1.id
  4929. porcelain.branch_create(self.repo, b"foo")
  4930. self.assertRaises(porcelain.Error, porcelain.branch_create, self.repo, b"foo")
  4931. porcelain.branch_create(self.repo, b"foo", force=True)
  4932. def test_new_branch(self) -> None:
  4933. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4934. self.repo[b"HEAD"] = c1.id
  4935. porcelain.branch_create(self.repo, b"foo")
  4936. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  4937. def test_auto_setup_merge_true_from_remote_tracking(self) -> None:
  4938. """Test branch.autoSetupMerge=true sets up tracking from remote-tracking branch."""
  4939. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4940. self.repo[b"HEAD"] = c1.id
  4941. # Create a remote-tracking branch
  4942. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  4943. # Set branch.autoSetupMerge to true (default)
  4944. config = self.repo.get_config()
  4945. config.set((b"branch",), b"autoSetupMerge", b"true")
  4946. config.write_to_path()
  4947. # Create branch from remote-tracking branch
  4948. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  4949. # Verify tracking was set up
  4950. config = self.repo.get_config()
  4951. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  4952. self.assertEqual(
  4953. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  4954. )
  4955. def test_auto_setup_merge_false(self) -> None:
  4956. """Test branch.autoSetupMerge=false disables tracking setup."""
  4957. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4958. self.repo[b"HEAD"] = c1.id
  4959. # Create a remote-tracking branch
  4960. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  4961. # Set branch.autoSetupMerge to false
  4962. config = self.repo.get_config()
  4963. config.set((b"branch",), b"autoSetupMerge", b"false")
  4964. config.write_to_path()
  4965. # Create branch from remote-tracking branch
  4966. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  4967. # Verify tracking was NOT set up
  4968. config = self.repo.get_config()
  4969. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"remote")
  4970. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"merge")
  4971. def test_auto_setup_merge_always(self) -> None:
  4972. """Test branch.autoSetupMerge=always sets up tracking even from local branches."""
  4973. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4974. self.repo[b"HEAD"] = c1.id
  4975. self.repo.refs[b"refs/heads/main"] = c1.id
  4976. # Set branch.autoSetupMerge to always
  4977. config = self.repo.get_config()
  4978. config.set((b"branch",), b"autoSetupMerge", b"always")
  4979. config.write_to_path()
  4980. # Create branch from local branch - normally wouldn't set up tracking
  4981. porcelain.branch_create(self.repo, "feature", "main")
  4982. # With always, tracking should NOT be set up from local branches
  4983. # (Git only sets up tracking from remote-tracking branches even with always)
  4984. config = self.repo.get_config()
  4985. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"remote")
  4986. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"merge")
  4987. def test_auto_setup_merge_always_from_remote(self) -> None:
  4988. """Test branch.autoSetupMerge=always still sets up tracking from remote branches."""
  4989. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  4990. self.repo[b"HEAD"] = c1.id
  4991. # Create a remote-tracking branch
  4992. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  4993. # Set branch.autoSetupMerge to always
  4994. config = self.repo.get_config()
  4995. config.set((b"branch",), b"autoSetupMerge", b"always")
  4996. config.write_to_path()
  4997. # Create branch from remote-tracking branch
  4998. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  4999. # Verify tracking was set up
  5000. config = self.repo.get_config()
  5001. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  5002. self.assertEqual(
  5003. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  5004. )
  5005. def test_auto_setup_merge_default(self) -> None:
  5006. """Test default behavior (no config) is same as true."""
  5007. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5008. self.repo[b"HEAD"] = c1.id
  5009. # Create a remote-tracking branch
  5010. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  5011. # Don't set any config - should default to true
  5012. # Create branch from remote-tracking branch
  5013. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  5014. # Verify tracking was set up
  5015. config = self.repo.get_config()
  5016. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  5017. self.assertEqual(
  5018. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  5019. )
  5020. class BranchDeleteTests(PorcelainTestCase):
  5021. def test_simple(self) -> None:
  5022. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5023. self.repo[b"HEAD"] = c1.id
  5024. porcelain.branch_create(self.repo, b"foo")
  5025. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  5026. porcelain.branch_delete(self.repo, b"foo")
  5027. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  5028. def test_simple_unicode(self) -> None:
  5029. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5030. self.repo[b"HEAD"] = c1.id
  5031. porcelain.branch_create(self.repo, "foo")
  5032. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  5033. porcelain.branch_delete(self.repo, "foo")
  5034. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  5035. class FetchTests(PorcelainTestCase):
  5036. def test_simple(self) -> None:
  5037. outstream = BytesIO()
  5038. errstream = BytesIO()
  5039. # create a file for initial commit
  5040. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5041. os.close(handle)
  5042. porcelain.add(repo=self.repo.path, paths=fullpath)
  5043. porcelain.commit(
  5044. repo=self.repo.path,
  5045. message=b"test",
  5046. author=b"test <email>",
  5047. committer=b"test <email>",
  5048. )
  5049. # Setup target repo
  5050. target_path = tempfile.mkdtemp()
  5051. self.addCleanup(shutil.rmtree, target_path)
  5052. target_repo = porcelain.clone(
  5053. self.repo.path, target=target_path, errstream=errstream
  5054. )
  5055. # create a second file to be pushed
  5056. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5057. os.close(handle)
  5058. porcelain.add(repo=self.repo.path, paths=fullpath)
  5059. porcelain.commit(
  5060. repo=self.repo.path,
  5061. message=b"test2",
  5062. author=b"test2 <email>",
  5063. committer=b"test2 <email>",
  5064. )
  5065. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  5066. target_repo.close()
  5067. # Fetch changes into the cloned repo
  5068. porcelain.fetch(target_path, "origin", outstream=outstream, errstream=errstream)
  5069. # Assert that fetch updated the local image of the remote
  5070. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  5071. # Check the target repo for pushed changes
  5072. with Repo(target_path) as r:
  5073. self.assertIn(self.repo[b"HEAD"].id, r)
  5074. def test_with_remote_name(self) -> None:
  5075. remote_name = "origin"
  5076. outstream = BytesIO()
  5077. errstream = BytesIO()
  5078. # create a file for initial commit
  5079. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5080. os.close(handle)
  5081. porcelain.add(repo=self.repo.path, paths=fullpath)
  5082. porcelain.commit(
  5083. repo=self.repo.path,
  5084. message=b"test",
  5085. author=b"test <email>",
  5086. committer=b"test <email>",
  5087. )
  5088. # Setup target repo
  5089. target_path = tempfile.mkdtemp()
  5090. self.addCleanup(shutil.rmtree, target_path)
  5091. target_repo = porcelain.clone(
  5092. self.repo.path, target=target_path, errstream=errstream
  5093. )
  5094. # Capture current refs
  5095. target_refs = target_repo.get_refs()
  5096. # create a second file to be pushed
  5097. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5098. os.close(handle)
  5099. porcelain.add(repo=self.repo.path, paths=fullpath)
  5100. porcelain.commit(
  5101. repo=self.repo.path,
  5102. message=b"test2",
  5103. author=b"test2 <email>",
  5104. committer=b"test2 <email>",
  5105. )
  5106. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  5107. target_config = target_repo.get_config()
  5108. target_config.set(
  5109. (b"remote", remote_name.encode()), b"url", self.repo.path.encode()
  5110. )
  5111. target_repo.close()
  5112. # Fetch changes into the cloned repo
  5113. porcelain.fetch(
  5114. target_path, remote_name, outstream=outstream, errstream=errstream
  5115. )
  5116. # Assert that fetch updated the local image of the remote
  5117. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  5118. # Check the target repo for pushed changes, as well as updates
  5119. # for the refs
  5120. with Repo(target_path) as r:
  5121. self.assertIn(self.repo[b"HEAD"].id, r)
  5122. self.assertNotEqual(self.repo.get_refs(), target_refs)
  5123. def assert_correct_remote_refs(
  5124. self, local_refs, remote_refs, remote_name=b"origin"
  5125. ) -> None:
  5126. """Assert that known remote refs corresponds to actual remote refs."""
  5127. local_ref_prefix = b"refs/heads"
  5128. remote_ref_prefix = b"refs/remotes/" + remote_name
  5129. locally_known_remote_refs = {
  5130. k[len(remote_ref_prefix) + 1 :]: v
  5131. for k, v in local_refs.items()
  5132. if k.startswith(remote_ref_prefix)
  5133. }
  5134. normalized_remote_refs = {
  5135. k[len(local_ref_prefix) + 1 :]: v
  5136. for k, v in remote_refs.items()
  5137. if k.startswith(local_ref_prefix)
  5138. }
  5139. if b"HEAD" in locally_known_remote_refs and b"HEAD" in remote_refs:
  5140. normalized_remote_refs[b"HEAD"] = remote_refs[b"HEAD"]
  5141. self.assertEqual(locally_known_remote_refs, normalized_remote_refs)
  5142. class RepackTests(PorcelainTestCase):
  5143. def test_empty(self) -> None:
  5144. porcelain.repack(self.repo)
  5145. def test_simple(self) -> None:
  5146. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5147. os.close(handle)
  5148. porcelain.add(repo=self.repo.path, paths=fullpath)
  5149. porcelain.repack(self.repo)
  5150. class LsTreeTests(PorcelainTestCase):
  5151. def test_empty(self) -> None:
  5152. porcelain.commit(
  5153. repo=self.repo.path,
  5154. message=b"test status",
  5155. author=b"author <email>",
  5156. committer=b"committer <email>",
  5157. )
  5158. f = StringIO()
  5159. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  5160. self.assertEqual(f.getvalue(), "")
  5161. def test_simple(self) -> None:
  5162. # Commit a dummy file then modify it
  5163. fullpath = os.path.join(self.repo.path, "foo")
  5164. with open(fullpath, "w") as f:
  5165. f.write("origstuff")
  5166. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5167. porcelain.commit(
  5168. repo=self.repo.path,
  5169. message=b"test status",
  5170. author=b"author <email>",
  5171. committer=b"committer <email>",
  5172. )
  5173. output = StringIO()
  5174. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  5175. self.assertEqual(
  5176. output.getvalue(),
  5177. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n",
  5178. )
  5179. def test_recursive(self) -> None:
  5180. # Create a directory then write a dummy file in it
  5181. dirpath = os.path.join(self.repo.path, "adir")
  5182. filepath = os.path.join(dirpath, "afile")
  5183. os.mkdir(dirpath)
  5184. with open(filepath, "w") as f:
  5185. f.write("origstuff")
  5186. porcelain.add(repo=self.repo.path, paths=[filepath])
  5187. porcelain.commit(
  5188. repo=self.repo.path,
  5189. message=b"test status",
  5190. author=b"author <email>",
  5191. committer=b"committer <email>",
  5192. )
  5193. output = StringIO()
  5194. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  5195. self.assertEqual(
  5196. output.getvalue(),
  5197. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n",
  5198. )
  5199. output2 = StringIO()
  5200. porcelain.ls_tree(self.repo, b"HEAD", outstream=output2, recursive=True)
  5201. self.assertEqual(
  5202. output2.getvalue(),
  5203. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n"
  5204. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir"
  5205. "/afile\n",
  5206. )
  5207. class LsRemoteTests(PorcelainTestCase):
  5208. def test_empty(self) -> None:
  5209. result = porcelain.ls_remote(self.repo.path)
  5210. self.assertEqual({}, result.refs)
  5211. self.assertEqual({}, result.symrefs)
  5212. def test_some(self) -> None:
  5213. cid = porcelain.commit(
  5214. repo=self.repo.path,
  5215. message=b"test status",
  5216. author=b"author <email>",
  5217. committer=b"committer <email>",
  5218. )
  5219. result = porcelain.ls_remote(self.repo.path)
  5220. self.assertEqual(
  5221. {b"refs/heads/master": cid, b"HEAD": cid},
  5222. result.refs,
  5223. )
  5224. # HEAD should be a symref to refs/heads/master
  5225. self.assertEqual({b"HEAD": b"refs/heads/master"}, result.symrefs)
  5226. class LsFilesTests(PorcelainTestCase):
  5227. def test_empty(self) -> None:
  5228. self.assertEqual([], list(porcelain.ls_files(self.repo)))
  5229. def test_simple(self) -> None:
  5230. # Commit a dummy file then modify it
  5231. fullpath = os.path.join(self.repo.path, "foo")
  5232. with open(fullpath, "w") as f:
  5233. f.write("origstuff")
  5234. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5235. self.assertEqual([b"foo"], list(porcelain.ls_files(self.repo)))
  5236. class RemoteAddTests(PorcelainTestCase):
  5237. def test_new(self) -> None:
  5238. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  5239. c = self.repo.get_config()
  5240. self.assertEqual(
  5241. c.get((b"remote", b"jelmer"), b"url"),
  5242. b"git://jelmer.uk/code/dulwich",
  5243. )
  5244. def test_exists(self) -> None:
  5245. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  5246. self.assertRaises(
  5247. porcelain.RemoteExists,
  5248. porcelain.remote_add,
  5249. self.repo,
  5250. "jelmer",
  5251. "git://jelmer.uk/code/dulwich",
  5252. )
  5253. class RemoteRemoveTests(PorcelainTestCase):
  5254. def test_remove(self) -> None:
  5255. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  5256. c = self.repo.get_config()
  5257. self.assertEqual(
  5258. c.get((b"remote", b"jelmer"), b"url"),
  5259. b"git://jelmer.uk/code/dulwich",
  5260. )
  5261. porcelain.remote_remove(self.repo, "jelmer")
  5262. self.assertRaises(KeyError, porcelain.remote_remove, self.repo, "jelmer")
  5263. c = self.repo.get_config()
  5264. self.assertRaises(KeyError, c.get, (b"remote", b"jelmer"), b"url")
  5265. class CheckIgnoreTests(PorcelainTestCase):
  5266. def test_check_ignored(self) -> None:
  5267. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5268. f.write("foo")
  5269. foo_path = os.path.join(self.repo.path, "foo")
  5270. with open(foo_path, "w") as f:
  5271. f.write("BAR")
  5272. bar_path = os.path.join(self.repo.path, "bar")
  5273. with open(bar_path, "w") as f:
  5274. f.write("BAR")
  5275. self.assertEqual(["foo"], list(porcelain.check_ignore(self.repo, [foo_path])))
  5276. self.assertEqual([], list(porcelain.check_ignore(self.repo, [bar_path])))
  5277. def test_check_added_abs(self) -> None:
  5278. path = os.path.join(self.repo.path, "foo")
  5279. with open(path, "w") as f:
  5280. f.write("BAR")
  5281. self.repo.stage(["foo"])
  5282. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5283. f.write("foo\n")
  5284. self.assertEqual([], list(porcelain.check_ignore(self.repo, [path])))
  5285. self.assertEqual(
  5286. ["foo"],
  5287. list(porcelain.check_ignore(self.repo, [path], no_index=True)),
  5288. )
  5289. def test_check_added_rel(self) -> None:
  5290. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  5291. f.write("BAR")
  5292. self.repo.stage(["foo"])
  5293. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5294. f.write("foo\n")
  5295. cwd = os.getcwd()
  5296. self.addCleanup(os.chdir, cwd)
  5297. os.mkdir(os.path.join(self.repo.path, "bar"))
  5298. os.chdir(os.path.join(self.repo.path, "bar"))
  5299. self.assertEqual(list(porcelain.check_ignore(self.repo, ["../foo"])), [])
  5300. self.assertEqual(
  5301. ["../foo"],
  5302. list(porcelain.check_ignore(self.repo, ["../foo"], no_index=True)),
  5303. )
  5304. class UpdateHeadTests(PorcelainTestCase):
  5305. def test_set_to_branch(self) -> None:
  5306. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5307. self.repo.refs[b"refs/heads/blah"] = c1.id
  5308. porcelain.update_head(self.repo, "blah")
  5309. self.assertEqual(c1.id, self.repo.head())
  5310. self.assertEqual(b"ref: refs/heads/blah", self.repo.refs.read_ref(b"HEAD"))
  5311. def test_set_to_branch_detached(self) -> None:
  5312. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5313. self.repo.refs[b"refs/heads/blah"] = c1.id
  5314. porcelain.update_head(self.repo, "blah", detached=True)
  5315. self.assertEqual(c1.id, self.repo.head())
  5316. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  5317. def test_set_to_commit_detached(self) -> None:
  5318. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5319. self.repo.refs[b"refs/heads/blah"] = c1.id
  5320. porcelain.update_head(self.repo, c1.id, detached=True)
  5321. self.assertEqual(c1.id, self.repo.head())
  5322. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  5323. def test_set_new_branch(self) -> None:
  5324. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5325. self.repo.refs[b"refs/heads/blah"] = c1.id
  5326. porcelain.update_head(self.repo, "blah", new_branch="bar")
  5327. self.assertEqual(c1.id, self.repo.head())
  5328. self.assertEqual(b"ref: refs/heads/bar", self.repo.refs.read_ref(b"HEAD"))
  5329. class MailmapTests(PorcelainTestCase):
  5330. def test_no_mailmap(self) -> None:
  5331. self.assertEqual(
  5332. b"Jelmer Vernooij <jelmer@samba.org>",
  5333. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  5334. )
  5335. def test_mailmap_lookup(self) -> None:
  5336. with open(os.path.join(self.repo.path, ".mailmap"), "wb") as f:
  5337. f.write(
  5338. b"""\
  5339. Jelmer Vernooij <jelmer@debian.org>
  5340. """
  5341. )
  5342. self.assertEqual(
  5343. b"Jelmer Vernooij <jelmer@debian.org>",
  5344. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  5345. )
  5346. class FsckTests(PorcelainTestCase):
  5347. def test_none(self) -> None:
  5348. self.assertEqual([], list(porcelain.fsck(self.repo)))
  5349. def test_git_dir(self) -> None:
  5350. obj = Tree()
  5351. a = Blob()
  5352. a.data = b"foo"
  5353. obj.add(b".git", 0o100644, a.id)
  5354. self.repo.object_store.add_objects([(a, None), (obj, None)])
  5355. self.assertEqual(
  5356. [(obj.id, "invalid name .git")],
  5357. [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)],
  5358. )
  5359. class DescribeTests(PorcelainTestCase):
  5360. def test_no_commits(self) -> None:
  5361. self.assertRaises(KeyError, porcelain.describe, self.repo.path)
  5362. def test_single_commit(self) -> None:
  5363. fullpath = os.path.join(self.repo.path, "foo")
  5364. with open(fullpath, "w") as f:
  5365. f.write("BAR")
  5366. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5367. sha = porcelain.commit(
  5368. self.repo.path,
  5369. message=b"Some message",
  5370. author=b"Joe <joe@example.com>",
  5371. committer=b"Bob <bob@example.com>",
  5372. )
  5373. self.assertEqual(
  5374. "g{}".format(sha[:7].decode("ascii")),
  5375. porcelain.describe(self.repo.path),
  5376. )
  5377. def test_tag(self) -> None:
  5378. fullpath = os.path.join(self.repo.path, "foo")
  5379. with open(fullpath, "w") as f:
  5380. f.write("BAR")
  5381. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5382. porcelain.commit(
  5383. self.repo.path,
  5384. message=b"Some message",
  5385. author=b"Joe <joe@example.com>",
  5386. committer=b"Bob <bob@example.com>",
  5387. )
  5388. porcelain.tag_create(
  5389. self.repo.path,
  5390. b"tryme",
  5391. b"foo <foo@bar.com>",
  5392. b"bar",
  5393. annotated=True,
  5394. )
  5395. self.assertEqual("tryme", porcelain.describe(self.repo.path))
  5396. def test_tag_and_commit(self) -> None:
  5397. fullpath = os.path.join(self.repo.path, "foo")
  5398. with open(fullpath, "w") as f:
  5399. f.write("BAR")
  5400. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5401. porcelain.commit(
  5402. self.repo.path,
  5403. message=b"Some message",
  5404. author=b"Joe <joe@example.com>",
  5405. committer=b"Bob <bob@example.com>",
  5406. )
  5407. porcelain.tag_create(
  5408. self.repo.path,
  5409. b"tryme",
  5410. b"foo <foo@bar.com>",
  5411. b"bar",
  5412. annotated=True,
  5413. )
  5414. with open(fullpath, "w") as f:
  5415. f.write("BAR2")
  5416. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5417. sha = porcelain.commit(
  5418. self.repo.path,
  5419. message=b"Some message",
  5420. author=b"Joe <joe@example.com>",
  5421. committer=b"Bob <bob@example.com>",
  5422. )
  5423. self.assertEqual(
  5424. "tryme-1-g{}".format(sha[:7].decode("ascii")),
  5425. porcelain.describe(self.repo.path),
  5426. )
  5427. def test_tag_and_commit_full(self) -> None:
  5428. fullpath = os.path.join(self.repo.path, "foo")
  5429. with open(fullpath, "w") as f:
  5430. f.write("BAR")
  5431. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5432. porcelain.commit(
  5433. self.repo.path,
  5434. message=b"Some message",
  5435. author=b"Joe <joe@example.com>",
  5436. committer=b"Bob <bob@example.com>",
  5437. )
  5438. porcelain.tag_create(
  5439. self.repo.path,
  5440. b"tryme",
  5441. b"foo <foo@bar.com>",
  5442. b"bar",
  5443. annotated=True,
  5444. )
  5445. with open(fullpath, "w") as f:
  5446. f.write("BAR2")
  5447. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5448. sha = porcelain.commit(
  5449. self.repo.path,
  5450. message=b"Some message",
  5451. author=b"Joe <joe@example.com>",
  5452. committer=b"Bob <bob@example.com>",
  5453. )
  5454. self.assertEqual(
  5455. "tryme-1-g{}".format(sha.decode("ascii")),
  5456. porcelain.describe(self.repo.path, abbrev=40),
  5457. )
  5458. def test_untagged_commit_abbreviation(self) -> None:
  5459. _, _, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]])
  5460. self.repo.refs[b"HEAD"] = c3.id
  5461. brief_description, complete_description = (
  5462. porcelain.describe(self.repo),
  5463. porcelain.describe(self.repo, abbrev=40),
  5464. )
  5465. self.assertTrue(complete_description.startswith(brief_description))
  5466. self.assertEqual(
  5467. "g{}".format(c3.id.decode("ascii")),
  5468. complete_description,
  5469. )
  5470. def test_hash_length_dynamic(self) -> None:
  5471. """Test that hash length adjusts based on uniqueness."""
  5472. fullpath = os.path.join(self.repo.path, "foo")
  5473. with open(fullpath, "w") as f:
  5474. f.write("content")
  5475. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5476. sha = porcelain.commit(
  5477. self.repo.path,
  5478. message=b"commit",
  5479. author=b"Joe <joe@example.com>",
  5480. committer=b"Bob <bob@example.com>",
  5481. )
  5482. # When abbrev is None, it should use find_unique_abbrev
  5483. result = porcelain.describe(self.repo.path)
  5484. # Should start with 'g' and have at least 7 characters
  5485. self.assertTrue(result.startswith("g"))
  5486. self.assertGreaterEqual(len(result[1:]), 7)
  5487. # Should be a prefix of the full SHA
  5488. self.assertTrue(sha.decode("ascii").startswith(result[1:]))
  5489. class PathToTreeTests(PorcelainTestCase):
  5490. def setUp(self) -> None:
  5491. super().setUp()
  5492. self.fp = os.path.join(self.test_dir, "bar")
  5493. with open(self.fp, "w") as f:
  5494. f.write("something")
  5495. oldcwd = os.getcwd()
  5496. self.addCleanup(os.chdir, oldcwd)
  5497. os.chdir(self.test_dir)
  5498. def test_path_to_tree_path_base(self) -> None:
  5499. self.assertEqual(b"bar", porcelain.path_to_tree_path(self.test_dir, self.fp))
  5500. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  5501. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "bar"))
  5502. cwd = os.getcwd()
  5503. self.assertEqual(
  5504. b"bar", porcelain.path_to_tree_path(".", os.path.join(cwd, "bar"))
  5505. )
  5506. self.assertEqual(b"bar", porcelain.path_to_tree_path(cwd, "bar"))
  5507. def test_path_to_tree_path_syntax(self) -> None:
  5508. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  5509. def test_path_to_tree_path_error(self) -> None:
  5510. with self.assertRaises(ValueError):
  5511. with tempfile.TemporaryDirectory() as od:
  5512. porcelain.path_to_tree_path(od, self.fp)
  5513. def test_path_to_tree_path_rel(self) -> None:
  5514. cwd = os.getcwd()
  5515. self.addCleanup(os.chdir, cwd)
  5516. os.mkdir(os.path.join(self.repo.path, "foo"))
  5517. os.mkdir(os.path.join(self.repo.path, "foo/bar"))
  5518. os.chdir(os.path.join(self.repo.path, "foo/bar"))
  5519. with open("baz", "w") as f:
  5520. f.write("contents")
  5521. self.assertEqual(b"bar/baz", porcelain.path_to_tree_path("..", "baz"))
  5522. self.assertEqual(
  5523. b"bar/baz",
  5524. porcelain.path_to_tree_path(
  5525. os.path.join(os.getcwd(), ".."),
  5526. os.path.join(os.getcwd(), "baz"),
  5527. ),
  5528. )
  5529. self.assertEqual(
  5530. b"bar/baz",
  5531. porcelain.path_to_tree_path("..", os.path.join(os.getcwd(), "baz")),
  5532. )
  5533. self.assertEqual(
  5534. b"bar/baz",
  5535. porcelain.path_to_tree_path(os.path.join(os.getcwd(), ".."), "baz"),
  5536. )
  5537. class GetObjectByPathTests(PorcelainTestCase):
  5538. def test_simple(self) -> None:
  5539. fullpath = os.path.join(self.repo.path, "foo")
  5540. with open(fullpath, "w") as f:
  5541. f.write("BAR")
  5542. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5543. porcelain.commit(
  5544. self.repo.path,
  5545. message=b"Some message",
  5546. author=b"Joe <joe@example.com>",
  5547. committer=b"Bob <bob@example.com>",
  5548. )
  5549. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  5550. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  5551. def test_encoding(self) -> None:
  5552. fullpath = os.path.join(self.repo.path, "foo")
  5553. with open(fullpath, "w") as f:
  5554. f.write("BAR")
  5555. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5556. porcelain.commit(
  5557. self.repo.path,
  5558. message=b"Some message",
  5559. author=b"Joe <joe@example.com>",
  5560. committer=b"Bob <bob@example.com>",
  5561. encoding=b"utf-8",
  5562. )
  5563. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  5564. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  5565. def test_missing(self) -> None:
  5566. self.assertRaises(KeyError, porcelain.get_object_by_path, self.repo, "foo")
  5567. class WriteTreeTests(PorcelainTestCase):
  5568. def test_simple(self) -> None:
  5569. fullpath = os.path.join(self.repo.path, "foo")
  5570. with open(fullpath, "w") as f:
  5571. f.write("BAR")
  5572. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5573. self.assertEqual(
  5574. b"d2092c8a9f311f0311083bf8d177f2ca0ab5b241",
  5575. porcelain.write_tree(self.repo),
  5576. )
  5577. class ActiveBranchTests(PorcelainTestCase):
  5578. def test_simple(self) -> None:
  5579. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  5580. class BranchTrackingTests(PorcelainTestCase):
  5581. def test_get_branch_merge(self) -> None:
  5582. # Set up branch tracking configuration
  5583. config = self.repo.get_config()
  5584. config.set((b"branch", b"master"), b"remote", b"origin")
  5585. config.set((b"branch", b"master"), b"merge", b"refs/heads/main")
  5586. config.write_to_path()
  5587. # Test getting merge ref for current branch
  5588. merge_ref = porcelain.get_branch_merge(self.repo)
  5589. self.assertEqual(b"refs/heads/main", merge_ref)
  5590. # Test getting merge ref for specific branch
  5591. merge_ref = porcelain.get_branch_merge(self.repo, b"master")
  5592. self.assertEqual(b"refs/heads/main", merge_ref)
  5593. # Test branch without merge config
  5594. with self.assertRaises(KeyError):
  5595. porcelain.get_branch_merge(self.repo, b"nonexistent")
  5596. def test_set_branch_tracking(self) -> None:
  5597. # Create a new branch
  5598. sha, _ = _commit_file_with_content(self.repo, "foo", "content\n")
  5599. porcelain.branch_create(self.repo, "feature")
  5600. # Set up tracking
  5601. porcelain.set_branch_tracking(
  5602. self.repo, b"feature", b"upstream", b"refs/heads/main"
  5603. )
  5604. # Verify configuration was written
  5605. config = self.repo.get_config()
  5606. self.assertEqual(b"upstream", config.get((b"branch", b"feature"), b"remote"))
  5607. self.assertEqual(
  5608. b"refs/heads/main", config.get((b"branch", b"feature"), b"merge")
  5609. )
  5610. class FindUniqueAbbrevTests(PorcelainTestCase):
  5611. def test_simple(self) -> None:
  5612. c1, c2, c3 = build_commit_graph(
  5613. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  5614. )
  5615. self.repo.refs[b"HEAD"] = c3.id
  5616. self.assertEqual(
  5617. c1.id.decode("ascii")[:7],
  5618. porcelain.find_unique_abbrev(self.repo.object_store, c1.id),
  5619. )
  5620. class PackRefsTests(PorcelainTestCase):
  5621. def test_all(self) -> None:
  5622. c1, c2, c3 = build_commit_graph(
  5623. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  5624. )
  5625. self.repo.refs[b"HEAD"] = c3.id
  5626. self.repo.refs[b"refs/heads/master"] = c2.id
  5627. self.repo.refs[b"refs/tags/foo"] = c1.id
  5628. porcelain.pack_refs(self.repo, all=True)
  5629. self.assertEqual(
  5630. self.repo.refs.get_packed_refs(),
  5631. {
  5632. b"refs/heads/master": c2.id,
  5633. b"refs/tags/foo": c1.id,
  5634. },
  5635. )
  5636. def test_not_all(self) -> None:
  5637. c1, c2, c3 = build_commit_graph(
  5638. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  5639. )
  5640. self.repo.refs[b"HEAD"] = c3.id
  5641. self.repo.refs[b"refs/heads/master"] = c2.id
  5642. self.repo.refs[b"refs/tags/foo"] = c1.id
  5643. porcelain.pack_refs(self.repo)
  5644. self.assertEqual(
  5645. self.repo.refs.get_packed_refs(),
  5646. {
  5647. b"refs/tags/foo": c1.id,
  5648. },
  5649. )
  5650. class ServerTests(PorcelainTestCase):
  5651. @contextlib.contextmanager
  5652. def _serving(self):
  5653. with make_server("localhost", 0, self.app) as server:
  5654. thread = threading.Thread(target=server.serve_forever, daemon=True)
  5655. thread.start()
  5656. try:
  5657. yield f"http://localhost:{server.server_port}"
  5658. finally:
  5659. server.shutdown()
  5660. thread.join(10)
  5661. def setUp(self) -> None:
  5662. super().setUp()
  5663. self.served_repo_path = os.path.join(self.test_dir, "served_repo.git")
  5664. self.served_repo = Repo.init_bare(self.served_repo_path, mkdir=True)
  5665. self.addCleanup(self.served_repo.close)
  5666. backend = DictBackend({"/": self.served_repo})
  5667. self.app = make_wsgi_chain(backend)
  5668. def test_pull(self) -> None:
  5669. (c1,) = build_commit_graph(self.served_repo.object_store, [[1]])
  5670. self.served_repo.refs[b"refs/heads/master"] = c1.id
  5671. with self._serving() as url:
  5672. porcelain.pull(self.repo, url, "master")
  5673. def test_push(self) -> None:
  5674. (c1,) = build_commit_graph(self.repo.object_store, [[1]])
  5675. self.repo.refs[b"refs/heads/master"] = c1.id
  5676. with self._serving() as url:
  5677. porcelain.push(self.repo, url, "master")
  5678. class ForEachTests(PorcelainTestCase):
  5679. def setUp(self) -> None:
  5680. super().setUp()
  5681. c1, c2, c3, c4 = build_commit_graph(
  5682. self.repo.object_store, [[1], [2, 1], [3, 1, 2], [4]]
  5683. )
  5684. porcelain.tag_create(
  5685. self.repo.path,
  5686. b"v0.1",
  5687. objectish=c1.id,
  5688. annotated=True,
  5689. message=b"0.1",
  5690. )
  5691. porcelain.tag_create(
  5692. self.repo.path,
  5693. b"v1.0",
  5694. objectish=c2.id,
  5695. annotated=True,
  5696. message=b"1.0",
  5697. )
  5698. porcelain.tag_create(self.repo.path, b"simple-tag", objectish=c3.id)
  5699. porcelain.tag_create(
  5700. self.repo.path,
  5701. b"v1.1",
  5702. objectish=c4.id,
  5703. annotated=True,
  5704. message=b"1.1",
  5705. )
  5706. porcelain.branch_create(
  5707. self.repo.path, b"feat", objectish=c2.id.decode("ascii")
  5708. )
  5709. self.repo.refs[b"HEAD"] = c4.id
  5710. def test_for_each_ref(self) -> None:
  5711. refs = porcelain.for_each_ref(self.repo)
  5712. self.assertEqual(
  5713. [(object_type, tag) for _, object_type, tag in refs],
  5714. [
  5715. (b"commit", b"refs/heads/feat"),
  5716. (b"commit", b"refs/heads/master"),
  5717. (b"commit", b"refs/tags/simple-tag"),
  5718. (b"tag", b"refs/tags/v0.1"),
  5719. (b"tag", b"refs/tags/v1.0"),
  5720. (b"tag", b"refs/tags/v1.1"),
  5721. ],
  5722. )
  5723. def test_for_each_ref_pattern(self) -> None:
  5724. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v*")
  5725. self.assertEqual(
  5726. [(object_type, tag) for _, object_type, tag in versions],
  5727. [
  5728. (b"tag", b"refs/tags/v0.1"),
  5729. (b"tag", b"refs/tags/v1.0"),
  5730. (b"tag", b"refs/tags/v1.1"),
  5731. ],
  5732. )
  5733. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v1.?")
  5734. self.assertEqual(
  5735. [(object_type, tag) for _, object_type, tag in versions],
  5736. [
  5737. (b"tag", b"refs/tags/v1.0"),
  5738. (b"tag", b"refs/tags/v1.1"),
  5739. ],
  5740. )
  5741. class SparseCheckoutTests(PorcelainTestCase):
  5742. """Integration tests for Dulwich's sparse checkout feature."""
  5743. # NOTE: We do NOT override `setUp()` here because the parent class
  5744. # (PorcelainTestCase) already:
  5745. # 1) Creates self.test_dir = a unique temp dir
  5746. # 2) Creates a subdir named "repo"
  5747. # 3) Calls Repo.init() on that path
  5748. # Re-initializing again caused FileExistsError.
  5749. #
  5750. # Utility/Placeholder
  5751. #
  5752. def sparse_checkout(self, repo, patterns, force=False):
  5753. """Wrapper around the actual porcelain.sparse_checkout function
  5754. to handle any test-specific setup or logging.
  5755. """
  5756. return porcelain.sparse_checkout(repo, patterns, force=force)
  5757. def _write_file(self, rel_path, content):
  5758. """Helper to write a file in the repository working tree."""
  5759. abs_path = os.path.join(self.repo_path, rel_path)
  5760. os.makedirs(os.path.dirname(abs_path), exist_ok=True)
  5761. with open(abs_path, "w") as f:
  5762. f.write(content)
  5763. return abs_path
  5764. def _commit_file(self, rel_path, content):
  5765. """Helper to write, add, and commit a file."""
  5766. abs_path = self._write_file(rel_path, content)
  5767. add(self.repo_path, paths=[abs_path])
  5768. commit(self.repo_path, message=b"Added " + rel_path.encode("utf-8"))
  5769. def _list_wtree_files(self):
  5770. """Return a set of all files (not dirs) present
  5771. in the working tree, ignoring .git/.
  5772. """
  5773. found_files = set()
  5774. for root, dirs, files in os.walk(self.repo_path):
  5775. # Skip .git in the walk
  5776. if ".git" in dirs:
  5777. dirs.remove(".git")
  5778. for filename in files:
  5779. file_rel = os.path.relpath(os.path.join(root, filename), self.repo_path)
  5780. found_files.add(file_rel)
  5781. return found_files
  5782. def test_only_included_paths_appear_in_wtree(self):
  5783. """Only included paths remain in the working tree, excluded paths are removed.
  5784. Commits two files, "keep_me.txt" and "exclude_me.txt". Then applies a
  5785. sparse-checkout pattern containing only "keep_me.txt". Ensures that
  5786. the latter remains in the working tree, while "exclude_me.txt" is
  5787. removed. This verifies correct application of sparse-checkout patterns
  5788. to remove files not listed.
  5789. """
  5790. self._commit_file("keep_me.txt", "I'll stay\n")
  5791. self._commit_file("exclude_me.txt", "I'll be excluded\n")
  5792. patterns = ["keep_me.txt"]
  5793. self.sparse_checkout(self.repo, patterns)
  5794. actual_files = self._list_wtree_files()
  5795. expected_files = {"keep_me.txt"}
  5796. self.assertEqual(
  5797. expected_files,
  5798. actual_files,
  5799. f"Expected only {expected_files}, but found {actual_files}",
  5800. )
  5801. def test_previously_included_paths_become_excluded(self):
  5802. """Previously included files become excluded after pattern changes.
  5803. Verifies that files initially brought into the working tree (e.g.,
  5804. by including `data/`) can later be excluded by narrowing the
  5805. sparse-checkout pattern to just `data/included_1.txt`. Confirms that
  5806. the file `data/included_2.txt` remains in the index with
  5807. skip-worktree set (rather than being removed entirely), ensuring
  5808. data is not lost and Dulwich correctly updates the index flags.
  5809. """
  5810. self._commit_file("data/included_1.txt", "some content\n")
  5811. self._commit_file("data/included_2.txt", "other content\n")
  5812. initial_patterns = ["data/"]
  5813. self.sparse_checkout(self.repo, initial_patterns)
  5814. updated_patterns = ["data/included_1.txt"]
  5815. self.sparse_checkout(self.repo, updated_patterns)
  5816. actual_files = self._list_wtree_files()
  5817. expected_files = {os.path.join("data", "included_1.txt")}
  5818. self.assertEqual(expected_files, actual_files)
  5819. idx = self.repo.open_index()
  5820. self.assertIn(b"data/included_2.txt", idx)
  5821. entry = idx[b"data/included_2.txt"]
  5822. self.assertTrue(entry.skip_worktree)
  5823. def test_force_removes_local_changes_for_excluded_paths(self):
  5824. """Forced sparse checkout removes local modifications for newly excluded paths.
  5825. Verifies that specifying force=True allows destructive operations
  5826. which discard uncommitted changes. First, we commit "file1.txt" and
  5827. then modify it. Next, we apply a pattern that excludes the file,
  5828. using force=True. The local modifications (and the file) should
  5829. be removed, leaving the working tree empty.
  5830. """
  5831. self._commit_file("file1.txt", "original content\n")
  5832. file1_path = os.path.join(self.repo_path, "file1.txt")
  5833. with open(file1_path, "a") as f:
  5834. f.write("local changes!\n")
  5835. new_patterns = ["some_other_file.txt"]
  5836. self.sparse_checkout(self.repo, new_patterns, force=True)
  5837. actual_files = self._list_wtree_files()
  5838. self.assertEqual(
  5839. set(),
  5840. actual_files,
  5841. "Force-sparse-checkout did not remove file with local changes.",
  5842. )
  5843. def test_destructive_refuse_uncommitted_changes_without_force(self):
  5844. """Fail on uncommitted changes for newly excluded paths without force.
  5845. Ensures that a sparse checkout is blocked if it would remove local
  5846. modifications from the working tree. We commit 'config.yaml', then
  5847. modify it, and finally attempt to exclude it via new patterns without
  5848. using force=True. This should raise a CheckoutError rather than
  5849. discarding the local changes.
  5850. """
  5851. self._commit_file("config.yaml", "initial\n")
  5852. cfg_path = os.path.join(self.repo_path, "config.yaml")
  5853. with open(cfg_path, "a") as f:
  5854. f.write("local modifications\n")
  5855. exclude_patterns = ["docs/"]
  5856. with self.assertRaises(CheckoutError):
  5857. self.sparse_checkout(self.repo, exclude_patterns, force=False)
  5858. def test_fnmatch_gitignore_pattern_expansion(self):
  5859. """Reading/writing patterns align with gitignore/fnmatch expansions.
  5860. Ensures that `sparse_checkout` interprets wildcard patterns (like `*.py`)
  5861. in the same way Git's sparse-checkout would. Multiple files are committed
  5862. to `src/` (e.g. `foo.py`, `foo_test.py`, `foo_helper.py`) and to `docs/`.
  5863. Then the pattern `src/foo*.py` is applied, confirming that only the
  5864. matching Python files remain in the working tree while the Markdown file
  5865. under `docs/` is excluded.
  5866. Finally, verifies that the `.git/info/sparse-checkout` file contains the
  5867. specified wildcard pattern (`src/foo*.py`), ensuring correct round-trip
  5868. of user-supplied patterns.
  5869. """
  5870. self._commit_file("src/foo.py", "print('hello')\n")
  5871. self._commit_file("src/foo_test.py", "print('test')\n")
  5872. self._commit_file("docs/readme.md", "# docs\n")
  5873. self._commit_file("src/foo_helper.py", "print('helper')\n")
  5874. patterns = ["src/foo*.py"]
  5875. self.sparse_checkout(self.repo, patterns)
  5876. actual_files = self._list_wtree_files()
  5877. expected_files = {
  5878. os.path.join("src", "foo.py"),
  5879. os.path.join("src", "foo_test.py"),
  5880. os.path.join("src", "foo_helper.py"),
  5881. }
  5882. self.assertEqual(
  5883. expected_files,
  5884. actual_files,
  5885. "Wildcard pattern not matched as expected. Either too strict or too broad.",
  5886. )
  5887. sc_file = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  5888. self.assertTrue(os.path.isfile(sc_file))
  5889. with open(sc_file) as f:
  5890. lines = f.read().strip().split()
  5891. self.assertIn("src/foo*.py", lines)
  5892. class ConeModeTests(PorcelainTestCase):
  5893. """Provide integration tests for Dulwich's cone mode sparse checkout.
  5894. This test suite verifies the expected behavior for:
  5895. * cone_mode_init
  5896. * cone_mode_set
  5897. * cone_mode_add
  5898. Although Dulwich does not yet implement cone mode, these tests are
  5899. prepared in advance to guide future development.
  5900. """
  5901. def setUp(self):
  5902. """Set up a fresh repository for each test.
  5903. This method creates a new empty repo_path and Repo object
  5904. as provided by the PorcelainTestCase base class.
  5905. """
  5906. super().setUp()
  5907. def _commit_file(self, rel_path, content=b"contents"):
  5908. """Add a file at the given relative path and commit it.
  5909. Creates necessary directories, writes the file content,
  5910. stages, and commits. The commit message and author/committer
  5911. are also provided.
  5912. """
  5913. full_path = os.path.join(self.repo_path, rel_path)
  5914. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  5915. with open(full_path, "wb") as f:
  5916. f.write(content)
  5917. porcelain.add(self.repo_path, paths=[full_path])
  5918. porcelain.commit(
  5919. self.repo_path,
  5920. message=b"Adding " + rel_path.encode("utf-8"),
  5921. author=b"Test Author <author@example.com>",
  5922. committer=b"Test Committer <committer@example.com>",
  5923. )
  5924. def _list_wtree_files(self):
  5925. """Return a set of all file paths relative to the repository root.
  5926. Walks the working tree, skipping the .git directory.
  5927. """
  5928. found_files = set()
  5929. for root, dirs, files in os.walk(self.repo_path):
  5930. if ".git" in dirs:
  5931. dirs.remove(".git")
  5932. for fn in files:
  5933. relp = os.path.relpath(os.path.join(root, fn), self.repo_path)
  5934. found_files.add(relp)
  5935. return found_files
  5936. def test_init_excludes_everything(self):
  5937. """Verify that cone_mode_init writes minimal patterns and empties the working tree.
  5938. Make some dummy files, commit them, then call cone_mode_init. Confirm
  5939. that the working tree is empty, the sparse-checkout file has the
  5940. minimal patterns (/*, !/*/), and the relevant config values are set.
  5941. """
  5942. self._commit_file("docs/readme.md", b"# doc\n")
  5943. self._commit_file("src/main.py", b"print('hello')\n")
  5944. porcelain.cone_mode_init(self.repo)
  5945. actual_files = self._list_wtree_files()
  5946. self.assertEqual(
  5947. set(),
  5948. actual_files,
  5949. "cone_mode_init did not exclude all files from the working tree.",
  5950. )
  5951. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  5952. with open(sp_path) as f:
  5953. lines = [ln.strip() for ln in f if ln.strip()]
  5954. self.assertIn("/*", lines)
  5955. self.assertIn("!/*/", lines)
  5956. config = self.repo.get_config()
  5957. self.assertEqual(config.get((b"core",), b"sparseCheckout"), b"true")
  5958. self.assertEqual(config.get((b"core",), b"sparseCheckoutCone"), b"true")
  5959. def test_set_specific_dirs(self):
  5960. """Verify that cone_mode_set overwrites the included directories to only the specified ones.
  5961. Initializes cone mode, commits some files, then calls cone_mode_set with
  5962. a list of directories. Expects that only those directories remain in the
  5963. working tree.
  5964. """
  5965. porcelain.cone_mode_init(self.repo)
  5966. self._commit_file("docs/readme.md", b"# doc\n")
  5967. self._commit_file("src/main.py", b"print('hello')\n")
  5968. self._commit_file("tests/test_foo.py", b"# tests\n")
  5969. # Everything is still excluded initially by init.
  5970. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  5971. actual_files = self._list_wtree_files()
  5972. expected_files = {
  5973. os.path.join("docs", "readme.md"),
  5974. os.path.join("src", "main.py"),
  5975. }
  5976. self.assertEqual(
  5977. expected_files,
  5978. actual_files,
  5979. "Did not see only the 'docs/' and 'src/' dirs in the working tree.",
  5980. )
  5981. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  5982. with open(sp_path) as f:
  5983. lines = [ln.strip() for ln in f if ln.strip()]
  5984. # For standard cone mode, we'd expect lines like:
  5985. # /* (include top-level files)
  5986. # !/*/ (exclude subdirectories)
  5987. # !/docs/ (re-include docs)
  5988. # !/src/ (re-include src)
  5989. # Instead of the wildcard-based lines the old test used.
  5990. self.assertIn("/*", lines)
  5991. self.assertIn("!/*/", lines)
  5992. self.assertIn("/docs/", lines)
  5993. self.assertIn("/src/", lines)
  5994. self.assertNotIn("/tests/", lines)
  5995. def test_set_overwrites_old_dirs(self):
  5996. """Ensure that calling cone_mode_set again overwrites old includes.
  5997. Initializes cone mode, includes two directories, then calls
  5998. cone_mode_set again with a different directory to confirm the
  5999. new set of includes replaces the old.
  6000. """
  6001. porcelain.cone_mode_init(self.repo)
  6002. self._commit_file("docs/readme.md")
  6003. self._commit_file("src/main.py")
  6004. self._commit_file("tests/test_bar.py")
  6005. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  6006. self.assertEqual(
  6007. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  6008. self._list_wtree_files(),
  6009. )
  6010. # Overwrite includes, now only 'tests'
  6011. porcelain.cone_mode_set(self.repo, dirs=["tests"], force=True)
  6012. actual_files = self._list_wtree_files()
  6013. expected_files = {os.path.join("tests", "test_bar.py")}
  6014. self.assertEqual(expected_files, actual_files)
  6015. def test_force_removal_of_local_mods(self):
  6016. """Confirm that force=True removes local changes in excluded paths.
  6017. cone_mode_init and cone_mode_set are called, a file is locally modified,
  6018. and then cone_mode_set is called again with force=True to exclude that path.
  6019. The excluded file should be removed with no CheckoutError.
  6020. """
  6021. porcelain.cone_mode_init(self.repo)
  6022. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  6023. self._commit_file("docs/readme.md", b"Docs stuff\n")
  6024. self._commit_file("src/main.py", b"print('hello')\n")
  6025. # Modify src/main.py
  6026. with open(os.path.join(self.repo_path, "src/main.py"), "ab") as f:
  6027. f.write(b"extra line\n")
  6028. # Exclude src/ with force=True
  6029. porcelain.cone_mode_set(self.repo, dirs=["docs"], force=True)
  6030. actual_files = self._list_wtree_files()
  6031. expected_files = {os.path.join("docs", "readme.md")}
  6032. self.assertEqual(expected_files, actual_files)
  6033. def test_add_and_merge_dirs(self):
  6034. """Verify that cone_mode_add merges new directories instead of overwriting them.
  6035. After initializing cone mode and including a single directory, call
  6036. cone_mode_add with a new directory. Confirm that both directories
  6037. remain included. Repeat for an additional directory to ensure it
  6038. is merged, not overwritten.
  6039. """
  6040. porcelain.cone_mode_init(self.repo)
  6041. self._commit_file("docs/readme.md", b"# doc\n")
  6042. self._commit_file("src/main.py", b"print('hello')\n")
  6043. self._commit_file("tests/test_bar.py", b"# tests\n")
  6044. # Include "docs" only
  6045. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  6046. self.assertEqual({os.path.join("docs", "readme.md")}, self._list_wtree_files())
  6047. # Add "src"
  6048. porcelain.cone_mode_add(self.repo, dirs=["src"])
  6049. actual_files = self._list_wtree_files()
  6050. self.assertEqual(
  6051. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  6052. actual_files,
  6053. )
  6054. # Add "tests" as well
  6055. porcelain.cone_mode_add(self.repo, dirs=["tests"])
  6056. actual_files = self._list_wtree_files()
  6057. expected_files = {
  6058. os.path.join("docs", "readme.md"),
  6059. os.path.join("src", "main.py"),
  6060. os.path.join("tests", "test_bar.py"),
  6061. }
  6062. self.assertEqual(expected_files, actual_files)
  6063. # Check .git/info/sparse-checkout
  6064. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  6065. with open(sp_path) as f:
  6066. lines = [ln.strip() for ln in f if ln.strip()]
  6067. # Standard cone mode lines:
  6068. # "/*" -> include top-level
  6069. # "!/*/" -> exclude subdirectories
  6070. # "!/docs/", "!/src/", "!/tests/" -> re-include the directories we added
  6071. self.assertIn("/*", lines)
  6072. self.assertIn("!/*/", lines)
  6073. self.assertIn("/docs/", lines)
  6074. self.assertIn("/src/", lines)
  6075. self.assertIn("/tests/", lines)
  6076. class UnpackObjectsTest(PorcelainTestCase):
  6077. def test_unpack_objects(self):
  6078. """Test unpacking objects from a pack file."""
  6079. # Create a test repository with some objects
  6080. b1 = Blob()
  6081. b1.data = b"test content 1"
  6082. b2 = Blob()
  6083. b2.data = b"test content 2"
  6084. # Add objects to the repo
  6085. self.repo.object_store.add_object(b1)
  6086. self.repo.object_store.add_object(b2)
  6087. # Create a pack file with these objects
  6088. pack_path = os.path.join(self.test_dir, "test_pack")
  6089. with (
  6090. open(pack_path + ".pack", "wb") as pack_f,
  6091. open(pack_path + ".idx", "wb") as idx_f,
  6092. ):
  6093. porcelain.pack_objects(
  6094. self.repo,
  6095. [b1.id, b2.id],
  6096. pack_f,
  6097. idx_f,
  6098. )
  6099. # Create a new repository to unpack into
  6100. target_repo_path = os.path.join(self.test_dir, "target_repo")
  6101. target_repo = Repo.init(target_repo_path, mkdir=True)
  6102. self.addCleanup(target_repo.close)
  6103. # Unpack the objects
  6104. count = porcelain.unpack_objects(pack_path + ".pack", target_repo_path)
  6105. # Verify the objects were unpacked
  6106. self.assertEqual(2, count)
  6107. self.assertIn(b1.id, target_repo.object_store)
  6108. self.assertIn(b2.id, target_repo.object_store)
  6109. # Verify the content is correct
  6110. unpacked_b1 = target_repo.object_store[b1.id]
  6111. unpacked_b2 = target_repo.object_store[b2.id]
  6112. self.assertEqual(b1.data, unpacked_b1.data)
  6113. self.assertEqual(b2.data, unpacked_b2.data)
  6114. class CountObjectsTests(PorcelainTestCase):
  6115. def test_count_objects_empty_repo(self):
  6116. """Test counting objects in an empty repository."""
  6117. stats = porcelain.count_objects(self.repo)
  6118. self.assertEqual(0, stats.count)
  6119. self.assertEqual(0, stats.size)
  6120. def test_count_objects_verbose_empty_repo(self):
  6121. """Test verbose counting in an empty repository."""
  6122. stats = porcelain.count_objects(self.repo, verbose=True)
  6123. self.assertEqual(0, stats.count)
  6124. self.assertEqual(0, stats.size)
  6125. self.assertEqual(0, stats.in_pack)
  6126. self.assertEqual(0, stats.packs)
  6127. self.assertEqual(0, stats.size_pack)
  6128. def test_count_objects_with_loose_objects(self):
  6129. """Test counting loose objects."""
  6130. # Create some loose objects
  6131. blob1 = make_object(Blob, data=b"data1")
  6132. blob2 = make_object(Blob, data=b"data2")
  6133. self.repo.object_store.add_object(blob1)
  6134. self.repo.object_store.add_object(blob2)
  6135. stats = porcelain.count_objects(self.repo)
  6136. self.assertEqual(2, stats.count)
  6137. self.assertGreater(stats.size, 0)
  6138. def test_count_objects_verbose_with_objects(self):
  6139. """Test verbose counting with both loose and packed objects."""
  6140. # Add some loose objects
  6141. for i in range(3):
  6142. blob = make_object(Blob, data=f"data{i}".encode())
  6143. self.repo.object_store.add_object(blob)
  6144. # Create a simple commit to have some objects in a pack
  6145. tree = Tree()
  6146. c1 = make_commit(tree=tree.id, message=b"Test commit")
  6147. self.repo.object_store.add_objects([(tree, None), (c1, None)])
  6148. self.repo.refs[b"HEAD"] = c1.id
  6149. # Repack to create a pack file
  6150. porcelain.repack(self.repo)
  6151. stats = porcelain.count_objects(self.repo, verbose=True)
  6152. # After repacking, loose objects might be cleaned up
  6153. self.assertIsInstance(stats.count, int)
  6154. self.assertIsInstance(stats.size, int)
  6155. self.assertGreater(stats.in_pack, 0) # Should have packed objects
  6156. self.assertGreater(stats.packs, 0) # Should have at least one pack
  6157. self.assertGreater(stats.size_pack, 0) # Pack should have size
  6158. # Verify it's the correct dataclass type
  6159. self.assertIsInstance(stats, CountObjectsResult)
  6160. class PruneTests(PorcelainTestCase):
  6161. def test_prune_removes_old_tempfiles(self):
  6162. """Test that prune removes old temporary files."""
  6163. # Create an old temporary file in the objects directory
  6164. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  6165. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_test")
  6166. with open(tmp_pack_path, "wb") as f:
  6167. f.write(b"old temporary data")
  6168. # Make it old
  6169. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  6170. os.utime(tmp_pack_path, (old_time, old_time))
  6171. # Run prune
  6172. porcelain.prune(self.repo.path)
  6173. # Verify the file was removed
  6174. self.assertFalse(os.path.exists(tmp_pack_path))
  6175. def test_prune_keeps_recent_tempfiles(self):
  6176. """Test that prune keeps recent temporary files."""
  6177. # Create a recent temporary file
  6178. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  6179. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_recent")
  6180. with open(tmp_pack_path, "wb") as f:
  6181. f.write(b"recent temporary data")
  6182. self.addCleanup(os.remove, tmp_pack_path)
  6183. # Run prune
  6184. porcelain.prune(self.repo.path)
  6185. # Verify the file was NOT removed
  6186. self.assertTrue(os.path.exists(tmp_pack_path))
  6187. def test_prune_with_custom_grace_period(self):
  6188. """Test prune with custom grace period."""
  6189. # Create a 1-hour-old temporary file
  6190. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  6191. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_1hour")
  6192. with open(tmp_pack_path, "wb") as f:
  6193. f.write(b"1 hour old data")
  6194. # Make it 1 hour old
  6195. old_time = time.time() - 3600
  6196. os.utime(tmp_pack_path, (old_time, old_time))
  6197. # Prune with 30-minute grace period should remove it
  6198. porcelain.prune(self.repo.path, grace_period=1800)
  6199. # Verify the file was removed
  6200. self.assertFalse(os.path.exists(tmp_pack_path))
  6201. def test_prune_dry_run(self):
  6202. """Test prune in dry-run mode."""
  6203. # Create an old temporary file
  6204. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  6205. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_dryrun")
  6206. with open(tmp_pack_path, "wb") as f:
  6207. f.write(b"old temporary data")
  6208. self.addCleanup(os.remove, tmp_pack_path)
  6209. # Make it old
  6210. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  6211. os.utime(tmp_pack_path, (old_time, old_time))
  6212. # Run prune in dry-run mode
  6213. porcelain.prune(self.repo.path, dry_run=True)
  6214. # Verify the file was NOT removed (dry run)
  6215. self.assertTrue(os.path.exists(tmp_pack_path))
  6216. class FilterBranchTests(PorcelainTestCase):
  6217. def setUp(self):
  6218. super().setUp()
  6219. # Create initial commits with different authors
  6220. from dulwich.objects import Commit, Tree
  6221. # Create actual tree and blob objects
  6222. tree = Tree()
  6223. self.repo.object_store.add_object(tree)
  6224. c1 = Commit()
  6225. c1.tree = tree.id
  6226. c1.parents = []
  6227. c1.author = b"Old Author <old@example.com>"
  6228. c1.author_time = 1000
  6229. c1.author_timezone = 0
  6230. c1.committer = b"Old Committer <old@example.com>"
  6231. c1.commit_time = 1000
  6232. c1.commit_timezone = 0
  6233. c1.message = b"Initial commit"
  6234. self.repo.object_store.add_object(c1)
  6235. c2 = Commit()
  6236. c2.tree = tree.id
  6237. c2.parents = [c1.id]
  6238. c2.author = b"Another Author <another@example.com>"
  6239. c2.author_time = 2000
  6240. c2.author_timezone = 0
  6241. c2.committer = b"Another Committer <another@example.com>"
  6242. c2.commit_time = 2000
  6243. c2.commit_timezone = 0
  6244. c2.message = b"Second commit\n\nWith body"
  6245. self.repo.object_store.add_object(c2)
  6246. c3 = Commit()
  6247. c3.tree = tree.id
  6248. c3.parents = [c2.id]
  6249. c3.author = b"Third Author <third@example.com>"
  6250. c3.author_time = 3000
  6251. c3.author_timezone = 0
  6252. c3.committer = b"Third Committer <third@example.com>"
  6253. c3.commit_time = 3000
  6254. c3.commit_timezone = 0
  6255. c3.message = b"Third commit"
  6256. self.repo.object_store.add_object(c3)
  6257. self.repo.refs[b"refs/heads/master"] = c3.id
  6258. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  6259. # Store IDs for test assertions
  6260. self.c1_id = c1.id
  6261. self.c2_id = c2.id
  6262. self.c3_id = c3.id
  6263. def test_filter_branch_author(self):
  6264. """Test filtering branch with author changes."""
  6265. def filter_author(author):
  6266. # Change all authors to "New Author"
  6267. return b"New Author <new@example.com>"
  6268. result = porcelain.filter_branch(
  6269. self.repo_path, "master", filter_author=filter_author
  6270. )
  6271. # Check that we have mappings for all commits
  6272. self.assertEqual(len(result), 3)
  6273. # Verify the branch ref was updated
  6274. new_head = self.repo.refs[b"refs/heads/master"]
  6275. self.assertNotEqual(new_head, self.c3_id)
  6276. # Verify the original ref was saved
  6277. original_ref = self.repo.refs[b"refs/original/refs/heads/master"]
  6278. self.assertEqual(original_ref, self.c3_id)
  6279. # Check that authors were updated
  6280. new_commit = self.repo[new_head]
  6281. self.assertEqual(new_commit.author, b"New Author <new@example.com>")
  6282. # Check parent chain
  6283. parent = self.repo[new_commit.parents[0]]
  6284. self.assertEqual(parent.author, b"New Author <new@example.com>")
  6285. def test_filter_branch_message(self):
  6286. """Test filtering branch with message changes."""
  6287. def filter_message(message):
  6288. # Add prefix to all messages
  6289. return b"[FILTERED] " + message
  6290. porcelain.filter_branch(self.repo_path, "master", filter_message=filter_message)
  6291. # Verify messages were updated
  6292. new_head = self.repo.refs[b"refs/heads/master"]
  6293. new_commit = self.repo[new_head]
  6294. self.assertTrue(new_commit.message.startswith(b"[FILTERED] "))
  6295. def test_filter_branch_custom_filter(self):
  6296. """Test filtering branch with custom filter function."""
  6297. def custom_filter(commit):
  6298. # Change both author and message
  6299. return {
  6300. "author": b"Custom Author <custom@example.com>",
  6301. "message": b"Custom: " + commit.message,
  6302. }
  6303. porcelain.filter_branch(self.repo_path, "master", filter_fn=custom_filter)
  6304. # Verify custom filter was applied
  6305. new_head = self.repo.refs[b"refs/heads/master"]
  6306. new_commit = self.repo[new_head]
  6307. self.assertEqual(new_commit.author, b"Custom Author <custom@example.com>")
  6308. self.assertTrue(new_commit.message.startswith(b"Custom: "))
  6309. def test_filter_branch_no_changes(self):
  6310. """Test filtering branch with no changes."""
  6311. result = porcelain.filter_branch(self.repo_path, "master")
  6312. # All commits should map to themselves
  6313. for old_sha, new_sha in result.items():
  6314. self.assertEqual(old_sha, new_sha)
  6315. # HEAD should be unchanged
  6316. self.assertEqual(self.repo.refs[b"refs/heads/master"], self.c3_id)
  6317. def test_filter_branch_force(self):
  6318. """Test force filtering a previously filtered branch."""
  6319. # First filter
  6320. porcelain.filter_branch(
  6321. self.repo_path, "master", filter_message=lambda m: b"First: " + m
  6322. )
  6323. # Try again without force - should fail
  6324. with self.assertRaises(porcelain.Error):
  6325. porcelain.filter_branch(
  6326. self.repo_path, "master", filter_message=lambda m: b"Second: " + m
  6327. )
  6328. # Try again with force - should succeed
  6329. porcelain.filter_branch(
  6330. self.repo_path,
  6331. "master",
  6332. filter_message=lambda m: b"Second: " + m,
  6333. force=True,
  6334. )
  6335. # Verify second filter was applied
  6336. new_head = self.repo.refs[b"refs/heads/master"]
  6337. new_commit = self.repo[new_head]
  6338. self.assertTrue(new_commit.message.startswith(b"Second: First: "))
  6339. class StashTests(PorcelainTestCase):
  6340. def setUp(self) -> None:
  6341. super().setUp()
  6342. # Create initial commit
  6343. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  6344. f.write(b"initial content")
  6345. porcelain.add(repo=self.repo.path, paths=["initial.txt"])
  6346. porcelain.commit(
  6347. repo=self.repo.path,
  6348. message=b"Initial commit",
  6349. author=b"Test Author <test@example.com>",
  6350. committer=b"Test Committer <test@example.com>",
  6351. )
  6352. def test_stash_push_and_pop(self) -> None:
  6353. # Create a new file and stage it
  6354. new_file = os.path.join(self.repo.path, "new.txt")
  6355. with open(new_file, "wb") as f:
  6356. f.write(b"new file content")
  6357. porcelain.add(repo=self.repo.path, paths=["new.txt"])
  6358. # Modify existing file
  6359. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  6360. f.write(b"modified content")
  6361. # Push to stash
  6362. porcelain.stash_push(self.repo.path)
  6363. # Verify files are reset
  6364. self.assertFalse(os.path.exists(new_file))
  6365. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  6366. self.assertEqual(b"initial content", f.read())
  6367. # Pop the stash
  6368. porcelain.stash_pop(self.repo.path)
  6369. # Verify files are restored
  6370. self.assertTrue(os.path.exists(new_file))
  6371. with open(new_file, "rb") as f:
  6372. self.assertEqual(b"new file content", f.read())
  6373. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  6374. self.assertEqual(b"modified content", f.read())
  6375. # Verify new file is in the index
  6376. from dulwich.index import Index
  6377. index = Index(os.path.join(self.repo.path, ".git", "index"))
  6378. self.assertIn(b"new.txt", index)
  6379. def test_stash_list(self) -> None:
  6380. # Initially no stashes
  6381. stashes = list(porcelain.stash_list(self.repo.path))
  6382. self.assertEqual(0, len(stashes))
  6383. # Create a file and stash it
  6384. test_file = os.path.join(self.repo.path, "test.txt")
  6385. with open(test_file, "wb") as f:
  6386. f.write(b"test content")
  6387. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  6388. # Push first stash
  6389. porcelain.stash_push(self.repo.path)
  6390. # Create another file and stash it
  6391. test_file2 = os.path.join(self.repo.path, "test2.txt")
  6392. with open(test_file2, "wb") as f:
  6393. f.write(b"test content 2")
  6394. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  6395. # Push second stash
  6396. porcelain.stash_push(self.repo.path)
  6397. # Check stash list
  6398. stashes = list(porcelain.stash_list(self.repo.path))
  6399. self.assertEqual(2, len(stashes))
  6400. # Stashes are returned in order (most recent first)
  6401. self.assertEqual(0, stashes[0][0])
  6402. self.assertEqual(1, stashes[1][0])
  6403. def test_stash_drop(self) -> None:
  6404. # Create and stash some changes
  6405. test_file = os.path.join(self.repo.path, "test.txt")
  6406. with open(test_file, "wb") as f:
  6407. f.write(b"test content")
  6408. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  6409. porcelain.stash_push(self.repo.path)
  6410. # Create another stash
  6411. test_file2 = os.path.join(self.repo.path, "test2.txt")
  6412. with open(test_file2, "wb") as f:
  6413. f.write(b"test content 2")
  6414. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  6415. porcelain.stash_push(self.repo.path)
  6416. # Verify we have 2 stashes
  6417. stashes = list(porcelain.stash_list(self.repo.path))
  6418. self.assertEqual(2, len(stashes))
  6419. # Drop the first stash (index 0)
  6420. porcelain.stash_drop(self.repo.path, 0)
  6421. # Verify we have 1 stash left
  6422. stashes = list(porcelain.stash_list(self.repo.path))
  6423. self.assertEqual(1, len(stashes))
  6424. # The remaining stash should be the one we created first
  6425. # Pop it and verify it's the first file
  6426. porcelain.stash_pop(self.repo.path)
  6427. self.assertTrue(os.path.exists(test_file))
  6428. self.assertFalse(os.path.exists(test_file2))
  6429. def test_stash_pop_empty(self) -> None:
  6430. # Attempting to pop from empty stash should raise an error
  6431. with self.assertRaises(IndexError):
  6432. porcelain.stash_pop(self.repo.path)
  6433. def test_stash_with_untracked_files(self) -> None:
  6434. # Create an untracked file
  6435. untracked_file = os.path.join(self.repo.path, "untracked.txt")
  6436. with open(untracked_file, "wb") as f:
  6437. f.write(b"untracked content")
  6438. # Create a tracked change
  6439. tracked_file = os.path.join(self.repo.path, "tracked.txt")
  6440. with open(tracked_file, "wb") as f:
  6441. f.write(b"tracked content")
  6442. porcelain.add(repo=self.repo.path, paths=["tracked.txt"])
  6443. # Stash (by default, untracked files are not included)
  6444. porcelain.stash_push(self.repo.path)
  6445. # Untracked file should still exist
  6446. self.assertTrue(os.path.exists(untracked_file))
  6447. # Tracked file should be gone
  6448. self.assertFalse(os.path.exists(tracked_file))
  6449. # Pop the stash
  6450. porcelain.stash_pop(self.repo.path)
  6451. # Tracked file should be restored
  6452. self.assertTrue(os.path.exists(tracked_file))
  6453. class BisectTests(PorcelainTestCase):
  6454. """Tests for bisect porcelain functions."""
  6455. def test_bisect_start(self):
  6456. """Test starting a bisect session."""
  6457. # Create some commits
  6458. c1, c2, c3 = build_commit_graph(
  6459. self.repo.object_store,
  6460. [[1], [2, 1], [3, 2]],
  6461. attrs={
  6462. 1: {"message": b"initial"},
  6463. 2: {"message": b"second"},
  6464. 3: {"message": b"third"},
  6465. },
  6466. )
  6467. self.repo.refs[b"refs/heads/master"] = c3.id
  6468. self.repo.refs[b"HEAD"] = c3.id
  6469. # Start bisect
  6470. porcelain.bisect_start(self.repo_path)
  6471. # Check that bisect state files exist
  6472. self.assertTrue(
  6473. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  6474. )
  6475. self.assertTrue(
  6476. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_TERMS"))
  6477. )
  6478. self.assertTrue(
  6479. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_NAMES"))
  6480. )
  6481. self.assertTrue(
  6482. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_LOG"))
  6483. )
  6484. def test_bisect_workflow(self):
  6485. """Test a complete bisect workflow."""
  6486. # Create some commits
  6487. c1, c2, c3, c4 = build_commit_graph(
  6488. self.repo.object_store,
  6489. [[1], [2, 1], [3, 2], [4, 3]],
  6490. attrs={
  6491. 1: {"message": b"good commit 1"},
  6492. 2: {"message": b"good commit 2"},
  6493. 3: {"message": b"bad commit"},
  6494. 4: {"message": b"bad commit 2"},
  6495. },
  6496. )
  6497. self.repo.refs[b"refs/heads/master"] = c4.id
  6498. self.repo.refs[b"HEAD"] = c4.id
  6499. # Start bisect with bad and good
  6500. next_sha = porcelain.bisect_start(self.repo_path, bad=c4.id, good=c1.id)
  6501. # Should return the middle commit
  6502. self.assertIsNotNone(next_sha)
  6503. self.assertIn(next_sha, [c2.id, c3.id])
  6504. # Mark the middle commit as good or bad
  6505. if next_sha == c2.id:
  6506. # c2 is good, next should be c3
  6507. next_sha = porcelain.bisect_good(self.repo_path)
  6508. self.assertEqual(next_sha, c3.id)
  6509. # Mark c3 as bad - bisect complete
  6510. next_sha = porcelain.bisect_bad(self.repo_path)
  6511. self.assertIsNone(next_sha)
  6512. else:
  6513. # c3 is bad, next should be c2
  6514. next_sha = porcelain.bisect_bad(self.repo_path)
  6515. self.assertEqual(next_sha, c2.id)
  6516. # Mark c2 as good - bisect complete
  6517. next_sha = porcelain.bisect_good(self.repo_path)
  6518. self.assertIsNone(next_sha)
  6519. def test_bisect_log(self):
  6520. """Test getting bisect log."""
  6521. # Create some commits
  6522. c1, c2, c3 = build_commit_graph(
  6523. self.repo.object_store,
  6524. [[1], [2, 1], [3, 2]],
  6525. attrs={
  6526. 1: {"message": b"initial"},
  6527. 2: {"message": b"second"},
  6528. 3: {"message": b"third"},
  6529. },
  6530. )
  6531. self.repo.refs[b"refs/heads/master"] = c3.id
  6532. self.repo.refs[b"HEAD"] = c3.id
  6533. # Start bisect and mark commits
  6534. porcelain.bisect_start(self.repo_path)
  6535. porcelain.bisect_bad(self.repo_path, c3.id)
  6536. porcelain.bisect_good(self.repo_path, c1.id)
  6537. # Get log
  6538. log = porcelain.bisect_log(self.repo_path)
  6539. self.assertIn("git bisect start", log)
  6540. self.assertIn("git bisect bad", log)
  6541. self.assertIn("git bisect good", log)
  6542. def test_bisect_reset(self):
  6543. """Test resetting bisect state."""
  6544. # Create some commits
  6545. c1, c2, c3 = build_commit_graph(
  6546. self.repo.object_store,
  6547. [[1], [2, 1], [3, 2]],
  6548. attrs={
  6549. 1: {"message": b"initial"},
  6550. 2: {"message": b"second"},
  6551. 3: {"message": b"third"},
  6552. },
  6553. )
  6554. self.repo.refs[b"refs/heads/master"] = c3.id
  6555. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  6556. # Start bisect
  6557. porcelain.bisect_start(self.repo_path)
  6558. porcelain.bisect_bad(self.repo_path)
  6559. porcelain.bisect_good(self.repo_path, c1.id)
  6560. # Reset
  6561. porcelain.bisect_reset(self.repo_path)
  6562. # Check that bisect state files are removed
  6563. self.assertFalse(
  6564. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  6565. )
  6566. self.assertFalse(
  6567. os.path.exists(os.path.join(self.repo.controldir(), "refs", "bisect"))
  6568. )
  6569. # HEAD should be back to being a symbolic ref to master
  6570. head_target, _ = self.repo.refs.follow(b"HEAD")
  6571. self.assertEqual(head_target[-1], b"refs/heads/master")
  6572. def test_bisect_skip(self):
  6573. """Test skipping commits during bisect."""
  6574. # Create some commits
  6575. c1, c2, c3, c4, c5 = build_commit_graph(
  6576. self.repo.object_store,
  6577. [[1], [2, 1], [3, 2], [4, 3], [5, 4]],
  6578. attrs={
  6579. 1: {"message": b"good"},
  6580. 2: {"message": b"skip this"},
  6581. 3: {"message": b"bad"},
  6582. 4: {"message": b"bad"},
  6583. 5: {"message": b"bad"},
  6584. },
  6585. )
  6586. self.repo.refs[b"refs/heads/master"] = c5.id
  6587. self.repo.refs[b"HEAD"] = c5.id
  6588. # Start bisect
  6589. porcelain.bisect_start(self.repo_path, bad=c5.id, good=c1.id)
  6590. # Skip c2 if it's selected
  6591. next_sha = porcelain.bisect_skip(self.repo_path, [c2.id])
  6592. self.assertIsNotNone(next_sha)
  6593. class ReflogTest(PorcelainTestCase):
  6594. def test_reflog_head(self):
  6595. """Test reading HEAD reflog."""
  6596. # Create a commit
  6597. blob = Blob.from_string(b"test content")
  6598. self.repo.object_store.add_object(blob)
  6599. tree = Tree()
  6600. tree.add(b"test", 0o100644, blob.id)
  6601. self.repo.object_store.add_object(tree)
  6602. commit = Commit()
  6603. commit.tree = tree.id
  6604. commit.author = b"Test Author <test@example.com>"
  6605. commit.committer = b"Test Author <test@example.com>"
  6606. commit.commit_time = 1234567890
  6607. commit.commit_timezone = 0
  6608. commit.author_time = 1234567890
  6609. commit.author_timezone = 0
  6610. commit.message = b"Initial commit"
  6611. self.repo.object_store.add_object(commit)
  6612. # Write a reflog entry
  6613. self.repo._write_reflog(
  6614. b"HEAD",
  6615. ZERO_SHA,
  6616. commit.id,
  6617. b"Test Author <test@example.com>",
  6618. 1234567890,
  6619. 0,
  6620. b"commit (initial): Initial commit",
  6621. )
  6622. # Read reflog using porcelain
  6623. entries = list(porcelain.reflog(self.repo_path))
  6624. self.assertEqual(1, len(entries))
  6625. self.assertEqual(ZERO_SHA, entries[0].old_sha)
  6626. self.assertEqual(commit.id, entries[0].new_sha)
  6627. self.assertEqual(b"Test Author <test@example.com>", entries[0].committer)
  6628. self.assertEqual(1234567890, entries[0].timestamp)
  6629. self.assertEqual(0, entries[0].timezone)
  6630. self.assertEqual(b"commit (initial): Initial commit", entries[0].message)
  6631. def test_reflog_with_string_ref(self):
  6632. """Test reading reflog with string reference."""
  6633. # Create a commit
  6634. blob = Blob.from_string(b"test content")
  6635. self.repo.object_store.add_object(blob)
  6636. tree = Tree()
  6637. tree.add(b"test", 0o100644, blob.id)
  6638. self.repo.object_store.add_object(tree)
  6639. commit = Commit()
  6640. commit.tree = tree.id
  6641. commit.author = b"Test Author <test@example.com>"
  6642. commit.committer = b"Test Author <test@example.com>"
  6643. commit.commit_time = 1234567890
  6644. commit.commit_timezone = 0
  6645. commit.author_time = 1234567890
  6646. commit.author_timezone = 0
  6647. commit.message = b"Initial commit"
  6648. self.repo.object_store.add_object(commit)
  6649. # Write a reflog entry
  6650. self.repo._write_reflog(
  6651. b"refs/heads/master",
  6652. ZERO_SHA,
  6653. commit.id,
  6654. b"Test Author <test@example.com>",
  6655. 1234567890,
  6656. 0,
  6657. b"commit (initial): Initial commit",
  6658. )
  6659. # Read reflog using porcelain with string ref
  6660. entries = list(porcelain.reflog(self.repo_path, "refs/heads/master"))
  6661. self.assertEqual(1, len(entries))
  6662. self.assertEqual(commit.id, entries[0].new_sha)
  6663. def test_reflog_all(self):
  6664. """Test reading all reflogs."""
  6665. # Create a commit
  6666. blob = Blob.from_string(b"test content")
  6667. self.repo.object_store.add_object(blob)
  6668. tree = Tree()
  6669. tree.add(b"test", 0o100644, blob.id)
  6670. self.repo.object_store.add_object(tree)
  6671. commit = Commit()
  6672. commit.tree = tree.id
  6673. commit.author = b"Test Author <test@example.com>"
  6674. commit.committer = b"Test Author <test@example.com>"
  6675. commit.commit_time = 1234567890
  6676. commit.commit_timezone = 0
  6677. commit.author_time = 1234567890
  6678. commit.author_timezone = 0
  6679. commit.message = b"Initial commit"
  6680. self.repo.object_store.add_object(commit)
  6681. # Write reflog entries for HEAD and master
  6682. self.repo._write_reflog(
  6683. b"HEAD",
  6684. ZERO_SHA,
  6685. commit.id,
  6686. b"Test Author <test@example.com>",
  6687. 1234567890,
  6688. 0,
  6689. b"commit (initial): Initial commit",
  6690. )
  6691. self.repo._write_reflog(
  6692. b"refs/heads/master",
  6693. ZERO_SHA,
  6694. commit.id,
  6695. b"Test Author <test@example.com>",
  6696. 1234567891,
  6697. 0,
  6698. b"branch: Created from HEAD",
  6699. )
  6700. # Read all reflogs using porcelain
  6701. entries = list(porcelain.reflog(self.repo_path, all=True))
  6702. # Should have at least 2 entries (HEAD and refs/heads/master)
  6703. self.assertGreaterEqual(len(entries), 2)
  6704. # Check that we got entries from different refs
  6705. refs_seen = set()
  6706. for ref, entry in entries:
  6707. refs_seen.add(ref)
  6708. self.assertEqual(commit.id, entry.new_sha)
  6709. # Should have seen at least HEAD and refs/heads/master
  6710. self.assertIn(b"HEAD", refs_seen)
  6711. self.assertIn(b"refs/heads/master", refs_seen)
  6712. class WriteCommitGraphTests(PorcelainTestCase):
  6713. """Tests for the write_commit_graph porcelain function."""
  6714. def test_write_commit_graph_empty_repo(self):
  6715. """Test writing commit graph on empty repository."""
  6716. # Should not fail on empty repo
  6717. porcelain.write_commit_graph(self.repo_path)
  6718. # No commit graph should be created for empty repo
  6719. graph_path = os.path.join(
  6720. self.repo_path, ".git", "objects", "info", "commit-graph"
  6721. )
  6722. self.assertFalse(os.path.exists(graph_path))
  6723. def test_write_commit_graph_with_commits(self):
  6724. """Test writing commit graph with commits."""
  6725. # Create some commits
  6726. c1, c2, c3 = build_commit_graph(
  6727. self.repo.object_store,
  6728. [[1], [2, 1], [3, 1, 2]],
  6729. attrs={
  6730. 1: {"message": b"First commit"},
  6731. 2: {"message": b"Second commit"},
  6732. 3: {"message": b"Merge commit"},
  6733. },
  6734. )
  6735. self.repo.refs[b"refs/heads/master"] = c3.id
  6736. self.repo.refs[b"refs/heads/branch"] = c2.id
  6737. # Write commit graph
  6738. porcelain.write_commit_graph(self.repo_path)
  6739. # Verify commit graph was created
  6740. graph_path = os.path.join(
  6741. self.repo_path, ".git", "objects", "info", "commit-graph"
  6742. )
  6743. self.assertTrue(os.path.exists(graph_path))
  6744. # Load and verify the commit graph
  6745. from dulwich.commit_graph import read_commit_graph
  6746. commit_graph = read_commit_graph(graph_path)
  6747. self.assertIsNotNone(commit_graph)
  6748. self.assertEqual(3, len(commit_graph))
  6749. # Verify all commits are in the graph
  6750. for commit_obj in [c1, c2, c3]:
  6751. entry = commit_graph.get_entry_by_oid(commit_obj.id)
  6752. self.assertIsNotNone(entry)
  6753. def test_write_commit_graph_config_disabled(self):
  6754. """Test that commit graph is not written when disabled by config."""
  6755. # Create a commit
  6756. (c1,) = build_commit_graph(
  6757. self.repo.object_store, [[1]], attrs={1: {"message": b"First commit"}}
  6758. )
  6759. self.repo.refs[b"refs/heads/master"] = c1.id
  6760. # Disable commit graph in config
  6761. config = self.repo.get_config()
  6762. config.set((b"core",), b"commitGraph", b"false")
  6763. config.write_to_path()
  6764. # Write commit graph (should respect config)
  6765. porcelain.write_commit_graph(self.repo_path)
  6766. # Verify commit graph still gets written
  6767. # (porcelain.write_commit_graph explicitly writes regardless of config)
  6768. graph_path = os.path.join(
  6769. self.repo_path, ".git", "objects", "info", "commit-graph"
  6770. )
  6771. self.assertTrue(os.path.exists(graph_path))
  6772. def test_write_commit_graph_reachable_false(self):
  6773. """Test writing commit graph with reachable=False."""
  6774. # Create commits
  6775. c1, c2, c3 = build_commit_graph(
  6776. self.repo.object_store,
  6777. [[1], [2, 1], [3, 2]],
  6778. attrs={
  6779. 1: {"message": b"First commit"},
  6780. 2: {"message": b"Second commit"},
  6781. 3: {"message": b"Third commit"},
  6782. },
  6783. )
  6784. # Only reference the third commit
  6785. self.repo.refs[b"refs/heads/master"] = c3.id
  6786. # Write commit graph with reachable=False
  6787. porcelain.write_commit_graph(self.repo_path, reachable=False)
  6788. # Verify commit graph was created
  6789. graph_path = os.path.join(
  6790. self.repo_path, ".git", "objects", "info", "commit-graph"
  6791. )
  6792. self.assertTrue(os.path.exists(graph_path))
  6793. # Load and verify the commit graph
  6794. from dulwich.commit_graph import read_commit_graph
  6795. commit_graph = read_commit_graph(graph_path)
  6796. self.assertIsNotNone(commit_graph)
  6797. # With reachable=False, only directly referenced commits should be included
  6798. # In this case, only c3 (from refs/heads/master)
  6799. self.assertEqual(1, len(commit_graph))
  6800. entry = commit_graph.get_entry_by_oid(c3.id)
  6801. self.assertIsNotNone(entry)