test_porcelain.py 305 KB

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