__init__.py 410 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209
  1. # test_porcelain.py -- porcelain tests
  2. # Copyright (C) 2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Tests for dulwich.porcelain."""
  22. import contextlib
  23. import os
  24. import platform
  25. import re
  26. import shutil
  27. import stat
  28. import subprocess
  29. import sys
  30. import tarfile
  31. import tempfile
  32. import threading
  33. import time
  34. from io import BytesIO, StringIO
  35. from unittest import skipIf
  36. from dulwich import porcelain
  37. from dulwich.client import SendPackResult
  38. from dulwich.diff_tree import tree_changes
  39. from dulwich.errors import CommitError
  40. from dulwich.object_store import DEFAULT_TEMPFILE_GRACE_PERIOD
  41. from dulwich.objects import ZERO_SHA, Blob, Commit, Tag, Tree
  42. from dulwich.porcelain import (
  43. CheckoutError, # Hypothetical or real error class
  44. CountObjectsResult,
  45. add,
  46. commit,
  47. )
  48. from dulwich.repo import NoIndexPresent, Repo
  49. from dulwich.server import DictBackend
  50. from dulwich.tests.utils import build_commit_graph, make_commit, make_object
  51. from dulwich.web import make_server, make_wsgi_chain
  52. from .. import TestCase
  53. try:
  54. import gpg
  55. except ImportError:
  56. gpg = None
  57. def flat_walk_dir(dir_to_walk):
  58. for dirpath, _, filenames in os.walk(dir_to_walk):
  59. rel_dirpath = os.path.relpath(dirpath, dir_to_walk)
  60. if not dirpath == dir_to_walk:
  61. yield rel_dirpath
  62. for filename in filenames:
  63. if dirpath == dir_to_walk:
  64. yield filename
  65. else:
  66. yield os.path.join(rel_dirpath, filename)
  67. class PorcelainTestCase(TestCase):
  68. def setUp(self) -> None:
  69. super().setUp()
  70. # Disable pagers for tests
  71. self.overrideEnv("PAGER", "false")
  72. self.overrideEnv("GIT_PAGER", "false")
  73. self.overrideEnv("DULWICH_PAGER", "false")
  74. self.test_dir = tempfile.mkdtemp()
  75. self.addCleanup(shutil.rmtree, self.test_dir)
  76. self.repo_path = os.path.join(self.test_dir, "repo")
  77. self.repo = Repo.init(self.repo_path, mkdir=True)
  78. self.addCleanup(self.repo.close)
  79. def assertRecentTimestamp(self, ts) -> None:
  80. # On some slow CIs it does actually take more than 5 seconds to go from
  81. # creating the tag to here.
  82. self.assertLess(time.time() - ts, 50)
  83. @skipIf(gpg is None, "gpg is not available")
  84. class PorcelainGpgTestCase(PorcelainTestCase):
  85. DEFAULT_KEY = """
  86. -----BEGIN PGP PRIVATE KEY BLOCK-----
  87. lQVYBGBjIyIBDADAwydvMPQqeEiK54FG1DHwT5sQejAaJOb+PsOhVa4fLcKsrO3F
  88. g5CxO+/9BHCXAr8xQAtp/gOhDN05fyK3MFyGlL9s+Cd8xf34S3R4rN/qbF0oZmaa
  89. FW0MuGnniq54HINs8KshadVn1Dhi/GYSJ588qNFRl/qxFTYAk+zaGsgX/QgFfy0f
  90. djWXJLypZXu9D6DlyJ0cPSzUlfBkI2Ytx6grzIquRjY0FbkjK3l+iGsQ+ebRMdcP
  91. Sqd5iTN9XuzIUVoBFAZBRjibKV3N2wxlnCbfLlzCyDp7rktzSThzjJ2pVDuLrMAx
  92. 6/L9hIhwmFwdtY4FBFGvMR0b0Ugh3kCsRWr8sgj9I7dUoLHid6ObYhJFhnD3GzRc
  93. U+xX1uy3iTCqJDsG334aQIhC5Giuxln4SUZna2MNbq65ksh38N1aM/t3+Dc/TKVB
  94. rb5KWicRPCQ4DIQkHMDCSPyj+dvRLCPzIaPvHD7IrCfHYHOWuvvPGCpwjo0As3iP
  95. IecoMeguPLVaqgcAEQEAAQAL/i5/pQaUd4G7LDydpbixPS6r9UrfPrU/y5zvBP/p
  96. DCynPDutJ1oq539pZvXQ2VwEJJy7x0UVKkjyMndJLNWly9wHC7o8jkHx/NalVP47
  97. LXR+GWbCdOOcYYbdAWcCNB3zOtzPnWhdAEagkc2G9xRQDIB0dLHLCIUpCbLP/CWM
  98. qlHnDsVMrVTWjgzcpsnyGgw8NeLYJtYGB8dsN+XgCCjo7a9LEvUBKNgdmWBbf14/
  99. iBw7PCugazFcH9QYfZwzhsi3nqRRagTXHbxFRG0LD9Ro9qCEutHYGP2PJ59Nj8+M
  100. zaVkJj/OxWxVOGvn2q16mQBCjKpbWfqXZVVl+G5DGOmiSTZqXy+3j6JCKdOMy6Qd
  101. JBHOHhFZXYmWYaaPzoc33T/C3QhMfY5sOtUDLJmV05Wi4dyBeNBEslYgUuTk/jXb
  102. 5ZAie25eDdrsoqkcnSs2ZguMF7AXhe6il2zVhUUMs/6UZgd6I7I4Is0HXT/pnxEp
  103. uiTRFu4v8E+u+5a8O3pffe5boQYA3TsIxceen20qY+kRaTOkURHMZLn/y6KLW8bZ
  104. rNJyXWS9hBAcbbSGhfOwYfzbDCM17yPQO3E2zo8lcGdRklUdIIaCxQwtu36N5dfx
  105. OLCCQc5LmYdl/EAm91iAhrr7dNntZ18MU09gdzUu+ONZwu4CP3cJT83+qYZULso8
  106. 4Fvd/X8IEfGZ7kM+ylrdqBwtlrn8yYXtom+ows2M2UuNR53B+BUOd73kVLTkTCjE
  107. JH63+nE8BqG7tDLCMws+23SAA3xxBgDfDrr0x7zCozQKVQEqBzQr9Uoo/c/ZjAfi
  108. syzNSrDz+g5gqJYtuL9XpPJVWf6V1GXVyJlSbxR9CjTkBxmlPxpvV25IsbVSsh0o
  109. aqkf2eWpbCL6Qb2E0jd1rvf8sGeTTohzYfiSVVsC2t9ngRO/CmetizwQBvRzLGMZ
  110. 4mtAPiy7ZEDc2dFrPp7zlKISYmJZUx/DJVuZWuOrVMpBP+bSgJXoMTlICxZUqUnE
  111. 2VKVStb/L+Tl8XCwIWdrZb9BaDnHqfcGAM2B4HNPxP88Yj1tEDly/vqeb3vVMhj+
  112. S1lunnLdgxp46YyuTMYAzj88eCGurRtzBsdxxlGAsioEnZGebEqAHQbieKq/DO6I
  113. MOMZHMSVBDqyyIx3assGlxSX8BSFW0lhKyT7i0XqnAgCJ9f/5oq0SbFGq+01VQb7
  114. jIx9PbcYJORxsE0JG/CXXPv27bRtQXsudkWGSYvC0NLOgk4z8+kQpQtyFh16lujq
  115. WRwMeriu0qNDjCa1/eHIKDovhAZ3GyO5/9m1tBlUZXN0IFVzZXIgPHRlc3RAdGVz
  116. dC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAFiEEjrR8
  117. MQ4fJK44PYMvfN2AClLmXiYFAmDcEZEACgkQfN2AClLmXibZzgv/ZfeTpTuqQE1W
  118. C1jT5KpQExnt0BizTX0U7BvSn8Fr6VXTyol6kYc3u71GLUuJyawCLtIzOXqOXJvz
  119. bjcZqymcMADuftKcfMy513FhbF6MhdVd6QoeBP6+7/xXOFJCi+QVYF7SQ2h7K1Qm
  120. +yXOiAMgSxhCZQGPBNJLlDUOd47nSIMANvlumFtmLY/1FD7RpG7WQWjeX1mnxNTw
  121. hUU+Yv7GuFc/JprXCIYqHbhWfvXyVtae2ZK4xuVi5eqwA2RfggOVM7drb+CgPhG0
  122. +9aEDDLOZqVi65wK7J73Puo3rFTbPQMljxw5s27rWqF+vB6hhVdJOPNomWy3naPi
  123. k5MW0mhsacASz1WYndpZz+XaQTq/wJF5HUyyeUWJ0vlOEdwx021PHcqSTyfNnkjD
  124. KncrE21t2sxWRsgGDETxIwkd2b2HNGAvveUD0ffFK/oJHGSXjAERFGc3wuiDj3mQ
  125. BvKm4wt4QF9ZMrCdhMAA6ax5kfEUqQR4ntmrJk/khp/mV7TILaI4nQVYBGBjIyIB
  126. DADghIo9wXnRxzfdDTvwnP8dHpLAIaPokgdpyLswqUCixJWiW2xcV6weUjEWwH6n
  127. eN/t1uZYVehbrotxVPla+MPvzhxp6/cmG+2lhzEBOp6zRwnL1wIB6HoKJfpREhyM
  128. c8rLR0zMso1L1bJTyydvnu07a7BWo3VWKjilb0rEZZUSD/2hidx5HxMOJSoidLWe
  129. d/PPuv6yht3NtA4UThlcfldm9G6PbqCdm1kMEKAkq0wVJvhPJ6gEFRNJimgygfUw
  130. MDFXEIhQtxjgdV5Uoz3O5452VLoRsDlgpi3E0WDGj7WXDaO5uSU0T5aJgVgHCP/f
  131. xZhHuQFk2YYIl5nCBpOZyWWI0IKmscTuEwzpkhICQDQFvcMZ5ibsl7wA2P7YTrQf
  132. FDMjjzuaK80GYPfxDFlyKUyLqFt8w/QzsZLDLX7+jxIEpbRAaMw/JsWqm5BMxxbS
  133. 3CIQiS5S3oSKDsNINelqWFfwvLhvlQra8gIxyNTlek25OdgG66BiiX+seH8A/ql+
  134. F+MAEQEAAQAL/1jrNSLjMt9pwo6qFKClVQZP2vf7+sH7v7LeHIDXr3EnYUnVYnOq
  135. B1FU5PspTp/+J9W25DB9CZLx7Gj8qeslFdiuLSOoIBB4RCToB3kAoeTH0DHqW/Gs
  136. hFTrmJkuDp9zpo/ek6SIXJx5rHAyR9KVw0fizQprH2f6PcgLbTWeM61dJuqowmg3
  137. 7eCOyIKv7VQvFqEhYokLD+JNmrvg+Htg0DXGvdjRjAwPf/NezEXpj67a6cHTp1/C
  138. hwp7pevG+3fTxaCJFesl5/TxxtnaBLE8m2uo/S6Hxgn9l0edonroe1QlTjEqGLy2
  139. 7qi2z5Rem+v6GWNDRgvAWur13v8FNdyduHlioG/NgRsU9mE2MYeFsfi3cfNpJQp/
  140. wC9PSCIXrb/45mkS8KyjZpCrIPB9RV/m0MREq01TPom7rstZc4A1pD0Ot7AtUYS3
  141. e95zLyEmeLziPJ9fV4fgPmEudDr1uItnmV0LOskKlpg5sc0hhdrwYoobfkKt2dx6
  142. DqfMlcM1ZkUbLQYA4jwfpFJG4HmYvjL2xCJxM0ycjvMbqFN+4UjgYWVlRfOrm1V4
  143. Op86FjbRbV6OOCNhznotAg7mul4xtzrrTkK8o3YLBeJseDgl4AWuzXtNa9hE0XpK
  144. 9gJoEHUuBOOsamVh2HpXESFyE5CclOV7JSh541TlZKfnqfZYCg4JSbp0UijkawCL
  145. 5bJJUiGGMD9rZUxIAKQO1DvUEzptS7Jl6S3y5sbIIhilp4KfYWbSk3PPu9CnZD5b
  146. LhEQp0elxnb/IL8PBgD+DpTeC8unkGKXUpbe9x0ISI6V1D6FmJq/FxNg7fMa3QCh
  147. fGiAyoTm80ZETynj+blRaDO3gY4lTLa3Opubof1EqK2QmwXmpyvXEZNYcQfQ2CCS
  148. GOWUCK8jEQamUPf1PWndZXJUmROI1WukhlL71V/ir6zQeVCv1wcwPwclJPnAe87u
  149. pEklnCYpvsEldwHUX9u0BWzoULIEsi+ddtHmT0KTeF/DHRy0W15jIHbjFqhqckj1
  150. /6fmr7l7kIi/kN4vWe0F/0Q8IXX+cVMgbl3aIuaGcvENLGcoAsAtPGx88SfRgmfu
  151. HK64Y7hx1m+Bo215rxJzZRjqHTBPp0BmCi+JKkaavIBrYRbsx20gveI4dzhLcUhB
  152. kiT4Q7oz0/VbGHS1CEf9KFeS/YOGj57s4yHauSVI0XdP9kBRTWmXvBkzsooB2cKH
  153. hwhUN7iiT1k717CiTNUT6Q/pcPFCyNuMoBBGQTU206JEgIjQvI3f8xMUMGmGVVQz
  154. 9/k716ycnhb2JZ/Q/AyQIeHJiQG2BBgBCAAgAhsMFiEEjrR8MQ4fJK44PYMvfN2A
  155. ClLmXiYFAmDcEa4ACgkQfN2AClLmXiZxxQv/XaMN0hPCygtrQMbCsTNb34JbvJzh
  156. hngPuUAfTbRHrR3YeATyQofNbL0DD3fvfzeFF8qESqvzCSZxS6dYsXPd4MCJTzlp
  157. zYBZ2X0sOrgDqZvqCZKN72RKgdk0KvthdzAxsIm2dfcQOxxowXMxhJEXZmsFpusx
  158. jKJxOcrfVRjXJnh9isY0NpCoqMQ+3k3wDJ3VGEHV7G+A+vFkWfbLJF5huQ96uaH9
  159. Uc+jUsREUH9G82ZBqpoioEN8Ith4VXpYnKdTMonK/+ZcyeraJZhXrvbjnEomKdzU
  160. 0pu4bt1HlLR3dcnpjN7b009MBf2xLgEfQk2nPZ4zzY+tDkxygtPllaB4dldFjBpT
  161. j7Q+t49sWMjmlJUbLlHfuJ7nUUK5+cGjBsWVObAEcyfemHWCTVFnEa2BJslGC08X
  162. rFcjRRcMEr9ct4551QFBHsv3O/Wp3/wqczYgE9itSnGT05w+4vLt4smG+dnEHjRJ
  163. brMb2upTHa+kjktjdO96/BgSnKYqmNmPB/qB
  164. =ivA/
  165. -----END PGP PRIVATE KEY BLOCK-----
  166. """
  167. DEFAULT_KEY_ID = "8EB47C310E1F24AE383D832F7CDD800A52E65E26"
  168. NON_DEFAULT_KEY = """
  169. -----BEGIN PGP PRIVATE KEY BLOCK-----
  170. lQVYBGBjI0ABDADGWBRp+t02emfzUlhrc1psqIhhecFm6Em0Kv33cfDpnfoMF1tK
  171. Yy/4eLYIR7FmpdbFPcDThFNHbXJzBi00L1mp0XQE2l50h/2bDAAgREdZ+NVo5a7/
  172. RSZjauNU1PxW6pnXMehEh1tyIQmV78jAukaakwaicrpIenMiFUN3fAKHnLuFffA6
  173. t0f3LqJvTDhUw/o2vPgw5e6UDQhA1C+KTv1KXVrhJNo88a3hZqCZ76z3drKR411Q
  174. zYgT4DUb8lfnbN+z2wfqT9oM5cegh2k86/mxAA3BYOeQrhmQo/7uhezcgbxtdGZr
  175. YlbuaNDTSBrn10ZoaxLPo2dJe2zWxgD6MpvsGU1w3tcRW508qo/+xoWp2/pDzmok
  176. +uhOh1NAj9zB05VWBz1r7oBgCOIKpkD/LD4VKq59etsZ/UnrYDwKdXWZp7uhshkU
  177. M7N35lUJcR76a852dlMdrgpmY18+BP7+o7M+5ElHTiqQbMuE1nHTg8RgVpdV+tUx
  178. dg6GWY/XHf5asm8AEQEAAQAL/A85epOp+GnymmEQfI3+5D178D//Lwu9n86vECB6
  179. xAHCqQtdjZnXpDp/1YUsL59P8nzgYRk7SoMskQDoQ/cB/XFuDOhEdMSgHaTVlnrj
  180. ktCCq6rqGnUosyolbb64vIfVaSqd/5SnCStpAsnaBoBYrAu4ZmV4xfjDQWwn0q5s
  181. u+r56mD0SkjPgbwk/b3qTVagVmf2OFzUgWwm1e/X+bA1oPag1NV8VS4hZPXswT4f
  182. qhiyqUFOgP6vUBcqehkjkIDIl/54xII7/P5tp3LIZawvIXqHKNTqYPCqaCqCj+SL
  183. vMYDIb6acjescfZoM71eAeHAANeFZzr/rwfBT+dEP6qKmPXNcvgE11X44ZCr04nT
  184. zOV/uDUifEvKT5qgtyJpSFEVr7EXubJPKoNNhoYqq9z1pYU7IedX5BloiVXKOKTY
  185. 0pk7JkLqf3g5fYtXh/wol1owemITJy5V5PgaqZvk491LkI6S+kWC7ANYUg+TDPIW
  186. afxW3E5N1CYV6XDAl0ZihbLcoQYAy0Ky/p/wayWKePyuPBLwx9O89GSONK2pQljZ
  187. yaAgxPQ5/i1vx6LIMg7k/722bXR9W3zOjWOin4eatPM3d2hkG96HFvnBqXSmXOPV
  188. 03Xqy1/B5Tj8E9naLKUHE/OBQEc363DgLLG9db5HfPlpAngeppYPdyWkhzXyzkgS
  189. PylaE5eW3zkdjEbYJ6RBTecTZEgBaMvJNPdWbn//frpP7kGvyiCg5Es+WjLInUZ6
  190. 0sdifcNTCewzLXK80v/y5mVOdJhPBgD5zs9cYdyiQJayqAuOr+He1eMHMVUbm9as
  191. qBmPrst398eBW9ZYF7eBfTSlUf6B+WnvyLKEGsUf/7IK0EWDlzoBuWzWiHjUAY1g
  192. m9eTV2MnvCCCefqCErWwfFo2nWOasAZA9sKD+ICIBY4tbtvSl4yfLBzTMwSvs9ZS
  193. K1ocPSYUnhm2miSWZ8RLZPH7roHQasNHpyq/AX7DahFf2S/bJ+46ZGZ8Pigr7hA+
  194. MjmpQ4qVdb5SaViPmZhAKO+PjuCHm+EF/2H0Y3Sl4eXgxZWoQVOUeXdWg9eMfYrj
  195. XDtUMIFppV/QxbeztZKvJdfk64vt/crvLsOp0hOky9cKwY89r4QaHfexU3qR+qDq
  196. UlMvR1rHk7dS5HZAtw0xKsFJNkuDxvBkMqv8Los8zp3nUl+U99dfZOArzNkW38wx
  197. FPa0ixkC9za2BkDrWEA8vTnxw0A2upIFegDUhwOByrSyfPPnG3tKGeqt3Izb/kDk
  198. Q9vmo+HgxBOguMIvlzbBfQZwtbd/gXzlvPqCtCJBbm90aGVyIFRlc3QgVXNlciA8
  199. dGVzdDJAdGVzdC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4B
  200. AheAFiEEapM5P1DF5qzT1vtFuTYhLttOFMAFAmDcEeEACgkQuTYhLttOFMDe0Qv/
  201. Qx/bzXztJ3BCc+CYAVDx7Kr37S68etwwLgcWzhG+CDeMB5F/QE+upKgxy2iaqQFR
  202. mxfOMgf/TIQkUfkbaASzK1LpnesYO85pk7XYjoN1bYEHiXTkeW+bgB6aJIxrRmO2
  203. SrWasdBC/DsI3Mrya8YMt/TiHC6VpRJVxCe5vv7/kZC4CXrgTBnZocXx/YXimbke
  204. poPMVdbvhYh6N0aGeS38jRKgyN10KXmhDTAQDwseVFavBWAjVfx3DEwjtK2Z2GbA
  205. aL8JvAwRtqiPFkDMIKPL4UwxtXFws8SpMt6juroUkNyf6+BxNWYqmwXHPy8zCJAb
  206. xkxIJMlEc+s7qQsP3fILOo8Xn+dVzJ5sa5AoARoXm1GMjsdqaKAzq99Dic/dHnaQ
  207. Civev1PQsdwlYW2C2wNXNeIrxMndbDMFfNuZ6BnGHWJ/wjcp/pFs4YkyyZN8JH7L
  208. hP2FO4Jgham3AuP13kC3Ivea7V6hR8QNcDZRwFPOMIX4tXwQv1T72+7DZGaA25O7
  209. nQVXBGBjI0ABDADJMBYIcG0Yil9YxFs7aYzNbd7alUAr89VbY8eIGPHP3INFPM1w
  210. lBQCu+4j6xdEbhMpppLBZ9A5TEylP4C6qLtPa+oLtPeuSw8gHDE10XE4lbgPs376
  211. rL60XdImSOHhiduACUefYjqpcmFH9Bim1CC+koArYrSQJQx1Jri+OpnTaL/8UID0
  212. KzD/kEgMVGlHIVj9oJmb4+j9pW8I/g0wDSnIaEKFMxqu6SIVJ1GWj+MUMvZigjLC
  213. sNCZd7PnbOC5VeU3SsXj6he74Jx0AmGMPWIHi9M0DjHO5d1cCbXTnud8xxM1bOh4
  214. 7aCTnMK5cVyIr+adihgJpVVhrndSM8aklBPRgtozrGNCgF2CkYU2P1blxfloNr/8
  215. UZpM83o+s1aObBszzRNLxnpNORqoLqjfPtLEPQnagxE+4EapCq0NZ/x6yO5VTwwp
  216. NljdFAEk40uGuKyn1QA3uNMHy5DlpLl+tU7t1KEovdZ+OVYsYKZhVzw0MTpKogk9
  217. JI7AN0q62ronPskAEQEAAQAL+O8BUSt1ZCVjPSIXIsrR+ZOSkszZwgJ1CWIoh0IH
  218. YD2vmcMHGIhFYgBdgerpvhptKhaw7GcXDScEnYkyh5s4GE2hxclik1tbj/x1gYCN
  219. 8BNoyeDdPFxQG73qN12D99QYEctpOsz9xPLIDwmL0j1ehAfhwqHIAPm9Ca+i8JYM
  220. x/F+35S/jnKDXRI+NVlwbiEyXKXxxIqNlpy9i8sDBGexO5H5Sg0zSN/B1duLekGD
  221. biDw6gLc6bCgnS+0JOUpU07Z2fccMOY9ncjKGD2uIb/ePPUaek92GCQyq0eorCIV
  222. brcQsRc5sSsNtnRKQTQtxioROeDg7kf2oWySeHTswlXW/219ihrSXgteHJd+rPm7
  223. DYLEeGLRny8bRKv8rQdAtApHaJE4dAATXeY4RYo4NlXHYaztGYtU6kiM/3zCfWAe
  224. 9Nn+Wh9jMTZrjefUCagS5r6ZqAh7veNo/vgIGaCLh0a1Ypa0Yk9KFrn3LYEM3zgk
  225. 3m3bn+7qgy5cUYXoJ3DGJJEhBgDPonpW0WElqLs5ZMem1ha85SC38F0IkAaSuzuz
  226. v3eORiKWuyJGF32Q2XHa1RHQs1JtUKd8rxFer3b8Oq71zLz6JtVc9dmRudvgcJYX
  227. 0PC11F6WGjZFSSp39dajFp0A5DKUs39F3w7J1yuDM56TDIN810ywufGAHARY1pZb
  228. UJAy/dTqjFnCbNjpAakor3hVzqxcmUG+7Y2X9c2AGncT1MqAQC3M8JZcuZvkK8A9
  229. cMk8B914ryYE7VsZMdMhyTwHmykGAPgNLLa3RDETeGeGCKWI+ZPOoU0ib5JtJZ1d
  230. P3tNwfZKuZBZXKW9gqYqyBa/qhMip84SP30pr/TvulcdAFC759HK8sQZyJ6Vw24P
  231. c+5ssRxrQUEw1rvJPWhmQCmCOZHBMQl5T6eaTOpR5u3aUKTMlxPKhK9eC1dCSTnI
  232. /nyL8An3VKnLy+K/LI42YGphBVLLJmBewuTVDIJviWRdntiG8dElyEJMOywUltk3
  233. 2CEmqgsD9tPO8rXZjnMrMn3gfsiaoQYA6/6/e2utkHr7gAoWBgrBBdqVHsvqh5Ro
  234. 2DjLAOpZItO/EdCJfDAmbTYOa04535sBDP2tcH/vipPOPpbr1Y9Y/mNsKCulNxed
  235. yqAmEkKOcerLUP5UHju0AB6VBjHJFdU2mqT+UjPyBk7WeKXgFomyoYMv3KpNOFWR
  236. xi0Xji4kKHbttA6Hy3UcGPr9acyUAlDYeKmxbSUYIPhw32bbGrX9+F5YriTufRsG
  237. 3jftQVo9zqdcQSD/5pUTMn3EYbEcohYB2YWJAbYEGAEIACACGwwWIQRqkzk/UMXm
  238. rNPW+0W5NiEu204UwAUCYNwR6wAKCRC5NiEu204UwOPnC/92PgB1c3h9FBXH1maz
  239. g29fndHIHH65VLgqMiQ7HAMojwRlT5Xnj5tdkCBmszRkv5vMvdJRa3ZY8Ed/Inqr
  240. hxBFNzpjqX4oj/RYIQLKXWWfkTKYVLJFZFPCSo00jesw2gieu3Ke/Yy4gwhtNodA
  241. v+s6QNMvffTW/K3XNrWDB0E7/LXbdidzhm+MBu8ov2tuC3tp9liLICiE1jv/2xT4
  242. CNSO6yphmk1/1zEYHS/mN9qJ2csBmte2cdmGyOcuVEHk3pyINNMDOamaURBJGRwF
  243. XB5V7gTKUFU4jCp3chywKrBHJHxGGDUmPBmZtDtfWAOgL32drK7/KUyzZL/WO7Fj
  244. akOI0hRDFOcqTYWL20H7+hAiX3oHMP7eou3L5C7wJ9+JMcACklN/WMjG9a536DFJ
  245. 4UgZ6HyKPP+wy837Hbe8b25kNMBwFgiaLR0lcgzxj7NyQWjVCMOEN+M55tRCjvL6
  246. ya6JVZCRbMXfdCy8lVPgtNQ6VlHaj8Wvnn2FLbWWO2n2r3s=
  247. =9zU5
  248. -----END PGP PRIVATE KEY BLOCK-----
  249. """
  250. NON_DEFAULT_KEY_ID = "6A93393F50C5E6ACD3D6FB45B936212EDB4E14C0"
  251. def setUp(self) -> None:
  252. super().setUp()
  253. self.gpg_dir = os.path.join(self.test_dir, "gpg")
  254. os.mkdir(self.gpg_dir, mode=0o700)
  255. # Ignore errors when deleting GNUPGHOME, because of race conditions
  256. # (e.g. the gpg-agent socket having been deleted). See
  257. # https://github.com/jelmer/dulwich/issues/1000
  258. self.addCleanup(shutil.rmtree, self.gpg_dir, ignore_errors=True)
  259. self.overrideEnv("GNUPGHOME", self.gpg_dir)
  260. def import_default_key(self) -> None:
  261. subprocess.run(
  262. ["gpg", "--import"],
  263. stdout=subprocess.DEVNULL,
  264. stderr=subprocess.DEVNULL,
  265. input=PorcelainGpgTestCase.DEFAULT_KEY,
  266. text=True,
  267. )
  268. def import_non_default_key(self) -> None:
  269. subprocess.run(
  270. ["gpg", "--import"],
  271. stdout=subprocess.DEVNULL,
  272. stderr=subprocess.DEVNULL,
  273. input=PorcelainGpgTestCase.NON_DEFAULT_KEY,
  274. text=True,
  275. )
  276. class ArchiveTests(PorcelainTestCase):
  277. """Tests for the archive command."""
  278. def test_simple(self) -> None:
  279. _c1, _c2, c3 = build_commit_graph(
  280. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  281. )
  282. self.repo.refs[b"refs/heads/master"] = c3.id
  283. out = BytesIO()
  284. err = BytesIO()
  285. porcelain.archive(
  286. self.repo.path, b"refs/heads/master", outstream=out, errstream=err
  287. )
  288. self.assertEqual(b"", err.getvalue())
  289. tf = tarfile.TarFile(fileobj=out)
  290. self.addCleanup(tf.close)
  291. self.assertEqual([], tf.getnames())
  292. class UpdateServerInfoTests(PorcelainTestCase):
  293. def test_simple(self) -> None:
  294. _c1, _c2, c3 = build_commit_graph(
  295. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  296. )
  297. self.repo.refs[b"refs/heads/foo"] = c3.id
  298. porcelain.update_server_info(self.repo.path)
  299. self.assertTrue(
  300. os.path.exists(os.path.join(self.repo.controldir(), "info", "refs"))
  301. )
  302. class CommitTests(PorcelainTestCase):
  303. def test_custom_author(self) -> None:
  304. _c1, _c2, c3 = build_commit_graph(
  305. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  306. )
  307. self.repo.refs[b"refs/heads/foo"] = c3.id
  308. sha = porcelain.commit(
  309. self.repo.path,
  310. message=b"Some message",
  311. author=b"Joe <joe@example.com>",
  312. committer=b"Bob <bob@example.com>",
  313. )
  314. self.assertIsInstance(sha, bytes)
  315. self.assertEqual(len(sha), 40)
  316. def test_unicode(self) -> None:
  317. _c1, _c2, c3 = build_commit_graph(
  318. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  319. )
  320. self.repo.refs[b"refs/heads/foo"] = c3.id
  321. sha = porcelain.commit(
  322. self.repo.path,
  323. message="Some message",
  324. author="Joe <joe@example.com>",
  325. committer="Bob <bob@example.com>",
  326. )
  327. self.assertIsInstance(sha, bytes)
  328. self.assertEqual(len(sha), 40)
  329. def test_no_verify(self) -> None:
  330. if os.name != "posix":
  331. self.skipTest("shell hook tests requires POSIX shell")
  332. self.assertTrue(os.path.exists("/bin/sh"))
  333. hooks_dir = os.path.join(self.repo.controldir(), "hooks")
  334. os.makedirs(hooks_dir, exist_ok=True)
  335. self.addCleanup(shutil.rmtree, hooks_dir)
  336. _c1, _c2, _c3 = build_commit_graph(
  337. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  338. )
  339. hook_fail = "#!/bin/sh\nexit 1"
  340. # hooks are executed in pre-commit, commit-msg order
  341. # test commit-msg failure first, then pre-commit failure, then
  342. # no_verify to skip both hooks
  343. commit_msg = os.path.join(hooks_dir, "commit-msg")
  344. with open(commit_msg, "w") as f:
  345. f.write(hook_fail)
  346. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  347. with self.assertRaises(CommitError):
  348. porcelain.commit(
  349. self.repo.path,
  350. message="Some message",
  351. author="Joe <joe@example.com>",
  352. committer="Bob <bob@example.com>",
  353. )
  354. pre_commit = os.path.join(hooks_dir, "pre-commit")
  355. with open(pre_commit, "w") as f:
  356. f.write(hook_fail)
  357. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  358. with self.assertRaises(CommitError):
  359. porcelain.commit(
  360. self.repo.path,
  361. message="Some message",
  362. author="Joe <joe@example.com>",
  363. committer="Bob <bob@example.com>",
  364. )
  365. sha = porcelain.commit(
  366. self.repo.path,
  367. message="Some message",
  368. author="Joe <joe@example.com>",
  369. committer="Bob <bob@example.com>",
  370. no_verify=True,
  371. )
  372. self.assertIsInstance(sha, bytes)
  373. self.assertEqual(len(sha), 40)
  374. def test_timezone(self) -> None:
  375. _c1, _c2, c3 = build_commit_graph(
  376. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  377. )
  378. self.repo.refs[b"refs/heads/foo"] = c3.id
  379. sha = porcelain.commit(
  380. self.repo.path,
  381. message="Some message",
  382. author="Joe <joe@example.com>",
  383. author_timezone=18000,
  384. committer="Bob <bob@example.com>",
  385. commit_timezone=18000,
  386. )
  387. self.assertIsInstance(sha, bytes)
  388. self.assertEqual(len(sha), 40)
  389. commit = self.repo.get_object(sha)
  390. assert isinstance(commit, Commit)
  391. self.assertEqual(commit._author_timezone, 18000)
  392. self.assertEqual(commit._commit_timezone, 18000)
  393. self.overrideEnv("GIT_AUTHOR_DATE", "1995-11-20T19:12:08-0501")
  394. self.overrideEnv("GIT_COMMITTER_DATE", "1995-11-20T19:12:08-0501")
  395. sha = porcelain.commit(
  396. self.repo.path,
  397. message="Some message",
  398. author="Joe <joe@example.com>",
  399. committer="Bob <bob@example.com>",
  400. )
  401. self.assertIsInstance(sha, bytes)
  402. self.assertEqual(len(sha), 40)
  403. commit = self.repo.get_object(sha)
  404. assert isinstance(commit, Commit)
  405. self.assertEqual(commit._author_timezone, -18060)
  406. self.assertEqual(commit._commit_timezone, -18060)
  407. self.overrideEnv("GIT_AUTHOR_DATE", None)
  408. self.overrideEnv("GIT_COMMITTER_DATE", None)
  409. local_timezone = time.localtime().tm_gmtoff
  410. sha = porcelain.commit(
  411. self.repo.path,
  412. message="Some message",
  413. author="Joe <joe@example.com>",
  414. committer="Bob <bob@example.com>",
  415. )
  416. self.assertIsInstance(sha, bytes)
  417. self.assertEqual(len(sha), 40)
  418. commit = self.repo.get_object(sha)
  419. assert isinstance(commit, Commit)
  420. self.assertEqual(commit._author_timezone, local_timezone)
  421. self.assertEqual(commit._commit_timezone, local_timezone)
  422. def test_commit_all(self) -> None:
  423. # Create initial commit
  424. filename = os.path.join(self.repo.path, "test.txt")
  425. with open(filename, "wb") as f:
  426. f.write(b"initial content")
  427. porcelain.add(self.repo.path, paths=["test.txt"])
  428. initial_sha = porcelain.commit(self.repo.path, message=b"Initial commit")
  429. # Modify the file without staging
  430. with open(filename, "wb") as f:
  431. f.write(b"modified content")
  432. # Create an untracked file
  433. untracked_file = os.path.join(self.repo.path, "untracked.txt")
  434. with open(untracked_file, "wb") as f:
  435. f.write(b"untracked content")
  436. # Commit with all=True should stage modified files but not untracked
  437. sha = porcelain.commit(self.repo.path, message=b"Modified commit", all=True)
  438. self.assertIsInstance(sha, bytes)
  439. self.assertEqual(len(sha), 40)
  440. self.assertNotEqual(sha, initial_sha)
  441. # Verify the commit contains the modification
  442. commit = self.repo.get_object(sha)
  443. assert isinstance(commit, Commit)
  444. tree = self.repo.get_object(commit.tree)
  445. # The modified file should be in the commit
  446. self.assertIn(b"test.txt", tree)
  447. # The untracked file should not be in the commit
  448. self.assertNotIn(b"untracked.txt", tree)
  449. def test_commit_all_no_changes(self) -> None:
  450. # Create initial commit
  451. filename = os.path.join(self.repo.path, "test.txt")
  452. with open(filename, "wb") as f:
  453. f.write(b"initial content")
  454. porcelain.add(self.repo.path, paths=["test.txt"])
  455. initial_sha = porcelain.commit(self.repo.path, message=b"Initial commit")
  456. # Try to commit with all=True when there are no unstaged changes
  457. sha = porcelain.commit(self.repo.path, message=b"No changes commit", all=True)
  458. self.assertIsInstance(sha, bytes)
  459. self.assertEqual(len(sha), 40)
  460. self.assertNotEqual(sha, initial_sha)
  461. def test_commit_all_multiple_files(self) -> None:
  462. # Create initial commit with multiple files
  463. file1 = os.path.join(self.repo.path, "file1.txt")
  464. file2 = os.path.join(self.repo.path, "file2.txt")
  465. with open(file1, "wb") as f:
  466. f.write(b"content1")
  467. with open(file2, "wb") as f:
  468. f.write(b"content2")
  469. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  470. initial_sha = porcelain.commit(self.repo.path, message=b"Initial commit")
  471. # Modify both files
  472. with open(file1, "wb") as f:
  473. f.write(b"modified content1")
  474. with open(file2, "wb") as f:
  475. f.write(b"modified content2")
  476. # Commit with all=True should stage both modified files
  477. sha = porcelain.commit(self.repo.path, message=b"Modified both files", all=True)
  478. self.assertIsInstance(sha, bytes)
  479. self.assertEqual(len(sha), 40)
  480. self.assertNotEqual(sha, initial_sha)
  481. # Verify both modifications are in the commit
  482. commit = self.repo.get_object(sha)
  483. assert isinstance(commit, Commit)
  484. tree = self.repo.get_object(commit.tree)
  485. self.assertIn(b"file1.txt", tree)
  486. self.assertIn(b"file2.txt", tree)
  487. def test_commit_amend_message(self) -> None:
  488. # Create initial commit
  489. filename = os.path.join(self.repo.path, "test.txt")
  490. with open(filename, "wb") as f:
  491. f.write(b"initial content")
  492. porcelain.add(self.repo.path, paths=["test.txt"])
  493. original_sha = porcelain.commit(self.repo.path, message=b"Original commit")
  494. # Amend with new message
  495. amended_sha = porcelain.commit(
  496. self.repo.path, message=b"Amended commit", amend=True
  497. )
  498. self.assertIsInstance(amended_sha, bytes)
  499. self.assertEqual(len(amended_sha), 40)
  500. self.assertNotEqual(amended_sha, original_sha)
  501. # Check that the amended commit has the new message
  502. amended_commit = self.repo.get_object(amended_sha)
  503. assert isinstance(amended_commit, Commit)
  504. self.assertEqual(amended_commit.message, b"Amended commit")
  505. # Check that the amended commit uses the original commit's parents
  506. original_commit = self.repo.get_object(original_sha)
  507. assert isinstance(original_commit, Commit)
  508. # Since this was the first commit, it should have no parents,
  509. # and the amended commit should also have no parents
  510. self.assertEqual(amended_commit.parents, original_commit.parents)
  511. def test_commit_amend_no_message(self) -> None:
  512. # Create initial commit
  513. filename = os.path.join(self.repo.path, "test.txt")
  514. with open(filename, "wb") as f:
  515. f.write(b"initial content")
  516. porcelain.add(self.repo.path, paths=["test.txt"])
  517. original_sha = porcelain.commit(self.repo.path, message=b"Original commit")
  518. # Modify file and stage it
  519. with open(filename, "wb") as f:
  520. f.write(b"modified content")
  521. porcelain.add(self.repo.path, paths=["test.txt"])
  522. # Amend without providing message (should reuse original message)
  523. amended_sha = porcelain.commit(self.repo.path, amend=True)
  524. self.assertIsInstance(amended_sha, bytes)
  525. self.assertEqual(len(amended_sha), 40)
  526. self.assertNotEqual(amended_sha, original_sha)
  527. # Check that the amended commit has the original message
  528. amended_commit = self.repo.get_object(amended_sha)
  529. assert isinstance(amended_commit, Commit)
  530. self.assertEqual(amended_commit.message, b"Original commit")
  531. def test_commit_amend_no_existing_commit(self) -> None:
  532. # Try to amend when there's no existing commit
  533. with self.assertRaises(ValueError) as cm:
  534. porcelain.commit(self.repo.path, message=b"Should fail", amend=True)
  535. self.assertIn("Cannot amend: no existing commit found", str(cm.exception))
  536. @skipIf(
  537. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  538. "gpgme not easily available or supported on Windows and PyPy",
  539. )
  540. class CommitSignTests(PorcelainGpgTestCase):
  541. def test_default_key(self) -> None:
  542. _c1, _c2, c3 = build_commit_graph(
  543. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  544. )
  545. self.repo.refs[b"HEAD"] = c3.id
  546. cfg = self.repo.get_config()
  547. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  548. self.import_default_key()
  549. sha = porcelain.commit(
  550. self.repo.path,
  551. message="Some message",
  552. author="Joe <joe@example.com>",
  553. committer="Bob <bob@example.com>",
  554. sign=True,
  555. )
  556. self.assertIsInstance(sha, bytes)
  557. self.assertEqual(len(sha), 40)
  558. commit = self.repo.get_object(sha)
  559. assert isinstance(commit, Commit)
  560. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  561. commit.verify()
  562. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  563. self.import_non_default_key()
  564. self.assertRaises(
  565. gpg.errors.MissingSignatures,
  566. commit.verify,
  567. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  568. )
  569. assert isinstance(commit, Commit)
  570. commit.committer = b"Alice <alice@example.com>"
  571. self.assertRaises(
  572. gpg.errors.BadSignatures,
  573. commit.verify,
  574. )
  575. def test_non_default_key(self) -> None:
  576. _c1, _c2, c3 = build_commit_graph(
  577. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  578. )
  579. self.repo.refs[b"HEAD"] = c3.id
  580. cfg = self.repo.get_config()
  581. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  582. self.import_non_default_key()
  583. sha = porcelain.commit(
  584. self.repo.path,
  585. message="Some message",
  586. author="Joe <joe@example.com>",
  587. committer="Bob <bob@example.com>",
  588. signoff=PorcelainGpgTestCase.NON_DEFAULT_KEY_ID,
  589. )
  590. self.assertIsInstance(sha, bytes)
  591. self.assertEqual(len(sha), 40)
  592. commit = self.repo.get_object(sha)
  593. assert isinstance(commit, Commit)
  594. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  595. commit.verify()
  596. def test_sign_uses_config_signingkey(self) -> None:
  597. """Test that sign=True uses user.signingKey from config."""
  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 in config
  603. cfg = self.repo.get_config()
  604. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  605. cfg.write_to_path()
  606. self.import_default_key()
  607. # Create commit with sign=True (should use signingKey from config)
  608. sha = porcelain.commit(
  609. self.repo.path,
  610. message="Signed with configured key",
  611. author="Joe <joe@example.com>",
  612. committer="Bob <bob@example.com>",
  613. sign=True, # This should read user.signingKey from config
  614. )
  615. self.assertIsInstance(sha, bytes)
  616. self.assertEqual(len(sha), 40)
  617. commit = self.repo.get_object(sha)
  618. assert isinstance(commit, Commit)
  619. # Verify the commit is signed with the configured key
  620. commit.verify()
  621. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  622. def test_commit_gpg_sign_config_enabled(self) -> None:
  623. """Test that commit.gpgSign=true automatically signs commits."""
  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 user.signingKey and commit.gpgSign in config
  629. cfg = self.repo.get_config()
  630. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  631. cfg.set(("commit",), "gpgSign", True)
  632. cfg.write_to_path()
  633. self.import_default_key()
  634. # Create commit without explicit signoff parameter (should auto-sign due to config)
  635. sha = porcelain.commit(
  636. self.repo.path,
  637. message="Auto-signed commit",
  638. author="Joe <joe@example.com>",
  639. committer="Bob <bob@example.com>",
  640. # No signoff parameter - should use commit.gpgSign config
  641. )
  642. self.assertIsInstance(sha, bytes)
  643. self.assertEqual(len(sha), 40)
  644. commit = self.repo.get_object(sha)
  645. assert isinstance(commit, Commit)
  646. # Verify the commit is signed due to config
  647. commit.verify()
  648. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  649. def test_commit_gpg_sign_config_disabled(self) -> None:
  650. """Test that commit.gpgSign=false does not sign commits."""
  651. _c1, _c2, c3 = build_commit_graph(
  652. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  653. )
  654. self.repo.refs[b"HEAD"] = c3.id
  655. # Set up user.signingKey and commit.gpgSign=false in config
  656. cfg = self.repo.get_config()
  657. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  658. cfg.set(("commit",), "gpgSign", False)
  659. cfg.write_to_path()
  660. self.import_default_key()
  661. # Create commit without explicit signoff parameter (should not sign)
  662. sha = porcelain.commit(
  663. self.repo.path,
  664. message="Unsigned commit",
  665. author="Joe <joe@example.com>",
  666. committer="Bob <bob@example.com>",
  667. # No signoff parameter - should use commit.gpgSign=false config
  668. )
  669. self.assertIsInstance(sha, bytes)
  670. self.assertEqual(len(sha), 40)
  671. commit = self.repo.get_object(sha)
  672. assert isinstance(commit, Commit)
  673. # Verify the commit is not signed
  674. self.assertIsNone(commit._gpgsig)
  675. def test_commit_gpg_sign_config_no_signing_key(self) -> None:
  676. """Test that commit.gpgSign=true works without user.signingKey (uses default)."""
  677. _c1, _c2, c3 = build_commit_graph(
  678. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  679. )
  680. self.repo.refs[b"HEAD"] = c3.id
  681. # Set up commit.gpgSign but no user.signingKey
  682. cfg = self.repo.get_config()
  683. cfg.set(("commit",), "gpgSign", True)
  684. cfg.write_to_path()
  685. self.import_default_key()
  686. # Create commit without explicit signoff parameter (should auto-sign with default key)
  687. sha = porcelain.commit(
  688. self.repo.path,
  689. message="Default signed commit",
  690. author="Joe <joe@example.com>",
  691. committer="Bob <bob@example.com>",
  692. # No signoff parameter - should use commit.gpgSign config with default key
  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 signed with default key
  699. commit.verify()
  700. def test_explicit_signoff_overrides_config(self) -> None:
  701. """Test that explicit signoff parameter overrides commit.gpgSign config."""
  702. _c1, _c2, c3 = build_commit_graph(
  703. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  704. )
  705. self.repo.refs[b"HEAD"] = c3.id
  706. # Set up commit.gpgSign=false but explicitly pass sign=True
  707. cfg = self.repo.get_config()
  708. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  709. cfg.set(("commit",), "gpgSign", False)
  710. cfg.write_to_path()
  711. self.import_default_key()
  712. # Create commit with explicit sign=True (should override config)
  713. sha = porcelain.commit(
  714. self.repo.path,
  715. message="Explicitly signed commit",
  716. author="Joe <joe@example.com>",
  717. committer="Bob <bob@example.com>",
  718. sign=True, # This should override commit.gpgSign=false
  719. )
  720. self.assertIsInstance(sha, bytes)
  721. self.assertEqual(len(sha), 40)
  722. commit = self.repo.get_object(sha)
  723. assert isinstance(commit, Commit)
  724. # Verify the commit is signed despite config=false
  725. commit.verify()
  726. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  727. def test_explicit_false_disables_signing(self) -> None:
  728. """Test that explicit signoff=False disables signing even with config=true."""
  729. _c1, _c2, c3 = build_commit_graph(
  730. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  731. )
  732. self.repo.refs[b"HEAD"] = c3.id
  733. # Set up commit.gpgSign=true but explicitly pass sign=False
  734. cfg = self.repo.get_config()
  735. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  736. cfg.set(("commit",), "gpgSign", True)
  737. cfg.write_to_path()
  738. self.import_default_key()
  739. # Create commit with explicit sign=False (should disable signing)
  740. sha = porcelain.commit(
  741. self.repo.path,
  742. message="Explicitly unsigned commit",
  743. author="Joe <joe@example.com>",
  744. committer="Bob <bob@example.com>",
  745. sign=False, # This should override commit.gpgSign=true
  746. )
  747. self.assertIsInstance(sha, bytes)
  748. self.assertEqual(len(sha), 40)
  749. commit = self.repo.get_object(sha)
  750. assert isinstance(commit, Commit)
  751. # Verify the commit is NOT signed despite config=true
  752. self.assertIsNone(commit._gpgsig)
  753. @skipIf(
  754. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  755. "gpgme not easily available or supported on Windows and PyPy",
  756. )
  757. class VerifyCommitTests(PorcelainGpgTestCase):
  758. def test_verify_commit_valid_signature(self) -> None:
  759. """Test verifying a commit with a valid GPG signature."""
  760. _c1, _c2, c3 = build_commit_graph(
  761. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  762. )
  763. self.repo.refs[b"HEAD"] = c3.id
  764. cfg = self.repo.get_config()
  765. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  766. cfg.write_to_path()
  767. self.import_default_key()
  768. # Create a signed commit
  769. sha = porcelain.commit(
  770. self.repo.path,
  771. message="Signed commit",
  772. author="Joe <joe@example.com>",
  773. committer="Bob <bob@example.com>",
  774. sign=True,
  775. )
  776. # Verify should not raise
  777. porcelain.verify_commit(self.repo.path, sha)
  778. porcelain.verify_commit(
  779. self.repo.path, sha, keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID]
  780. )
  781. def test_verify_commit_with_wrong_key(self) -> None:
  782. """Test that verifying with wrong keyid raises MissingSignatures."""
  783. _c1, _c2, c3 = build_commit_graph(
  784. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  785. )
  786. self.repo.refs[b"HEAD"] = c3.id
  787. cfg = self.repo.get_config()
  788. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  789. cfg.write_to_path()
  790. self.import_default_key()
  791. sha = porcelain.commit(
  792. self.repo.path,
  793. message="Signed commit",
  794. author="Joe <joe@example.com>",
  795. committer="Bob <bob@example.com>",
  796. sign=True,
  797. )
  798. self.import_non_default_key()
  799. self.assertRaises(
  800. gpg.errors.MissingSignatures,
  801. porcelain.verify_commit,
  802. self.repo.path,
  803. sha,
  804. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  805. )
  806. def test_verify_commit_unsigned(self) -> None:
  807. """Test that verifying an unsigned commit succeeds (no signature to verify)."""
  808. _c1, _c2, c3 = build_commit_graph(
  809. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  810. )
  811. self.repo.refs[b"HEAD"] = c3.id
  812. sha = porcelain.commit(
  813. self.repo.path,
  814. message="Unsigned commit",
  815. author="Joe <joe@example.com>",
  816. committer="Bob <bob@example.com>",
  817. sign=False,
  818. )
  819. # Verify should not raise for unsigned commits
  820. porcelain.verify_commit(self.repo.path, sha)
  821. @skipIf(
  822. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  823. "gpgme not easily available or supported on Windows and PyPy",
  824. )
  825. class VerifyTagTests(PorcelainGpgTestCase):
  826. def test_verify_tag_valid_signature(self) -> None:
  827. """Test verifying a tag with a valid GPG signature."""
  828. _c1, _c2, c3 = build_commit_graph(
  829. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  830. )
  831. self.repo.refs[b"HEAD"] = c3.id
  832. cfg = self.repo.get_config()
  833. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  834. cfg.write_to_path()
  835. self.import_default_key()
  836. # Create a signed tag
  837. porcelain.tag_create(
  838. self.repo.path,
  839. b"signed-tag",
  840. b"Tagger <tagger@example.com>",
  841. b"Signed tag message",
  842. annotated=True,
  843. sign=True,
  844. )
  845. # Verify should not raise
  846. porcelain.verify_tag(self.repo.path, b"signed-tag")
  847. porcelain.verify_tag(
  848. self.repo.path, b"signed-tag", keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID]
  849. )
  850. def test_verify_tag_with_wrong_key(self) -> None:
  851. """Test that verifying with wrong keyid raises MissingSignatures."""
  852. _c1, _c2, c3 = build_commit_graph(
  853. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  854. )
  855. self.repo.refs[b"HEAD"] = c3.id
  856. cfg = self.repo.get_config()
  857. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  858. cfg.write_to_path()
  859. self.import_default_key()
  860. porcelain.tag_create(
  861. self.repo.path,
  862. b"signed-tag",
  863. b"Tagger <tagger@example.com>",
  864. b"Signed tag message",
  865. annotated=True,
  866. sign=True,
  867. )
  868. self.import_non_default_key()
  869. self.assertRaises(
  870. gpg.errors.MissingSignatures,
  871. porcelain.verify_tag,
  872. self.repo.path,
  873. b"signed-tag",
  874. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  875. )
  876. def test_verify_tag_unsigned(self) -> None:
  877. """Test that verifying an unsigned tag succeeds (no signature to verify)."""
  878. _c1, _c2, c3 = build_commit_graph(
  879. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  880. )
  881. self.repo.refs[b"HEAD"] = c3.id
  882. porcelain.tag_create(
  883. self.repo.path,
  884. b"unsigned-tag",
  885. b"Tagger <tagger@example.com>",
  886. b"Unsigned tag message",
  887. annotated=True,
  888. sign=False,
  889. )
  890. # Verify should not raise for unsigned tags
  891. porcelain.verify_tag(self.repo.path, b"unsigned-tag")
  892. class TimezoneTests(PorcelainTestCase):
  893. def put_envs(self, value) -> None:
  894. self.overrideEnv("GIT_AUTHOR_DATE", value)
  895. self.overrideEnv("GIT_COMMITTER_DATE", value)
  896. def fallback(self, value) -> None:
  897. self.put_envs(value)
  898. self.assertRaises(porcelain.TimezoneFormatError, porcelain.get_user_timezones)
  899. def test_internal_format(self) -> None:
  900. self.put_envs("0 +0500")
  901. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  902. def test_rfc_2822(self) -> None:
  903. self.put_envs("Mon, 20 Nov 1995 19:12:08 -0500")
  904. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  905. self.put_envs("Mon, 20 Nov 1995 19:12:08")
  906. self.assertTupleEqual((0, 0), porcelain.get_user_timezones())
  907. def test_iso8601(self) -> None:
  908. self.put_envs("1995-11-20T19:12:08-0501")
  909. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  910. self.put_envs("1995-11-20T19:12:08+0501")
  911. self.assertTupleEqual((18060, 18060), porcelain.get_user_timezones())
  912. self.put_envs("1995-11-20T19:12:08-05:01")
  913. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  914. self.put_envs("1995-11-20 19:12:08-05")
  915. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  916. # https://github.com/git/git/blob/96b2d4fa927c5055adc5b1d08f10a5d7352e2989/t/t6300-for-each-ref.sh#L128
  917. self.put_envs("2006-07-03 17:18:44 +0200")
  918. self.assertTupleEqual((7200, 7200), porcelain.get_user_timezones())
  919. def test_missing_or_malformed(self) -> None:
  920. # TODO: add more here
  921. self.fallback("0 + 0500")
  922. self.fallback("a +0500")
  923. self.fallback("1995-11-20T19:12:08")
  924. self.fallback("1995-11-20T19:12:08-05:")
  925. self.fallback("1995.11.20")
  926. self.fallback("11/20/1995")
  927. self.fallback("20.11.1995")
  928. def test_different_envs(self) -> None:
  929. self.overrideEnv("GIT_AUTHOR_DATE", "0 +0500")
  930. self.overrideEnv("GIT_COMMITTER_DATE", "0 +0501")
  931. self.assertTupleEqual((18000, 18060), porcelain.get_user_timezones())
  932. def test_no_envs(self) -> None:
  933. local_timezone = time.localtime().tm_gmtoff
  934. self.put_envs("0 +0500")
  935. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  936. self.overrideEnv("GIT_COMMITTER_DATE", None)
  937. self.assertTupleEqual((18000, local_timezone), porcelain.get_user_timezones())
  938. self.put_envs("0 +0500")
  939. self.overrideEnv("GIT_AUTHOR_DATE", None)
  940. self.assertTupleEqual((local_timezone, 18000), porcelain.get_user_timezones())
  941. self.put_envs("0 +0500")
  942. self.overrideEnv("GIT_AUTHOR_DATE", None)
  943. self.overrideEnv("GIT_COMMITTER_DATE", None)
  944. self.assertTupleEqual(
  945. (local_timezone, local_timezone), porcelain.get_user_timezones()
  946. )
  947. class CleanTests(PorcelainTestCase):
  948. def put_files(self, tracked, ignored, untracked, empty_dirs) -> None:
  949. """Put the described files in the wd."""
  950. all_files = tracked | ignored | untracked
  951. for file_path in all_files:
  952. abs_path = os.path.join(self.repo.path, file_path)
  953. # File may need to be written in a dir that doesn't exist yet, so
  954. # create the parent dir(s) as necessary
  955. parent_dir = os.path.dirname(abs_path)
  956. try:
  957. os.makedirs(parent_dir)
  958. except FileExistsError:
  959. pass
  960. with open(abs_path, "w") as f:
  961. f.write("")
  962. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  963. f.writelines(ignored)
  964. for dir_path in empty_dirs:
  965. os.mkdir(os.path.join(self.repo.path, "empty_dir"))
  966. files_to_add = [os.path.join(self.repo.path, t) for t in tracked]
  967. porcelain.add(repo=self.repo.path, paths=files_to_add)
  968. porcelain.commit(repo=self.repo.path, message="init commit")
  969. def assert_wd(self, expected_paths) -> None:
  970. """Assert paths of files and dirs in wd are same as expected_paths."""
  971. control_dir_rel = os.path.relpath(self.repo._controldir, self.repo.path)
  972. # normalize paths to simplify comparison across platforms
  973. found_paths = {
  974. os.path.normpath(p)
  975. for p in flat_walk_dir(self.repo.path)
  976. if not p.split(os.sep)[0] == control_dir_rel
  977. }
  978. norm_expected_paths = {os.path.normpath(p) for p in expected_paths}
  979. self.assertEqual(found_paths, norm_expected_paths)
  980. def test_from_root(self) -> None:
  981. self.put_files(
  982. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  983. ignored={"ignored_file"},
  984. untracked={
  985. "untracked_file",
  986. "tracked_dir/untracked_dir/untracked_file",
  987. "untracked_dir/untracked_dir/untracked_file",
  988. },
  989. empty_dirs={"empty_dir"},
  990. )
  991. porcelain.clean(repo=self.repo.path, target_dir=self.repo.path)
  992. self.assert_wd(
  993. {
  994. "tracked_file",
  995. "tracked_dir/tracked_file",
  996. ".gitignore",
  997. "ignored_file",
  998. "tracked_dir",
  999. }
  1000. )
  1001. def test_from_subdir(self) -> None:
  1002. self.put_files(
  1003. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  1004. ignored={"ignored_file"},
  1005. untracked={
  1006. "untracked_file",
  1007. "tracked_dir/untracked_dir/untracked_file",
  1008. "untracked_dir/untracked_dir/untracked_file",
  1009. },
  1010. empty_dirs={"empty_dir"},
  1011. )
  1012. porcelain.clean(
  1013. repo=self.repo,
  1014. target_dir=os.path.join(self.repo.path, "untracked_dir"),
  1015. )
  1016. self.assert_wd(
  1017. {
  1018. "tracked_file",
  1019. "tracked_dir/tracked_file",
  1020. ".gitignore",
  1021. "ignored_file",
  1022. "untracked_file",
  1023. "tracked_dir/untracked_dir/untracked_file",
  1024. "empty_dir",
  1025. "untracked_dir",
  1026. "tracked_dir",
  1027. "tracked_dir/untracked_dir",
  1028. }
  1029. )
  1030. class CloneTests(PorcelainTestCase):
  1031. def test_simple_local(self) -> None:
  1032. f1_1 = make_object(Blob, data=b"f1")
  1033. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1034. trees = {
  1035. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1036. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1037. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1038. }
  1039. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1040. self.repo.refs[b"refs/heads/master"] = c3.id
  1041. self.repo.refs[b"refs/tags/foo"] = c3.id
  1042. target_path = tempfile.mkdtemp()
  1043. errstream = BytesIO()
  1044. self.addCleanup(shutil.rmtree, target_path)
  1045. r = porcelain.clone(
  1046. self.repo.path, target_path, checkout=False, errstream=errstream
  1047. )
  1048. self.addCleanup(r.close)
  1049. self.assertEqual(r.path, target_path)
  1050. target_repo = Repo(target_path)
  1051. self.addCleanup(target_repo.close)
  1052. self.assertEqual(0, len(target_repo.open_index()))
  1053. self.assertEqual(c3.id, target_repo.refs[b"refs/tags/foo"])
  1054. self.assertNotIn(b"f1", os.listdir(target_path))
  1055. self.assertNotIn(b"f2", os.listdir(target_path))
  1056. c = r.get_config()
  1057. encoded_path = self.repo.path
  1058. if not isinstance(encoded_path, bytes):
  1059. encoded_path_bytes = encoded_path.encode("utf-8")
  1060. else:
  1061. encoded_path_bytes = encoded_path
  1062. self.assertEqual(encoded_path_bytes, c.get((b"remote", b"origin"), b"url"))
  1063. self.assertEqual(
  1064. b"+refs/heads/*:refs/remotes/origin/*",
  1065. c.get((b"remote", b"origin"), b"fetch"),
  1066. )
  1067. def test_simple_local_with_checkout(self) -> None:
  1068. f1_1 = make_object(Blob, data=b"f1")
  1069. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1070. trees = {
  1071. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1072. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1073. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1074. }
  1075. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1076. self.repo.refs[b"refs/heads/master"] = c3.id
  1077. target_path = tempfile.mkdtemp()
  1078. errstream = BytesIO()
  1079. self.addCleanup(shutil.rmtree, target_path)
  1080. with porcelain.clone(
  1081. self.repo.path, target_path, checkout=True, errstream=errstream
  1082. ) as r:
  1083. self.assertEqual(r.path, target_path)
  1084. with Repo(target_path) as r:
  1085. self.assertEqual(r.head(), c3.id)
  1086. self.assertIn("f1", os.listdir(target_path))
  1087. self.assertIn("f2", os.listdir(target_path))
  1088. def test_bare_local_with_checkout(self) -> None:
  1089. f1_1 = make_object(Blob, data=b"f1")
  1090. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1091. trees = {
  1092. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1093. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1094. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1095. }
  1096. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1097. self.repo.refs[b"refs/heads/master"] = c3.id
  1098. target_path = tempfile.mkdtemp()
  1099. errstream = BytesIO()
  1100. self.addCleanup(shutil.rmtree, target_path)
  1101. with porcelain.clone(
  1102. self.repo.path, target_path, bare=True, errstream=errstream
  1103. ) as r:
  1104. self.assertEqual(r.path, target_path)
  1105. with Repo(target_path) as r:
  1106. r.head()
  1107. self.assertRaises(NoIndexPresent, r.open_index)
  1108. self.assertNotIn(b"f1", os.listdir(target_path))
  1109. self.assertNotIn(b"f2", os.listdir(target_path))
  1110. def test_no_checkout_with_bare(self) -> None:
  1111. f1_1 = make_object(Blob, data=b"f1")
  1112. commit_spec = [[1]]
  1113. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1114. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1115. self.repo.refs[b"refs/heads/master"] = c1.id
  1116. self.repo.refs[b"HEAD"] = c1.id
  1117. target_path = tempfile.mkdtemp()
  1118. errstream = BytesIO()
  1119. self.addCleanup(shutil.rmtree, target_path)
  1120. self.assertRaises(
  1121. porcelain.Error,
  1122. porcelain.clone,
  1123. self.repo.path,
  1124. target_path,
  1125. checkout=True,
  1126. bare=True,
  1127. errstream=errstream,
  1128. )
  1129. def test_no_head_no_checkout(self) -> None:
  1130. f1_1 = make_object(Blob, data=b"f1")
  1131. commit_spec = [[1]]
  1132. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1133. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1134. self.repo.refs[b"refs/heads/master"] = c1.id
  1135. target_path = tempfile.mkdtemp()
  1136. self.addCleanup(shutil.rmtree, target_path)
  1137. errstream = BytesIO()
  1138. r = porcelain.clone(
  1139. self.repo.path, target_path, checkout=True, errstream=errstream
  1140. )
  1141. r.close()
  1142. def test_no_head_no_checkout_outstream_errstream_autofallback(self) -> None:
  1143. f1_1 = make_object(Blob, data=b"f1")
  1144. commit_spec = [[1]]
  1145. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1146. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1147. self.repo.refs[b"refs/heads/master"] = c1.id
  1148. target_path = tempfile.mkdtemp()
  1149. self.addCleanup(shutil.rmtree, target_path)
  1150. errstream = porcelain.NoneStream()
  1151. r = porcelain.clone(
  1152. self.repo.path, target_path, checkout=True, errstream=errstream
  1153. )
  1154. r.close()
  1155. def test_source_broken(self) -> None:
  1156. with tempfile.TemporaryDirectory() as parent:
  1157. target_path = os.path.join(parent, "target")
  1158. self.assertRaises(
  1159. Exception, porcelain.clone, "/nonexistent/repo", target_path
  1160. )
  1161. self.assertFalse(os.path.exists(target_path))
  1162. def test_fetch_symref(self) -> None:
  1163. f1_1 = make_object(Blob, data=b"f1")
  1164. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1165. [c1] = build_commit_graph(self.repo.object_store, [[1]], trees)
  1166. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/else")
  1167. self.repo.refs[b"refs/heads/else"] = c1.id
  1168. target_path = tempfile.mkdtemp()
  1169. errstream = BytesIO()
  1170. self.addCleanup(shutil.rmtree, target_path)
  1171. r = porcelain.clone(
  1172. self.repo.path, target_path, checkout=False, errstream=errstream
  1173. )
  1174. self.addCleanup(r.close)
  1175. self.assertEqual(r.path, target_path)
  1176. target_repo = Repo(target_path)
  1177. self.addCleanup(target_repo.close)
  1178. self.assertEqual(0, len(target_repo.open_index()))
  1179. self.assertEqual(c1.id, target_repo.refs[b"refs/heads/else"])
  1180. self.assertEqual(c1.id, target_repo.refs[b"HEAD"])
  1181. self.assertEqual(
  1182. {
  1183. b"HEAD": b"refs/heads/else",
  1184. b"refs/remotes/origin/HEAD": b"refs/remotes/origin/else",
  1185. },
  1186. target_repo.refs.get_symrefs(),
  1187. )
  1188. def test_detached_head(self) -> None:
  1189. f1_1 = make_object(Blob, data=b"f1")
  1190. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1191. trees = {
  1192. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1193. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1194. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1195. }
  1196. _c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1197. self.repo.refs[b"refs/heads/master"] = c2.id
  1198. self.repo.refs.remove_if_equals(b"HEAD", None)
  1199. self.repo.refs[b"HEAD"] = c3.id
  1200. target_path = tempfile.mkdtemp()
  1201. self.addCleanup(shutil.rmtree, target_path)
  1202. errstream = porcelain.NoneStream()
  1203. with porcelain.clone(
  1204. self.repo.path, target_path, checkout=True, errstream=errstream
  1205. ) as r:
  1206. self.assertEqual(c3.id, r.refs[b"HEAD"])
  1207. def test_clone_pathlib(self) -> None:
  1208. from pathlib import Path
  1209. f1_1 = make_object(Blob, data=b"f1")
  1210. commit_spec = [[1]]
  1211. trees = {1: [(b"f1", f1_1)]}
  1212. c1 = build_commit_graph(self.repo.object_store, commit_spec, trees)[0]
  1213. self.repo.refs[b"refs/heads/master"] = c1.id
  1214. target_dir = tempfile.mkdtemp()
  1215. self.addCleanup(shutil.rmtree, target_dir)
  1216. target_path = Path(target_dir) / "clone_repo"
  1217. errstream = BytesIO()
  1218. r = porcelain.clone(
  1219. self.repo.path, target_path, checkout=False, errstream=errstream
  1220. )
  1221. self.addCleanup(r.close)
  1222. self.assertEqual(r.path, str(target_path))
  1223. self.assertTrue(os.path.exists(str(target_path)))
  1224. def test_clone_with_recurse_submodules(self) -> None:
  1225. # Create a submodule repository
  1226. sub_repo_path = tempfile.mkdtemp()
  1227. self.addCleanup(shutil.rmtree, sub_repo_path)
  1228. sub_repo = Repo.init(sub_repo_path)
  1229. self.addCleanup(sub_repo.close)
  1230. # Add a file to the submodule repo
  1231. sub_file = os.path.join(sub_repo_path, "subfile.txt")
  1232. with open(sub_file, "w") as f:
  1233. f.write("submodule content")
  1234. porcelain.add(sub_repo, paths=[sub_file])
  1235. sub_commit = porcelain.commit(
  1236. sub_repo,
  1237. message=b"Initial submodule commit",
  1238. author=b"Test Author <test@example.com>",
  1239. committer=b"Test Committer <test@example.com>",
  1240. )
  1241. # Create main repository with submodule
  1242. main_file = os.path.join(self.repo.path, "main.txt")
  1243. with open(main_file, "w") as f:
  1244. f.write("main content")
  1245. porcelain.add(self.repo, paths=[main_file])
  1246. porcelain.submodule_add(self.repo, sub_repo_path, "sub")
  1247. # Manually add the submodule to the index since submodule_add doesn't do it
  1248. # when the repository is local (to maintain backward compatibility)
  1249. from dulwich.index import IndexEntry
  1250. from dulwich.objects import S_IFGITLINK
  1251. index = self.repo.open_index()
  1252. index[b"sub"] = IndexEntry(
  1253. ctime=0,
  1254. mtime=0,
  1255. dev=0,
  1256. ino=0,
  1257. mode=S_IFGITLINK,
  1258. uid=0,
  1259. gid=0,
  1260. size=0,
  1261. sha=sub_commit,
  1262. flags=0,
  1263. )
  1264. index.write()
  1265. porcelain.add(self.repo, paths=[".gitmodules"])
  1266. porcelain.commit(
  1267. self.repo,
  1268. message=b"Add submodule",
  1269. author=b"Test Author <test@example.com>",
  1270. committer=b"Test Committer <test@example.com>",
  1271. )
  1272. # Clone with recurse_submodules
  1273. target_path = tempfile.mkdtemp()
  1274. self.addCleanup(shutil.rmtree, target_path)
  1275. cloned = porcelain.clone(
  1276. self.repo.path,
  1277. target_path,
  1278. recurse_submodules=True,
  1279. )
  1280. self.addCleanup(cloned.close)
  1281. # Check main file exists
  1282. cloned_main = os.path.join(target_path, "main.txt")
  1283. self.assertTrue(os.path.exists(cloned_main))
  1284. with open(cloned_main) as f:
  1285. self.assertEqual(f.read(), "main content")
  1286. # Check submodule file exists
  1287. cloned_sub_file = os.path.join(target_path, "sub", "subfile.txt")
  1288. self.assertTrue(os.path.exists(cloned_sub_file))
  1289. with open(cloned_sub_file) as f:
  1290. self.assertEqual(f.read(), "submodule content")
  1291. def test_clone_with_refspec_kwarg(self) -> None:
  1292. """Test that clone accepts refspec as a kwarg without TypeError.
  1293. This reproduces a bug where passing refspec as a kwarg to clone()
  1294. would cause a TypeError because it was being passed to
  1295. get_transport_and_path() which doesn't accept that parameter.
  1296. """
  1297. f1_1 = make_object(Blob, data=b"f1")
  1298. commit_spec = [[1]]
  1299. trees = {1: [(b"f1", f1_1)]}
  1300. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1301. self.repo.refs[b"refs/heads/master"] = c1.id
  1302. target_path = tempfile.mkdtemp()
  1303. errstream = BytesIO()
  1304. self.addCleanup(shutil.rmtree, target_path)
  1305. # This should not raise TypeError
  1306. r = porcelain.clone(
  1307. self.repo.path,
  1308. target_path,
  1309. checkout=False,
  1310. errstream=errstream,
  1311. refspec="refs/heads/master",
  1312. )
  1313. self.addCleanup(r.close)
  1314. self.assertEqual(r.path, target_path)
  1315. class InitTests(TestCase):
  1316. def test_non_bare(self) -> None:
  1317. repo_dir = tempfile.mkdtemp()
  1318. self.addCleanup(shutil.rmtree, repo_dir)
  1319. porcelain.init(repo_dir)
  1320. def test_bare(self) -> None:
  1321. repo_dir = tempfile.mkdtemp()
  1322. self.addCleanup(shutil.rmtree, repo_dir)
  1323. porcelain.init(repo_dir, bare=True)
  1324. def test_init_pathlib(self) -> None:
  1325. from pathlib import Path
  1326. repo_dir = tempfile.mkdtemp()
  1327. self.addCleanup(shutil.rmtree, repo_dir)
  1328. repo_path = Path(repo_dir)
  1329. # Test non-bare repo with pathlib
  1330. repo = porcelain.init(repo_path)
  1331. self.assertTrue(os.path.exists(os.path.join(repo_dir, ".git")))
  1332. repo.close()
  1333. def test_init_bare_pathlib(self) -> None:
  1334. from pathlib import Path
  1335. repo_dir = tempfile.mkdtemp()
  1336. self.addCleanup(shutil.rmtree, repo_dir)
  1337. repo_path = Path(repo_dir)
  1338. # Test bare repo with pathlib
  1339. repo = porcelain.init(repo_path, bare=True)
  1340. self.assertTrue(os.path.exists(os.path.join(repo_dir, "refs")))
  1341. repo.close()
  1342. class AddTests(PorcelainTestCase):
  1343. def test_add_default_paths(self) -> None:
  1344. # create a file for initial commit
  1345. fullpath = os.path.join(self.repo.path, "blah")
  1346. with open(fullpath, "w") as f:
  1347. f.write("\n")
  1348. porcelain.add(repo=self.repo.path, paths=[fullpath])
  1349. porcelain.commit(
  1350. repo=self.repo.path,
  1351. message=b"test",
  1352. author=b"test <email>",
  1353. committer=b"test <email>",
  1354. )
  1355. # Add a second test file and a file in a directory
  1356. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1357. f.write("\n")
  1358. os.mkdir(os.path.join(self.repo.path, "adir"))
  1359. with open(os.path.join(self.repo.path, "adir", "afile"), "w") as f:
  1360. f.write("\n")
  1361. cwd = os.getcwd()
  1362. self.addCleanup(os.chdir, cwd)
  1363. os.chdir(self.repo.path)
  1364. self.assertEqual({"foo", "blah", "adir", ".git"}, set(os.listdir(".")))
  1365. added, ignored = porcelain.add(self.repo.path)
  1366. # Normalize paths to use forward slashes for comparison
  1367. added_normalized = [path.replace(os.sep, "/") for path in added]
  1368. self.assertEqual(
  1369. (added_normalized, ignored),
  1370. (["foo", "adir/afile"], set()),
  1371. )
  1372. # Check that foo was added and nothing in .git was modified
  1373. index = self.repo.open_index()
  1374. self.assertEqual(sorted(index), [b"adir/afile", b"blah", b"foo"])
  1375. def test_add_default_paths_subdir(self) -> None:
  1376. os.mkdir(os.path.join(self.repo.path, "foo"))
  1377. with open(os.path.join(self.repo.path, "blah"), "w") as f:
  1378. f.write("\n")
  1379. with open(os.path.join(self.repo.path, "foo", "blie"), "w") as f:
  1380. f.write("\n")
  1381. cwd = os.getcwd()
  1382. self.addCleanup(os.chdir, cwd)
  1383. os.chdir(os.path.join(self.repo.path, "foo"))
  1384. porcelain.add(repo=self.repo.path)
  1385. porcelain.commit(
  1386. repo=self.repo.path,
  1387. message=b"test",
  1388. author=b"test <email>",
  1389. committer=b"test <email>",
  1390. )
  1391. index = self.repo.open_index()
  1392. # After fix: add() with no paths should behave like git add -A (add everything)
  1393. self.assertEqual(sorted(index), [b"blah", b"foo/blie"])
  1394. def test_add_file(self) -> None:
  1395. fullpath = os.path.join(self.repo.path, "foo")
  1396. with open(fullpath, "w") as f:
  1397. f.write("BAR")
  1398. porcelain.add(self.repo.path, paths=[fullpath])
  1399. self.assertIn(b"foo", self.repo.open_index())
  1400. def test_add_ignored(self) -> None:
  1401. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1402. f.write("foo\nsubdir/")
  1403. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1404. f.write("BAR")
  1405. with open(os.path.join(self.repo.path, "bar"), "w") as f:
  1406. f.write("BAR")
  1407. os.mkdir(os.path.join(self.repo.path, "subdir"))
  1408. with open(os.path.join(self.repo.path, "subdir", "baz"), "w") as f:
  1409. f.write("BAZ")
  1410. (added, ignored) = porcelain.add(
  1411. self.repo.path,
  1412. paths=[
  1413. os.path.join(self.repo.path, "foo"),
  1414. os.path.join(self.repo.path, "bar"),
  1415. os.path.join(self.repo.path, "subdir"),
  1416. ],
  1417. )
  1418. self.assertIn(b"bar", self.repo.open_index())
  1419. self.assertEqual({"bar"}, set(added))
  1420. self.assertEqual({"foo", "subdir/"}, ignored)
  1421. def test_add_from_ignored_directory(self) -> None:
  1422. # Test for issue #550 - adding files when cwd is in ignored directory
  1423. # Create .gitignore that ignores build/
  1424. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1425. f.write("build/\n")
  1426. # Create ignored directory
  1427. build_dir = os.path.join(self.repo.path, "build")
  1428. os.mkdir(build_dir)
  1429. # Create a file in the repo (not in ignored directory)
  1430. src_file = os.path.join(self.repo.path, "source.py")
  1431. with open(src_file, "w") as f:
  1432. f.write("print('hello')\n")
  1433. # Save current directory and change to ignored directory
  1434. original_cwd = os.getcwd()
  1435. try:
  1436. os.chdir(build_dir)
  1437. # Add file using absolute path from within ignored directory
  1438. (added, _ignored) = porcelain.add(self.repo.path, paths=[src_file])
  1439. self.assertIn(b"source.py", self.repo.open_index())
  1440. self.assertEqual({"source.py"}, set(added))
  1441. finally:
  1442. os.chdir(original_cwd)
  1443. def test_add_file_absolute_path(self) -> None:
  1444. # Absolute paths are (not yet) supported
  1445. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1446. f.write("BAR")
  1447. porcelain.add(self.repo, paths=[os.path.join(self.repo.path, "foo")])
  1448. self.assertIn(b"foo", self.repo.open_index())
  1449. def test_add_not_in_repo(self) -> None:
  1450. with open(os.path.join(self.test_dir, "foo"), "w") as f:
  1451. f.write("BAR")
  1452. self.assertRaises(
  1453. ValueError,
  1454. porcelain.add,
  1455. self.repo,
  1456. paths=[os.path.join(self.test_dir, "foo")],
  1457. )
  1458. self.assertRaises(
  1459. (ValueError, FileNotFoundError),
  1460. porcelain.add,
  1461. self.repo,
  1462. paths=["../foo"],
  1463. )
  1464. self.assertEqual([], list(self.repo.open_index()))
  1465. def test_add_file_clrf_conversion(self) -> None:
  1466. from dulwich.index import IndexEntry
  1467. # Set the right configuration to the repo
  1468. c = self.repo.get_config()
  1469. c.set("core", "autocrlf", "input")
  1470. c.write_to_path()
  1471. # Add a file with CRLF line-ending
  1472. fullpath = os.path.join(self.repo.path, "foo")
  1473. with open(fullpath, "wb") as f:
  1474. f.write(b"line1\r\nline2")
  1475. porcelain.add(self.repo.path, paths=[fullpath])
  1476. # The line-endings should have been converted to LF
  1477. index = self.repo.open_index()
  1478. self.assertIn(b"foo", index)
  1479. entry = index[b"foo"]
  1480. assert isinstance(entry, IndexEntry)
  1481. blob = self.repo[entry.sha]
  1482. self.assertEqual(blob.data, b"line1\nline2")
  1483. def test_add_symlink_outside_repo(self) -> None:
  1484. """Test adding a symlink that points outside the repository."""
  1485. # Create a symlink pointing outside the repository
  1486. symlink_path = os.path.join(self.repo.path, "symlink_to_nowhere")
  1487. os.symlink("/nonexistent/path", symlink_path)
  1488. # Adding the symlink should succeed (matching Git's behavior)
  1489. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1490. # Should successfully add the symlink
  1491. self.assertIn("symlink_to_nowhere", added)
  1492. self.assertEqual(len(ignored), 0)
  1493. # Verify symlink is actually staged
  1494. index = self.repo.open_index()
  1495. self.assertIn(b"symlink_to_nowhere", index)
  1496. def test_add_symlink_to_file_inside_repo(self) -> None:
  1497. """Test adding a symlink that points to a file inside the repository."""
  1498. # Create a regular file
  1499. target_file = os.path.join(self.repo.path, "target.txt")
  1500. with open(target_file, "w") as f:
  1501. f.write("target content")
  1502. # Create a symlink to the file
  1503. symlink_path = os.path.join(self.repo.path, "link_to_target")
  1504. os.symlink("target.txt", symlink_path)
  1505. # Add both the target and the symlink
  1506. added, ignored = porcelain.add(
  1507. self.repo.path, paths=[target_file, symlink_path]
  1508. )
  1509. # Both should be added successfully
  1510. self.assertIn("target.txt", added)
  1511. self.assertIn("link_to_target", added)
  1512. self.assertEqual(len(ignored), 0)
  1513. # Verify both are in the index
  1514. index = self.repo.open_index()
  1515. self.assertIn(b"target.txt", index)
  1516. self.assertIn(b"link_to_target", index)
  1517. def test_add_symlink_to_directory_inside_repo(self) -> None:
  1518. """Test adding a symlink that points to a directory inside the repository."""
  1519. # Create a directory with some files
  1520. target_dir = os.path.join(self.repo.path, "target_dir")
  1521. os.mkdir(target_dir)
  1522. with open(os.path.join(target_dir, "file1.txt"), "w") as f:
  1523. f.write("content1")
  1524. with open(os.path.join(target_dir, "file2.txt"), "w") as f:
  1525. f.write("content2")
  1526. # Create a symlink to the directory
  1527. symlink_path = os.path.join(self.repo.path, "link_to_dir")
  1528. os.symlink("target_dir", symlink_path)
  1529. # Add the symlink
  1530. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1531. # When adding a symlink to a directory, it follows the symlink and adds contents
  1532. self.assertEqual(len(added), 2)
  1533. self.assertIn("link_to_dir/file1.txt", added)
  1534. self.assertIn("link_to_dir/file2.txt", added)
  1535. self.assertEqual(len(ignored), 0)
  1536. # Verify files are added through the symlink path
  1537. index = self.repo.open_index()
  1538. self.assertIn(b"link_to_dir/file1.txt", index)
  1539. self.assertIn(b"link_to_dir/file2.txt", index)
  1540. # The original target directory files are not added
  1541. self.assertNotIn(b"target_dir/file1.txt", index)
  1542. self.assertNotIn(b"target_dir/file2.txt", index)
  1543. def test_add_symlink_chain(self) -> None:
  1544. """Test adding a chain of symlinks (symlink to symlink)."""
  1545. # Create a regular file
  1546. target_file = os.path.join(self.repo.path, "original.txt")
  1547. with open(target_file, "w") as f:
  1548. f.write("original content")
  1549. # Create first symlink
  1550. first_link = os.path.join(self.repo.path, "link1")
  1551. os.symlink("original.txt", first_link)
  1552. # Create second symlink pointing to first
  1553. second_link = os.path.join(self.repo.path, "link2")
  1554. os.symlink("link1", second_link)
  1555. # Add all files
  1556. added, _ignored = porcelain.add(
  1557. self.repo.path, paths=[target_file, first_link, second_link]
  1558. )
  1559. # All should be added
  1560. self.assertEqual(len(added), 3)
  1561. self.assertIn("original.txt", added)
  1562. self.assertIn("link1", added)
  1563. self.assertIn("link2", added)
  1564. # Verify all are in the index
  1565. index = self.repo.open_index()
  1566. self.assertIn(b"original.txt", index)
  1567. self.assertIn(b"link1", index)
  1568. self.assertIn(b"link2", index)
  1569. def test_add_broken_symlink(self) -> None:
  1570. """Test adding a broken symlink (points to non-existent target)."""
  1571. # Create a symlink to a non-existent file
  1572. broken_link = os.path.join(self.repo.path, "broken_link")
  1573. os.symlink("does_not_exist.txt", broken_link)
  1574. # Add the broken symlink
  1575. added, ignored = porcelain.add(self.repo.path, paths=[broken_link])
  1576. # Should be added successfully (Git tracks the symlink, not its target)
  1577. self.assertIn("broken_link", added)
  1578. self.assertEqual(len(ignored), 0)
  1579. # Verify it's in the index
  1580. index = self.repo.open_index()
  1581. self.assertIn(b"broken_link", index)
  1582. def test_add_symlink_relative_outside_repo(self) -> None:
  1583. """Test adding a symlink that uses '..' to point outside the repository."""
  1584. # Create a file outside the repo
  1585. outside_file = os.path.join(self.test_dir, "outside.txt")
  1586. with open(outside_file, "w") as f:
  1587. f.write("outside content")
  1588. # Create a symlink using relative path to go outside
  1589. symlink_path = os.path.join(self.repo.path, "link_outside")
  1590. os.symlink("../outside.txt", symlink_path)
  1591. # Add the symlink
  1592. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1593. # Should be added successfully
  1594. self.assertIn("link_outside", added)
  1595. self.assertEqual(len(ignored), 0)
  1596. # Verify it's in the index
  1597. index = self.repo.open_index()
  1598. self.assertIn(b"link_outside", index)
  1599. def test_add_symlink_absolute_to_system(self) -> None:
  1600. """Test adding a symlink with absolute path to system directory."""
  1601. # Create a symlink to a system directory
  1602. symlink_path = os.path.join(self.repo.path, "link_to_tmp")
  1603. if os.name == "nt":
  1604. # On Windows, use a system directory like TEMP
  1605. symlink_target = os.environ["TEMP"]
  1606. else:
  1607. # On Unix-like systems, use /tmp
  1608. symlink_target = os.environ.get("TMPDIR", "/tmp")
  1609. os.symlink(symlink_target, symlink_path)
  1610. # Adding a symlink to a directory outside the repo should raise ValueError
  1611. with self.assertRaises(ValueError) as cm:
  1612. porcelain.add(self.repo.path, paths=[symlink_path])
  1613. # Check that the error indicates the path is outside the repository
  1614. self.assertIn("is not in the subpath of", str(cm.exception))
  1615. def test_add_file_through_symlink(self) -> None:
  1616. """Test adding a file through a symlinked directory."""
  1617. # Create a directory with a file
  1618. real_dir = os.path.join(self.repo.path, "real_dir")
  1619. os.mkdir(real_dir)
  1620. real_file = os.path.join(real_dir, "file.txt")
  1621. with open(real_file, "w") as f:
  1622. f.write("content")
  1623. # Create a symlink to the directory
  1624. link_dir = os.path.join(self.repo.path, "link_dir")
  1625. os.symlink("real_dir", link_dir)
  1626. # Try to add the file through the symlink path
  1627. symlink_file_path = os.path.join(link_dir, "file.txt")
  1628. # This should add the real file, not create a new entry
  1629. added, _ignored = porcelain.add(self.repo.path, paths=[symlink_file_path])
  1630. # The real file should be added
  1631. self.assertIn("real_dir/file.txt", added)
  1632. self.assertEqual(len(added), 1)
  1633. # Verify correct path in index
  1634. index = self.repo.open_index()
  1635. self.assertIn(b"real_dir/file.txt", index)
  1636. # Should not create a separate entry for the symlink path
  1637. self.assertNotIn(b"link_dir/file.txt", index)
  1638. def test_add_repo_path(self) -> None:
  1639. """Test adding the repository path itself should add all untracked files."""
  1640. # Create some untracked files
  1641. with open(os.path.join(self.repo.path, "file1.txt"), "w") as f:
  1642. f.write("content1")
  1643. with open(os.path.join(self.repo.path, "file2.txt"), "w") as f:
  1644. f.write("content2")
  1645. # Add the repository path itself
  1646. added, _ignored = porcelain.add(self.repo.path, paths=[self.repo.path])
  1647. # Should add all untracked files, not stage './'
  1648. self.assertIn("file1.txt", added)
  1649. self.assertIn("file2.txt", added)
  1650. self.assertNotIn("./", added)
  1651. # Verify files are actually staged
  1652. index = self.repo.open_index()
  1653. self.assertIn(b"file1.txt", index)
  1654. self.assertIn(b"file2.txt", index)
  1655. def test_add_directory_contents(self) -> None:
  1656. """Test adding a directory adds all files within it."""
  1657. # Create a subdirectory with multiple files
  1658. subdir = os.path.join(self.repo.path, "subdir")
  1659. os.mkdir(subdir)
  1660. with open(os.path.join(subdir, "file1.txt"), "w") as f:
  1661. f.write("content1")
  1662. with open(os.path.join(subdir, "file2.txt"), "w") as f:
  1663. f.write("content2")
  1664. with open(os.path.join(subdir, "file3.txt"), "w") as f:
  1665. f.write("content3")
  1666. # Add the directory
  1667. added, _ignored = porcelain.add(self.repo.path, paths=["subdir"])
  1668. # Should add all files in the directory
  1669. self.assertEqual(len(added), 3)
  1670. # Normalize paths to use forward slashes for comparison
  1671. added_normalized = [path.replace(os.sep, "/") for path in added]
  1672. self.assertIn("subdir/file1.txt", added_normalized)
  1673. self.assertIn("subdir/file2.txt", added_normalized)
  1674. self.assertIn("subdir/file3.txt", added_normalized)
  1675. # Verify files are actually staged
  1676. index = self.repo.open_index()
  1677. self.assertIn(b"subdir/file1.txt", index)
  1678. self.assertIn(b"subdir/file2.txt", index)
  1679. self.assertIn(b"subdir/file3.txt", index)
  1680. def test_add_nested_directories(self) -> None:
  1681. """Test adding a directory with nested subdirectories."""
  1682. # Create nested directory structure
  1683. dir1 = os.path.join(self.repo.path, "dir1")
  1684. dir2 = os.path.join(dir1, "dir2")
  1685. dir3 = os.path.join(dir2, "dir3")
  1686. os.makedirs(dir3)
  1687. # Add files at each level
  1688. with open(os.path.join(dir1, "file1.txt"), "w") as f:
  1689. f.write("level1")
  1690. with open(os.path.join(dir2, "file2.txt"), "w") as f:
  1691. f.write("level2")
  1692. with open(os.path.join(dir3, "file3.txt"), "w") as f:
  1693. f.write("level3")
  1694. # Add the top-level directory
  1695. added, _ignored = porcelain.add(self.repo.path, paths=["dir1"])
  1696. # Should add all files recursively
  1697. self.assertEqual(len(added), 3)
  1698. # Normalize paths to use forward slashes for comparison
  1699. added_normalized = [path.replace(os.sep, "/") for path in added]
  1700. self.assertIn("dir1/file1.txt", added_normalized)
  1701. self.assertIn("dir1/dir2/file2.txt", added_normalized)
  1702. self.assertIn("dir1/dir2/dir3/file3.txt", added_normalized)
  1703. # Verify files are actually staged
  1704. index = self.repo.open_index()
  1705. self.assertIn(b"dir1/file1.txt", index)
  1706. self.assertIn(b"dir1/dir2/file2.txt", index)
  1707. self.assertIn(b"dir1/dir2/dir3/file3.txt", index)
  1708. def test_add_directory_with_tracked_files(self) -> None:
  1709. """Test adding a directory with some files already tracked."""
  1710. # Create a subdirectory with files
  1711. subdir = os.path.join(self.repo.path, "mixed")
  1712. os.mkdir(subdir)
  1713. # Create and commit one file
  1714. tracked_file = os.path.join(subdir, "tracked.txt")
  1715. with open(tracked_file, "w") as f:
  1716. f.write("already tracked")
  1717. porcelain.add(self.repo.path, paths=[tracked_file])
  1718. porcelain.commit(
  1719. repo=self.repo.path,
  1720. message=b"Add tracked file",
  1721. author=b"test <email>",
  1722. committer=b"test <email>",
  1723. )
  1724. # Add more untracked files
  1725. with open(os.path.join(subdir, "untracked1.txt"), "w") as f:
  1726. f.write("new file 1")
  1727. with open(os.path.join(subdir, "untracked2.txt"), "w") as f:
  1728. f.write("new file 2")
  1729. # Add the directory
  1730. added, _ignored = porcelain.add(self.repo.path, paths=["mixed"])
  1731. # Should only add the untracked files
  1732. self.assertEqual(len(added), 2)
  1733. # Normalize paths to use forward slashes for comparison
  1734. added_normalized = [path.replace(os.sep, "/") for path in added]
  1735. self.assertIn("mixed/untracked1.txt", added_normalized)
  1736. self.assertIn("mixed/untracked2.txt", added_normalized)
  1737. self.assertNotIn("mixed/tracked.txt", added)
  1738. # Verify the index contains all files
  1739. index = self.repo.open_index()
  1740. self.assertIn(b"mixed/tracked.txt", index)
  1741. self.assertIn(b"mixed/untracked1.txt", index)
  1742. self.assertIn(b"mixed/untracked2.txt", index)
  1743. def test_add_directory_with_gitignore(self) -> None:
  1744. """Test adding a directory respects .gitignore patterns."""
  1745. # Create .gitignore
  1746. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1747. f.write("*.log\n*.tmp\nbuild/\n")
  1748. # Create directory with mixed files
  1749. testdir = os.path.join(self.repo.path, "testdir")
  1750. os.mkdir(testdir)
  1751. # Create various files
  1752. with open(os.path.join(testdir, "important.txt"), "w") as f:
  1753. f.write("keep this")
  1754. with open(os.path.join(testdir, "debug.log"), "w") as f:
  1755. f.write("ignore this")
  1756. with open(os.path.join(testdir, "temp.tmp"), "w") as f:
  1757. f.write("ignore this too")
  1758. with open(os.path.join(testdir, "readme.md"), "w") as f:
  1759. f.write("keep this too")
  1760. # Create a build directory that should be ignored
  1761. builddir = os.path.join(testdir, "build")
  1762. os.mkdir(builddir)
  1763. with open(os.path.join(builddir, "output.txt"), "w") as f:
  1764. f.write("ignore entire directory")
  1765. # Add the directory
  1766. added, ignored = porcelain.add(self.repo.path, paths=["testdir"])
  1767. # Should only add non-ignored files
  1768. # Normalize paths to use forward slashes for comparison
  1769. added_normalized = {path.replace(os.sep, "/") for path in added}
  1770. self.assertEqual(
  1771. added_normalized, {"testdir/important.txt", "testdir/readme.md"}
  1772. )
  1773. # Check ignored files
  1774. # Normalize paths to use forward slashes for comparison
  1775. ignored_normalized = {path.replace(os.sep, "/") for path in ignored}
  1776. self.assertIn("testdir/debug.log", ignored_normalized)
  1777. self.assertIn("testdir/temp.tmp", ignored_normalized)
  1778. self.assertIn("testdir/build/", ignored_normalized)
  1779. def test_add_multiple_directories(self) -> None:
  1780. """Test adding multiple directories in one call."""
  1781. # Create multiple directories
  1782. for dirname in ["dir1", "dir2", "dir3"]:
  1783. dirpath = os.path.join(self.repo.path, dirname)
  1784. os.mkdir(dirpath)
  1785. # Add files to each directory
  1786. for i in range(2):
  1787. with open(os.path.join(dirpath, f"file{i}.txt"), "w") as f:
  1788. f.write(f"content {dirname} {i}")
  1789. # Add all directories at once
  1790. added, _ignored = porcelain.add(self.repo.path, paths=["dir1", "dir2", "dir3"])
  1791. # Should add all files from all directories
  1792. self.assertEqual(len(added), 6)
  1793. # Normalize paths to use forward slashes for comparison
  1794. added_normalized = [path.replace(os.sep, "/") for path in added]
  1795. for dirname in ["dir1", "dir2", "dir3"]:
  1796. for i in range(2):
  1797. self.assertIn(f"{dirname}/file{i}.txt", added_normalized)
  1798. # Verify all files are staged
  1799. index = self.repo.open_index()
  1800. self.assertEqual(len(index), 6)
  1801. def test_add_default_paths_includes_modified_files(self) -> None:
  1802. """Test that add() with no paths includes both untracked and modified files."""
  1803. # Create and commit initial file
  1804. initial_file = os.path.join(self.repo.path, "existing.txt")
  1805. with open(initial_file, "w") as f:
  1806. f.write("initial content\n")
  1807. porcelain.add(repo=self.repo.path, paths=[initial_file])
  1808. porcelain.commit(
  1809. repo=self.repo.path,
  1810. message=b"initial commit",
  1811. author=b"test <email>",
  1812. committer=b"test <email>",
  1813. )
  1814. # Modify the existing file (this creates an unstaged change)
  1815. with open(initial_file, "w") as f:
  1816. f.write("modified content\n")
  1817. # Create a new untracked file
  1818. new_file = os.path.join(self.repo.path, "new.txt")
  1819. with open(new_file, "w") as f:
  1820. f.write("new file content\n")
  1821. # Call add() with no paths - should stage both modified and untracked files
  1822. added_files, ignored_files = porcelain.add(repo=self.repo.path)
  1823. # Verify both files were added
  1824. self.assertIn("existing.txt", added_files)
  1825. self.assertIn("new.txt", added_files)
  1826. self.assertEqual(len(ignored_files), 0)
  1827. # Verify both files are now staged
  1828. index = self.repo.open_index()
  1829. self.assertIn(b"existing.txt", index)
  1830. self.assertIn(b"new.txt", index)
  1831. def test_add_empty_paths_list(self) -> None:
  1832. """Test that passing paths=[] does not add any files."""
  1833. # Create an untracked file
  1834. with open(os.path.join(self.repo.path, "file.txt"), "w") as f:
  1835. f.write("content")
  1836. # Add with empty paths list
  1837. added, _ignored = porcelain.add(self.repo.path, paths=[])
  1838. # Should not add any files
  1839. self.assertEqual(len(added), 0)
  1840. class RemoveTests(PorcelainTestCase):
  1841. def test_remove_file(self) -> None:
  1842. fullpath = os.path.join(self.repo.path, "foo")
  1843. with open(fullpath, "w") as f:
  1844. f.write("BAR")
  1845. porcelain.add(self.repo.path, paths=[fullpath])
  1846. porcelain.commit(
  1847. repo=self.repo,
  1848. message=b"test",
  1849. author=b"test <email>",
  1850. committer=b"test <email>",
  1851. )
  1852. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "foo")))
  1853. cwd = os.getcwd()
  1854. self.addCleanup(os.chdir, cwd)
  1855. os.chdir(self.repo.path)
  1856. porcelain.remove(self.repo.path, paths=["foo"])
  1857. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1858. def test_remove_file_staged(self) -> None:
  1859. fullpath = os.path.join(self.repo.path, "foo")
  1860. with open(fullpath, "w") as f:
  1861. f.write("BAR")
  1862. cwd = os.getcwd()
  1863. self.addCleanup(os.chdir, cwd)
  1864. os.chdir(self.repo.path)
  1865. porcelain.add(self.repo.path, paths=[fullpath])
  1866. self.assertRaises(Exception, porcelain.rm, self.repo.path, paths=["foo"])
  1867. def test_remove_file_removed_on_disk(self) -> None:
  1868. fullpath = os.path.join(self.repo.path, "foo")
  1869. with open(fullpath, "w") as f:
  1870. f.write("BAR")
  1871. porcelain.add(self.repo.path, paths=[fullpath])
  1872. cwd = os.getcwd()
  1873. self.addCleanup(os.chdir, cwd)
  1874. os.chdir(self.repo.path)
  1875. os.remove(fullpath)
  1876. porcelain.remove(self.repo.path, paths=["foo"])
  1877. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1878. def test_remove_from_different_directory(self) -> None:
  1879. # Create a subdirectory with a file
  1880. subdir = os.path.join(self.repo.path, "mydir")
  1881. os.makedirs(subdir)
  1882. fullpath = os.path.join(subdir, "myfile")
  1883. with open(fullpath, "w") as f:
  1884. f.write("BAR")
  1885. # Add and commit the file
  1886. porcelain.add(self.repo.path, paths=[fullpath])
  1887. porcelain.commit(
  1888. repo=self.repo,
  1889. message=b"test",
  1890. author=b"test <email>",
  1891. committer=b"test <email>",
  1892. )
  1893. # Change to a different directory
  1894. cwd = os.getcwd()
  1895. tempdir = tempfile.mkdtemp()
  1896. def cleanup():
  1897. os.chdir(cwd)
  1898. shutil.rmtree(tempdir)
  1899. self.addCleanup(cleanup)
  1900. os.chdir(tempdir)
  1901. # Remove the file using relative path from repository root
  1902. porcelain.remove(self.repo.path, paths=["mydir/myfile"])
  1903. # Verify file was removed
  1904. self.assertFalse(os.path.exists(fullpath))
  1905. def test_remove_with_absolute_path(self) -> None:
  1906. # Create a file
  1907. fullpath = os.path.join(self.repo.path, "foo")
  1908. with open(fullpath, "w") as f:
  1909. f.write("BAR")
  1910. # Add and commit the file
  1911. porcelain.add(self.repo.path, paths=[fullpath])
  1912. porcelain.commit(
  1913. repo=self.repo,
  1914. message=b"test",
  1915. author=b"test <email>",
  1916. committer=b"test <email>",
  1917. )
  1918. # Change to a different directory
  1919. cwd = os.getcwd()
  1920. tempdir = tempfile.mkdtemp()
  1921. def cleanup():
  1922. os.chdir(cwd)
  1923. shutil.rmtree(tempdir)
  1924. self.addCleanup(cleanup)
  1925. os.chdir(tempdir)
  1926. # Remove the file using absolute path
  1927. porcelain.remove(self.repo.path, paths=[fullpath])
  1928. # Verify file was removed
  1929. self.assertFalse(os.path.exists(fullpath))
  1930. def test_remove_with_filter_normalization(self) -> None:
  1931. # Enable autocrlf to normalize line endings
  1932. config = self.repo.get_config()
  1933. config.set(("core",), "autocrlf", b"true")
  1934. config.write_to_path()
  1935. # Create a file with LF line endings (will be stored with LF in index)
  1936. fullpath = os.path.join(self.repo.path, "foo.txt")
  1937. with open(fullpath, "wb") as f:
  1938. f.write(b"line1\nline2\nline3")
  1939. # Add and commit the file (stored with LF in index)
  1940. porcelain.add(self.repo.path, paths=[fullpath])
  1941. porcelain.commit(
  1942. repo=self.repo,
  1943. message=b"Add file with LF",
  1944. author=b"test <email>",
  1945. committer=b"test <email>",
  1946. )
  1947. # Simulate checkout with CRLF conversion (as would happen on Windows)
  1948. with open(fullpath, "wb") as f:
  1949. f.write(b"line1\r\nline2\r\nline3")
  1950. # Verify file exists
  1951. self.assertTrue(os.path.exists(fullpath))
  1952. # Remove the file - this should not fail even though working tree has CRLF
  1953. # and index has LF (thanks to the normalization in the commit)
  1954. cwd = os.getcwd()
  1955. os.chdir(self.repo.path)
  1956. self.addCleanup(os.chdir, cwd)
  1957. porcelain.remove(self.repo.path, paths=["foo.txt"])
  1958. # Verify file was removed
  1959. self.assertFalse(os.path.exists(fullpath))
  1960. class MvTests(PorcelainTestCase):
  1961. def test_mv_file(self) -> None:
  1962. # Create a file
  1963. fullpath = os.path.join(self.repo.path, "foo")
  1964. with open(fullpath, "w") as f:
  1965. f.write("BAR")
  1966. # Add and commit the file
  1967. porcelain.add(self.repo.path, paths=[fullpath])
  1968. porcelain.commit(
  1969. repo=self.repo,
  1970. message=b"test",
  1971. author=b"test <email>",
  1972. committer=b"test <email>",
  1973. )
  1974. # Move the file
  1975. porcelain.mv(self.repo.path, "foo", "bar")
  1976. # Verify old path doesn't exist and new path does
  1977. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1978. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "bar")))
  1979. # Verify index was updated
  1980. index = self.repo.open_index()
  1981. self.assertNotIn(b"foo", index)
  1982. self.assertIn(b"bar", index)
  1983. def test_mv_file_to_existing_directory(self) -> None:
  1984. # Create a file and a directory
  1985. fullpath = os.path.join(self.repo.path, "foo")
  1986. with open(fullpath, "w") as f:
  1987. f.write("BAR")
  1988. dirpath = os.path.join(self.repo.path, "mydir")
  1989. os.makedirs(dirpath)
  1990. # Add and commit the file
  1991. porcelain.add(self.repo.path, paths=[fullpath])
  1992. porcelain.commit(
  1993. repo=self.repo,
  1994. message=b"test",
  1995. author=b"test <email>",
  1996. committer=b"test <email>",
  1997. )
  1998. # Move the file into the directory
  1999. porcelain.mv(self.repo.path, "foo", "mydir")
  2000. # Verify file moved into directory
  2001. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  2002. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "mydir", "foo")))
  2003. # Verify index was updated
  2004. index = self.repo.open_index()
  2005. self.assertNotIn(b"foo", index)
  2006. self.assertIn(b"mydir/foo", index)
  2007. def test_mv_file_force_overwrite(self) -> None:
  2008. # Create two files
  2009. fullpath1 = os.path.join(self.repo.path, "foo")
  2010. with open(fullpath1, "w") as f:
  2011. f.write("FOO")
  2012. fullpath2 = os.path.join(self.repo.path, "bar")
  2013. with open(fullpath2, "w") as f:
  2014. f.write("BAR")
  2015. # Add and commit both files
  2016. porcelain.add(self.repo.path, paths=[fullpath1, fullpath2])
  2017. porcelain.commit(
  2018. repo=self.repo,
  2019. message=b"test",
  2020. author=b"test <email>",
  2021. committer=b"test <email>",
  2022. )
  2023. # Try to move without force (should fail)
  2024. self.assertRaises(porcelain.Error, porcelain.mv, self.repo.path, "foo", "bar")
  2025. # Move with force
  2026. porcelain.mv(self.repo.path, "foo", "bar", force=True)
  2027. # Verify foo doesn't exist and bar has foo's content
  2028. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  2029. with open(os.path.join(self.repo.path, "bar")) as f:
  2030. self.assertEqual(f.read(), "FOO")
  2031. def test_mv_file_not_tracked(self) -> None:
  2032. # Create an untracked file
  2033. fullpath = os.path.join(self.repo.path, "untracked")
  2034. with open(fullpath, "w") as f:
  2035. f.write("UNTRACKED")
  2036. # Try to move it (should fail)
  2037. self.assertRaises(
  2038. porcelain.Error, porcelain.mv, self.repo.path, "untracked", "tracked"
  2039. )
  2040. def test_mv_file_not_exists(self) -> None:
  2041. # Try to move a non-existent file
  2042. self.assertRaises(
  2043. porcelain.Error, porcelain.mv, self.repo.path, "nonexistent", "destination"
  2044. )
  2045. def test_mv_absolute_paths(self) -> None:
  2046. # Create a file
  2047. fullpath = os.path.join(self.repo.path, "foo")
  2048. with open(fullpath, "w") as f:
  2049. f.write("BAR")
  2050. # Add and commit the file
  2051. porcelain.add(self.repo.path, paths=[fullpath])
  2052. porcelain.commit(
  2053. repo=self.repo,
  2054. message=b"test",
  2055. author=b"test <email>",
  2056. committer=b"test <email>",
  2057. )
  2058. # Move using absolute paths
  2059. dest_path = os.path.join(self.repo.path, "bar")
  2060. porcelain.mv(self.repo.path, fullpath, dest_path)
  2061. # Verify file moved
  2062. self.assertFalse(os.path.exists(fullpath))
  2063. self.assertTrue(os.path.exists(dest_path))
  2064. def test_mv_from_different_directory(self) -> None:
  2065. # Create a subdirectory with a file
  2066. subdir = os.path.join(self.repo.path, "mydir")
  2067. os.makedirs(subdir)
  2068. fullpath = os.path.join(subdir, "myfile")
  2069. with open(fullpath, "w") as f:
  2070. f.write("BAR")
  2071. # Add and commit the file
  2072. porcelain.add(self.repo.path, paths=[fullpath])
  2073. porcelain.commit(
  2074. repo=self.repo,
  2075. message=b"test",
  2076. author=b"test <email>",
  2077. committer=b"test <email>",
  2078. )
  2079. # Change to a different directory and move the file
  2080. cwd = os.getcwd()
  2081. tempdir = tempfile.mkdtemp()
  2082. def cleanup():
  2083. os.chdir(cwd)
  2084. shutil.rmtree(tempdir)
  2085. self.addCleanup(cleanup)
  2086. os.chdir(tempdir)
  2087. # Move the file using relative path from repository root
  2088. porcelain.mv(self.repo.path, "mydir/myfile", "renamed")
  2089. # Verify file was moved
  2090. self.assertFalse(os.path.exists(fullpath))
  2091. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "renamed")))
  2092. class LogTests(PorcelainTestCase):
  2093. def test_simple(self) -> None:
  2094. _c1, _c2, c3 = build_commit_graph(
  2095. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2096. )
  2097. self.repo.refs[b"HEAD"] = c3.id
  2098. self.maxDiff = None
  2099. outstream = StringIO()
  2100. porcelain.log(self.repo.path, outstream=outstream)
  2101. self.assertEqual(
  2102. outstream.getvalue(),
  2103. """\
  2104. --------------------------------------------------
  2105. commit: 4a3b887baa9ecb2d054d2469b628aef84e2d74f0
  2106. merge: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  2107. Author: Test Author <test@nodomain.com>
  2108. Committer: Test Committer <test@nodomain.com>
  2109. Date: Fri Jan 01 2010 00:00:00 +0000
  2110. Commit 3
  2111. --------------------------------------------------
  2112. commit: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  2113. Author: Test Author <test@nodomain.com>
  2114. Committer: Test Committer <test@nodomain.com>
  2115. Date: Fri Jan 01 2010 00:00:00 +0000
  2116. Commit 2
  2117. --------------------------------------------------
  2118. commit: 11d3cf672a19366435c1983c7340b008ec6b8bf3
  2119. Author: Test Author <test@nodomain.com>
  2120. Committer: Test Committer <test@nodomain.com>
  2121. Date: Fri Jan 01 2010 00:00:00 +0000
  2122. Commit 1
  2123. """,
  2124. )
  2125. def test_max_entries(self) -> None:
  2126. _c1, _c2, c3 = build_commit_graph(
  2127. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2128. )
  2129. self.repo.refs[b"HEAD"] = c3.id
  2130. outstream = StringIO()
  2131. porcelain.log(self.repo.path, outstream=outstream, max_entries=1)
  2132. self.assertEqual(1, outstream.getvalue().count("-" * 50))
  2133. def test_no_revisions(self) -> None:
  2134. outstream = StringIO()
  2135. porcelain.log(self.repo.path, outstream=outstream)
  2136. self.assertEqual("", outstream.getvalue())
  2137. def test_empty_message(self) -> None:
  2138. c1 = make_commit(message="")
  2139. self.repo.object_store.add_object(c1)
  2140. self.repo.refs[b"HEAD"] = c1.id
  2141. outstream = StringIO()
  2142. porcelain.log(self.repo.path, outstream=outstream)
  2143. self.assertEqual(
  2144. outstream.getvalue(),
  2145. """\
  2146. --------------------------------------------------
  2147. commit: 4a7ad5552fad70647a81fb9a4a923ccefcca4b76
  2148. Author: Test Author <test@nodomain.com>
  2149. Committer: Test Committer <test@nodomain.com>
  2150. Date: Fri Jan 01 2010 00:00:00 +0000
  2151. """,
  2152. )
  2153. class ShowTests(PorcelainTestCase):
  2154. def test_nolist(self) -> None:
  2155. _c1, _c2, c3 = build_commit_graph(
  2156. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2157. )
  2158. self.repo.refs[b"HEAD"] = c3.id
  2159. outstream = StringIO()
  2160. porcelain.show(self.repo.path, objects=c3.id, outstream=outstream)
  2161. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  2162. def test_simple(self) -> None:
  2163. _c1, _c2, c3 = build_commit_graph(
  2164. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2165. )
  2166. self.repo.refs[b"HEAD"] = c3.id
  2167. outstream = StringIO()
  2168. porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream)
  2169. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  2170. def test_blob(self) -> None:
  2171. b = Blob.from_string(b"The Foo\n")
  2172. self.repo.object_store.add_object(b)
  2173. outstream = StringIO()
  2174. porcelain.show(self.repo.path, objects=[b.id], outstream=outstream)
  2175. self.assertEqual(outstream.getvalue(), "The Foo\n")
  2176. def test_commit_no_parent(self) -> None:
  2177. a = Blob.from_string(b"The Foo\n")
  2178. ta = Tree()
  2179. ta.add(b"somename", 0o100644, a.id)
  2180. ca = make_commit(tree=ta.id)
  2181. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2182. outstream = StringIO()
  2183. porcelain.show(self.repo.path, objects=[ca.id], outstream=outstream)
  2184. self.assertMultiLineEqual(
  2185. outstream.getvalue(),
  2186. """\
  2187. --------------------------------------------------
  2188. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2189. Author: Test Author <test@nodomain.com>
  2190. Committer: Test Committer <test@nodomain.com>
  2191. Date: Fri Jan 01 2010 00:00:00 +0000
  2192. Test message.
  2193. diff --git a/somename b/somename
  2194. new file mode 100644
  2195. index 0000000..ea5c7bf
  2196. --- /dev/null
  2197. +++ b/somename
  2198. @@ -0,0 +1 @@
  2199. +The Foo
  2200. """,
  2201. )
  2202. def test_tag(self) -> None:
  2203. a = Blob.from_string(b"The Foo\n")
  2204. ta = Tree()
  2205. ta.add(b"somename", 0o100644, a.id)
  2206. ca = make_commit(tree=ta.id)
  2207. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2208. porcelain.tag_create(
  2209. self.repo.path,
  2210. b"tryme",
  2211. b"foo <foo@bar.com>",
  2212. b"bar",
  2213. annotated=True,
  2214. objectish=ca.id,
  2215. tag_time=1552854211,
  2216. tag_timezone=0,
  2217. )
  2218. outstream = StringIO()
  2219. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2220. self.maxDiff = None
  2221. self.assertMultiLineEqual(
  2222. outstream.getvalue(),
  2223. """\
  2224. Tagger: foo <foo@bar.com>
  2225. Date: Sun Mar 17 2019 20:23:31 +0000
  2226. bar
  2227. --------------------------------------------------
  2228. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2229. Author: Test Author <test@nodomain.com>
  2230. Committer: Test Committer <test@nodomain.com>
  2231. Date: Fri Jan 01 2010 00:00:00 +0000
  2232. Test message.
  2233. diff --git a/somename b/somename
  2234. new file mode 100644
  2235. index 0000000..ea5c7bf
  2236. --- /dev/null
  2237. +++ b/somename
  2238. @@ -0,0 +1 @@
  2239. +The Foo
  2240. """,
  2241. )
  2242. def test_tag_unicode(self) -> None:
  2243. a = Blob.from_string(b"The Foo\n")
  2244. ta = Tree()
  2245. ta.add(b"somename", 0o100644, a.id)
  2246. ca = make_commit(tree=ta.id)
  2247. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2248. porcelain.tag_create(
  2249. self.repo.path,
  2250. "tryme",
  2251. "foo <foo@bar.com>",
  2252. "bar",
  2253. annotated=True,
  2254. objectish=ca.id,
  2255. tag_time=1552854211,
  2256. tag_timezone=0,
  2257. )
  2258. outstream = StringIO()
  2259. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2260. self.maxDiff = None
  2261. self.assertMultiLineEqual(
  2262. outstream.getvalue(),
  2263. """\
  2264. Tagger: foo <foo@bar.com>
  2265. Date: Sun Mar 17 2019 20:23:31 +0000
  2266. bar
  2267. --------------------------------------------------
  2268. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2269. Author: Test Author <test@nodomain.com>
  2270. Committer: Test Committer <test@nodomain.com>
  2271. Date: Fri Jan 01 2010 00:00:00 +0000
  2272. Test message.
  2273. diff --git a/somename b/somename
  2274. new file mode 100644
  2275. index 0000000..ea5c7bf
  2276. --- /dev/null
  2277. +++ b/somename
  2278. @@ -0,0 +1 @@
  2279. +The Foo
  2280. """,
  2281. )
  2282. def test_commit_with_change(self) -> None:
  2283. a = Blob.from_string(b"The Foo\n")
  2284. ta = Tree()
  2285. ta.add(b"somename", 0o100644, a.id)
  2286. ca = make_commit(tree=ta.id)
  2287. b = Blob.from_string(b"The Bar\n")
  2288. tb = Tree()
  2289. tb.add(b"somename", 0o100644, b.id)
  2290. cb = make_commit(tree=tb.id, parents=[ca.id])
  2291. self.repo.object_store.add_objects(
  2292. [
  2293. (a, None),
  2294. (b, None),
  2295. (ta, None),
  2296. (tb, None),
  2297. (ca, None),
  2298. (cb, None),
  2299. ]
  2300. )
  2301. outstream = StringIO()
  2302. porcelain.show(self.repo.path, objects=[cb.id], outstream=outstream)
  2303. self.assertMultiLineEqual(
  2304. outstream.getvalue(),
  2305. """\
  2306. --------------------------------------------------
  2307. commit: 2c6b6c9cb72c130956657e1fdae58e5b103744fa
  2308. Author: Test Author <test@nodomain.com>
  2309. Committer: Test Committer <test@nodomain.com>
  2310. Date: Fri Jan 01 2010 00:00:00 +0000
  2311. Test message.
  2312. diff --git a/somename b/somename
  2313. index ea5c7bf..fd38bcb 100644
  2314. --- a/somename
  2315. +++ b/somename
  2316. @@ -1 +1 @@
  2317. -The Foo
  2318. +The Bar
  2319. """,
  2320. )
  2321. class FormatPatchTests(PorcelainTestCase):
  2322. def test_format_patch_single_commit(self) -> None:
  2323. # Create initial commit
  2324. tree1 = Tree()
  2325. c1 = make_commit(
  2326. tree=tree1,
  2327. message=b"Initial commit",
  2328. )
  2329. self.repo.object_store.add_objects([(tree1, None), (c1, None)])
  2330. # Create second commit
  2331. b = Blob.from_string(b"modified")
  2332. tree = Tree()
  2333. tree.add(b"test.txt", 0o100644, b.id)
  2334. c2 = make_commit(
  2335. tree=tree,
  2336. parents=[c1.id],
  2337. message=b"Add test.txt",
  2338. )
  2339. self.repo.object_store.add_objects([(b, None), (tree, None), (c2, None)])
  2340. self.repo[b"HEAD"] = c2.id
  2341. # Generate patch for single commit
  2342. with tempfile.TemporaryDirectory() as tmpdir:
  2343. patches = porcelain.format_patch(
  2344. self.repo.path,
  2345. committish=c2.id,
  2346. outdir=tmpdir,
  2347. )
  2348. self.assertEqual(len(patches), 1)
  2349. self.assertTrue(patches[0].endswith("-Add-test.txt.patch"))
  2350. # Verify patch content
  2351. with open(patches[0], "rb") as f:
  2352. content = f.read()
  2353. self.assertIn(b"Subject: [PATCH 1/1] Add test.txt", content)
  2354. self.assertIn(b"+modified", content)
  2355. def test_format_patch_multiple_commits(self) -> None:
  2356. # Create commit chain
  2357. commits = []
  2358. for i in range(3):
  2359. blob = Blob.from_string(f"content {i}".encode())
  2360. tree = Tree()
  2361. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  2362. parents = [commits[-1].id] if commits else []
  2363. commit = make_commit(
  2364. tree=tree,
  2365. parents=parents,
  2366. message=f"Commit {i}".encode(),
  2367. )
  2368. self.repo.object_store.add_objects(
  2369. [(blob, None), (tree, None), (commit, None)]
  2370. )
  2371. commits.append(commit)
  2372. self.repo[b"HEAD"] = commits[-1].id
  2373. # Test generating last 2 commits
  2374. with tempfile.TemporaryDirectory() as tmpdir:
  2375. patches = porcelain.format_patch(
  2376. self.repo.path,
  2377. n=2,
  2378. outdir=tmpdir,
  2379. )
  2380. self.assertEqual(len(patches), 2)
  2381. self.assertTrue(patches[0].endswith("-Commit-1.patch"))
  2382. self.assertTrue(patches[1].endswith("-Commit-2.patch"))
  2383. # Check patch numbering
  2384. with open(patches[0], "rb") as f:
  2385. self.assertIn(b"Subject: [PATCH 1/2] Commit 1", f.read())
  2386. with open(patches[1], "rb") as f:
  2387. self.assertIn(b"Subject: [PATCH 2/2] Commit 2", f.read())
  2388. def test_format_patch_range(self) -> None:
  2389. # Create commit chain
  2390. c1, _c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  2391. self.repo[b"HEAD"] = c3.id
  2392. # Test commit range
  2393. with tempfile.TemporaryDirectory() as tmpdir:
  2394. patches = porcelain.format_patch(
  2395. self.repo.path,
  2396. committish=(c1.id, c3.id),
  2397. outdir=tmpdir,
  2398. )
  2399. # Should include c2 and c3
  2400. self.assertEqual(len(patches), 2)
  2401. def test_format_patch_stdout(self) -> None:
  2402. # Create a commit
  2403. blob = Blob.from_string(b"test content")
  2404. tree = Tree()
  2405. tree.add(b"test.txt", 0o100644, blob.id)
  2406. commit = make_commit(
  2407. tree=tree,
  2408. message=b"Test commit",
  2409. )
  2410. self.repo.object_store.add_objects([(blob, None), (tree, None), (commit, None)])
  2411. self.repo[b"HEAD"] = commit.id
  2412. # Test stdout output
  2413. outstream = BytesIO()
  2414. patches = porcelain.format_patch(
  2415. self.repo.path,
  2416. committish=commit.id,
  2417. stdout=True,
  2418. outstream=outstream,
  2419. )
  2420. # Should return empty list when writing to stdout
  2421. self.assertEqual(patches, [])
  2422. # Check stdout content
  2423. outstream.seek(0)
  2424. content = outstream.read()
  2425. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  2426. self.assertIn(b"diff --git", content)
  2427. def test_format_patch_no_commits(self) -> None:
  2428. # Test with a new repository with no commits
  2429. # Just remove HEAD to simulate empty repo
  2430. patches = porcelain.format_patch(
  2431. self.repo.path,
  2432. n=5,
  2433. )
  2434. self.assertEqual(patches, [])
  2435. class SymbolicRefTests(PorcelainTestCase):
  2436. def test_set_wrong_symbolic_ref(self) -> None:
  2437. _c1, _c2, c3 = build_commit_graph(
  2438. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2439. )
  2440. self.repo.refs[b"HEAD"] = c3.id
  2441. self.assertRaises(
  2442. porcelain.Error, porcelain.symbolic_ref, self.repo.path, b"foobar"
  2443. )
  2444. def test_set_force_wrong_symbolic_ref(self) -> None:
  2445. _c1, _c2, c3 = build_commit_graph(
  2446. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2447. )
  2448. self.repo.refs[b"HEAD"] = c3.id
  2449. porcelain.symbolic_ref(self.repo.path, b"force_foobar", force=True)
  2450. # test if we actually changed the file
  2451. with self.repo.get_named_file("HEAD") as f:
  2452. new_ref = f.read()
  2453. self.assertEqual(new_ref, b"ref: refs/heads/force_foobar\n")
  2454. def test_set_symbolic_ref(self) -> None:
  2455. _c1, _c2, c3 = build_commit_graph(
  2456. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2457. )
  2458. self.repo.refs[b"HEAD"] = c3.id
  2459. porcelain.symbolic_ref(self.repo.path, b"master")
  2460. def test_set_symbolic_ref_other_than_master(self) -> None:
  2461. _c1, _c2, c3 = build_commit_graph(
  2462. self.repo.object_store,
  2463. [[1], [2, 1], [3, 1, 2]],
  2464. attrs=dict(refs="develop"),
  2465. )
  2466. self.repo.refs[b"HEAD"] = c3.id
  2467. self.repo.refs[b"refs/heads/develop"] = c3.id
  2468. porcelain.symbolic_ref(self.repo.path, b"develop")
  2469. # test if we actually changed the file
  2470. with self.repo.get_named_file("HEAD") as f:
  2471. new_ref = f.read()
  2472. self.assertEqual(new_ref, b"ref: refs/heads/develop\n")
  2473. class DiffTreeTests(PorcelainTestCase):
  2474. def test_empty(self) -> None:
  2475. _c1, c2, c3 = build_commit_graph(
  2476. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2477. )
  2478. self.repo.refs[b"HEAD"] = c3.id
  2479. outstream = BytesIO()
  2480. porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream)
  2481. self.assertEqual(outstream.getvalue(), b"")
  2482. class DiffTests(PorcelainTestCase):
  2483. def test_diff_uncommitted_stage(self) -> None:
  2484. # Test diff in repository with no commits yet
  2485. fullpath = os.path.join(self.repo.path, "test.txt")
  2486. with open(fullpath, "w") as f:
  2487. f.write("Hello, world!\n")
  2488. porcelain.add(self.repo.path, paths=["test.txt"])
  2489. outstream = BytesIO()
  2490. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2491. diff_output = outstream.getvalue()
  2492. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2493. self.assertIn(b"new file mode", diff_output)
  2494. self.assertIn(b"+Hello, world!", diff_output)
  2495. def test_diff_uncommitted_working_tree(self) -> None:
  2496. # Test unstaged changes in repository with no commits
  2497. fullpath = os.path.join(self.repo.path, "test.txt")
  2498. with open(fullpath, "w") as f:
  2499. f.write("Hello, world!\n")
  2500. porcelain.add(self.repo.path, paths=["test.txt"])
  2501. # Modify file in working tree
  2502. with open(fullpath, "w") as f:
  2503. f.write("Hello, world!\nNew line\n")
  2504. outstream = BytesIO()
  2505. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2506. diff_output = outstream.getvalue()
  2507. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2508. self.assertIn(b"+New line", diff_output)
  2509. def test_diff_with_commits_staged(self) -> None:
  2510. # Test staged changes with existing commits
  2511. fullpath = os.path.join(self.repo.path, "test.txt")
  2512. with open(fullpath, "w") as f:
  2513. f.write("Initial content\n")
  2514. porcelain.add(self.repo.path, paths=["test.txt"])
  2515. porcelain.commit(self.repo.path, message=b"Initial commit")
  2516. # Modify and stage
  2517. with open(fullpath, "w") as f:
  2518. f.write("Initial content\nModified\n")
  2519. porcelain.add(self.repo.path, paths=["test.txt"])
  2520. outstream = BytesIO()
  2521. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2522. diff_output = outstream.getvalue()
  2523. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2524. self.assertIn(b"+Modified", diff_output)
  2525. def test_diff_with_commits_unstaged(self) -> None:
  2526. # Test unstaged changes with existing commits
  2527. fullpath = os.path.join(self.repo.path, "test.txt")
  2528. with open(fullpath, "w") as f:
  2529. f.write("Initial content\n")
  2530. porcelain.add(self.repo.path, paths=["test.txt"])
  2531. porcelain.commit(self.repo.path, message=b"Initial commit")
  2532. # Modify without staging
  2533. with open(fullpath, "w") as f:
  2534. f.write("Initial content\nModified\n")
  2535. outstream = BytesIO()
  2536. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2537. diff_output = outstream.getvalue()
  2538. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2539. self.assertIn(b"+Modified", diff_output)
  2540. def test_diff_file_deletion(self) -> None:
  2541. # Test showing file deletion
  2542. fullpath = os.path.join(self.repo.path, "test.txt")
  2543. with open(fullpath, "w") as f:
  2544. f.write("Content to delete\n")
  2545. porcelain.add(self.repo.path, paths=["test.txt"])
  2546. porcelain.commit(self.repo.path, message=b"Add file")
  2547. # Delete file
  2548. os.unlink(fullpath)
  2549. outstream = BytesIO()
  2550. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2551. diff_output = outstream.getvalue()
  2552. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2553. self.assertIn(b"deleted file mode", diff_output)
  2554. self.assertIn(b"-Content to delete", diff_output)
  2555. def test_diff_with_paths(self) -> None:
  2556. # Test diff with specific paths
  2557. # Create two files
  2558. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2559. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2560. with open(fullpath1, "w") as f:
  2561. f.write("File 1 content\n")
  2562. with open(fullpath2, "w") as f:
  2563. f.write("File 2 content\n")
  2564. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2565. porcelain.commit(self.repo.path, message=b"Add two files")
  2566. # Modify both files
  2567. with open(fullpath1, "w") as f:
  2568. f.write("File 1 modified\n")
  2569. with open(fullpath2, "w") as f:
  2570. f.write("File 2 modified\n")
  2571. # Test diff with specific path
  2572. outstream = BytesIO()
  2573. porcelain.diff(self.repo.path, paths=["file1.txt"], outstream=outstream)
  2574. diff_output = outstream.getvalue()
  2575. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2576. self.assertIn(b"-File 1 content", diff_output)
  2577. self.assertIn(b"+File 1 modified", diff_output)
  2578. # file2.txt should not appear in diff
  2579. self.assertNotIn(b"file2.txt", diff_output)
  2580. def test_diff_with_paths_multiple(self) -> None:
  2581. # Test diff with multiple paths
  2582. # Create three files
  2583. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2584. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2585. fullpath3 = os.path.join(self.repo.path, "file3.txt")
  2586. with open(fullpath1, "w") as f:
  2587. f.write("File 1 content\n")
  2588. with open(fullpath2, "w") as f:
  2589. f.write("File 2 content\n")
  2590. with open(fullpath3, "w") as f:
  2591. f.write("File 3 content\n")
  2592. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt", "file3.txt"])
  2593. porcelain.commit(self.repo.path, message=b"Add three files")
  2594. # Modify all files
  2595. with open(fullpath1, "w") as f:
  2596. f.write("File 1 modified\n")
  2597. with open(fullpath2, "w") as f:
  2598. f.write("File 2 modified\n")
  2599. with open(fullpath3, "w") as f:
  2600. f.write("File 3 modified\n")
  2601. # Test diff with two specific paths
  2602. outstream = BytesIO()
  2603. porcelain.diff(
  2604. self.repo.path, paths=["file1.txt", "file3.txt"], outstream=outstream
  2605. )
  2606. diff_output = outstream.getvalue()
  2607. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2608. self.assertIn(b"diff --git a/file3.txt b/file3.txt", diff_output)
  2609. # file2.txt should not appear in diff
  2610. self.assertNotIn(b"file2.txt", diff_output)
  2611. def test_diff_with_paths_directory(self) -> None:
  2612. # Test diff with directory paths
  2613. # Create files in subdirectory
  2614. os.mkdir(os.path.join(self.repo.path, "subdir"))
  2615. fullpath1 = os.path.join(self.repo.path, "subdir", "file1.txt")
  2616. fullpath2 = os.path.join(self.repo.path, "subdir", "file2.txt")
  2617. fullpath3 = os.path.join(self.repo.path, "root.txt")
  2618. with open(fullpath1, "w") as f:
  2619. f.write("Subdir file 1\n")
  2620. with open(fullpath2, "w") as f:
  2621. f.write("Subdir file 2\n")
  2622. with open(fullpath3, "w") as f:
  2623. f.write("Root file\n")
  2624. porcelain.add(
  2625. self.repo.path, paths=["subdir/file1.txt", "subdir/file2.txt", "root.txt"]
  2626. )
  2627. porcelain.commit(self.repo.path, message=b"Add files in subdir")
  2628. # Modify all files
  2629. with open(fullpath1, "w") as f:
  2630. f.write("Subdir file 1 modified\n")
  2631. with open(fullpath2, "w") as f:
  2632. f.write("Subdir file 2 modified\n")
  2633. with open(fullpath3, "w") as f:
  2634. f.write("Root file modified\n")
  2635. # Test diff with directory path
  2636. outstream = BytesIO()
  2637. porcelain.diff(self.repo.path, paths=["subdir"], outstream=outstream)
  2638. diff_output = outstream.getvalue()
  2639. self.assertIn(b"subdir/file1.txt", diff_output)
  2640. self.assertIn(b"subdir/file2.txt", diff_output)
  2641. # root.txt should not appear in diff
  2642. self.assertNotIn(b"root.txt", diff_output)
  2643. def test_diff_staged_with_paths(self) -> None:
  2644. # Test staged diff with specific paths
  2645. # Create two files
  2646. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2647. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2648. with open(fullpath1, "w") as f:
  2649. f.write("File 1 content\n")
  2650. with open(fullpath2, "w") as f:
  2651. f.write("File 2 content\n")
  2652. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2653. porcelain.commit(self.repo.path, message=b"Add two files")
  2654. # Modify and stage both files
  2655. with open(fullpath1, "w") as f:
  2656. f.write("File 1 staged\n")
  2657. with open(fullpath2, "w") as f:
  2658. f.write("File 2 staged\n")
  2659. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2660. # Test staged diff with specific path
  2661. outstream = BytesIO()
  2662. porcelain.diff(
  2663. self.repo.path, staged=True, paths=["file1.txt"], outstream=outstream
  2664. )
  2665. diff_output = outstream.getvalue()
  2666. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2667. self.assertIn(b"-File 1 content", diff_output)
  2668. self.assertIn(b"+File 1 staged", diff_output)
  2669. # file2.txt should not appear in diff
  2670. self.assertNotIn(b"file2.txt", diff_output)
  2671. def test_diff_with_commit_and_paths(self) -> None:
  2672. # Test diff against specific commit with paths
  2673. # Create initial file
  2674. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2675. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2676. with open(fullpath1, "w") as f:
  2677. f.write("Initial content 1\n")
  2678. with open(fullpath2, "w") as f:
  2679. f.write("Initial content 2\n")
  2680. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2681. first_commit = porcelain.commit(self.repo.path, message=b"Initial commit")
  2682. # Make second commit
  2683. with open(fullpath1, "w") as f:
  2684. f.write("Second content 1\n")
  2685. with open(fullpath2, "w") as f:
  2686. f.write("Second content 2\n")
  2687. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2688. porcelain.commit(self.repo.path, message=b"Second commit")
  2689. # Modify working tree
  2690. with open(fullpath1, "w") as f:
  2691. f.write("Working content 1\n")
  2692. with open(fullpath2, "w") as f:
  2693. f.write("Working content 2\n")
  2694. # Test diff against first commit with specific path
  2695. outstream = BytesIO()
  2696. porcelain.diff(
  2697. self.repo.path,
  2698. commit=first_commit,
  2699. paths=["file1.txt"],
  2700. outstream=outstream,
  2701. )
  2702. diff_output = outstream.getvalue()
  2703. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2704. self.assertIn(b"-Initial content 1", diff_output)
  2705. self.assertIn(b"+Working content 1", diff_output)
  2706. # file2.txt should not appear in diff
  2707. self.assertNotIn(b"file2.txt", diff_output)
  2708. class CommitTreeTests(PorcelainTestCase):
  2709. def test_simple(self) -> None:
  2710. _c1, _c2, _c3 = build_commit_graph(
  2711. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2712. )
  2713. b = Blob()
  2714. b.data = b"foo the bar"
  2715. t = Tree()
  2716. t.add(b"somename", 0o100644, b.id)
  2717. self.repo.object_store.add_object(t)
  2718. self.repo.object_store.add_object(b)
  2719. sha = porcelain.commit_tree(
  2720. self.repo.path,
  2721. t.id,
  2722. message=b"Withcommit.",
  2723. author=b"Joe <joe@example.com>",
  2724. committer=b"Jane <jane@example.com>",
  2725. )
  2726. self.assertIsInstance(sha, bytes)
  2727. self.assertEqual(len(sha), 40)
  2728. class RevListTests(PorcelainTestCase):
  2729. def test_simple(self) -> None:
  2730. c1, c2, c3 = build_commit_graph(
  2731. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2732. )
  2733. outstream = BytesIO()
  2734. porcelain.rev_list(self.repo.path, [c3.id], outstream=outstream)
  2735. self.assertEqual(
  2736. c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue()
  2737. )
  2738. @skipIf(
  2739. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  2740. "gpgme not easily available or supported on Windows and PyPy",
  2741. )
  2742. class TagCreateSignTests(PorcelainGpgTestCase):
  2743. def test_default_key(self) -> None:
  2744. _c1, _c2, c3 = build_commit_graph(
  2745. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2746. )
  2747. self.repo.refs[b"HEAD"] = c3.id
  2748. cfg = self.repo.get_config()
  2749. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2750. self.import_default_key()
  2751. porcelain.tag_create(
  2752. self.repo.path,
  2753. b"tryme",
  2754. b"foo <foo@bar.com>",
  2755. b"bar",
  2756. annotated=True,
  2757. sign=True,
  2758. )
  2759. tags = self.repo.refs.as_dict(b"refs/tags")
  2760. self.assertEqual(list(tags.keys()), [b"tryme"])
  2761. tag = self.repo[b"refs/tags/tryme"]
  2762. self.assertIsInstance(tag, Tag)
  2763. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2764. self.assertEqual(b"bar\n", tag.message)
  2765. self.assertRecentTimestamp(tag.tag_time)
  2766. tag = self.repo[b"refs/tags/tryme"]
  2767. assert isinstance(tag, Tag)
  2768. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2769. tag.verify()
  2770. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2771. self.import_non_default_key()
  2772. self.assertRaises(
  2773. gpg.errors.MissingSignatures,
  2774. tag.verify,
  2775. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  2776. )
  2777. assert tag.signature is not None
  2778. tag._chunked_text = [b"bad data", tag.signature]
  2779. self.assertRaises(
  2780. gpg.errors.BadSignatures,
  2781. tag.verify,
  2782. )
  2783. def test_non_default_key(self) -> None:
  2784. _c1, _c2, c3 = build_commit_graph(
  2785. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2786. )
  2787. self.repo.refs[b"HEAD"] = c3.id
  2788. cfg = self.repo.get_config()
  2789. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2790. self.import_non_default_key()
  2791. porcelain.tag_create(
  2792. self.repo.path,
  2793. b"tryme",
  2794. b"foo <foo@bar.com>",
  2795. b"bar",
  2796. annotated=True,
  2797. sign=True,
  2798. )
  2799. tags = self.repo.refs.as_dict(b"refs/tags")
  2800. self.assertEqual(list(tags.keys()), [b"tryme"])
  2801. tag = self.repo[b"refs/tags/tryme"]
  2802. self.assertIsInstance(tag, Tag)
  2803. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2804. self.assertEqual(b"bar\n", tag.message)
  2805. self.assertRecentTimestamp(tag.tag_time)
  2806. tag = self.repo[b"refs/tags/tryme"]
  2807. assert isinstance(tag, Tag)
  2808. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2809. tag.verify()
  2810. def test_sign_uses_config_signingkey(self) -> None:
  2811. """Test that sign=True uses user.signingKey from config."""
  2812. _c1, _c2, c3 = build_commit_graph(
  2813. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2814. )
  2815. self.repo.refs[b"HEAD"] = c3.id
  2816. # Set up user.signingKey in config
  2817. cfg = self.repo.get_config()
  2818. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2819. cfg.write_to_path()
  2820. self.import_default_key()
  2821. # Create tag with sign=True (should use signingKey from config)
  2822. porcelain.tag_create(
  2823. self.repo.path,
  2824. b"signed-tag",
  2825. b"foo <foo@bar.com>",
  2826. b"Tag with configured key",
  2827. annotated=True,
  2828. sign=True, # This should read user.signingKey from config
  2829. )
  2830. tags = self.repo.refs.as_dict(b"refs/tags")
  2831. self.assertEqual(list(tags.keys()), [b"signed-tag"])
  2832. tag = self.repo[b"refs/tags/signed-tag"]
  2833. self.assertIsInstance(tag, Tag)
  2834. # Verify the tag is signed with the configured key
  2835. tag.verify()
  2836. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2837. def test_tag_gpg_sign_config_enabled(self) -> None:
  2838. """Test that tag.gpgSign=true automatically signs tags."""
  2839. _c1, _c2, c3 = build_commit_graph(
  2840. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2841. )
  2842. self.repo.refs[b"HEAD"] = c3.id
  2843. # Set up user.signingKey and tag.gpgSign in config
  2844. cfg = self.repo.get_config()
  2845. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2846. cfg.set(("tag",), "gpgSign", True)
  2847. cfg.write_to_path()
  2848. self.import_default_key()
  2849. # Create tag without explicit sign parameter (should auto-sign due to config)
  2850. porcelain.tag_create(
  2851. self.repo.path,
  2852. b"auto-signed-tag",
  2853. b"foo <foo@bar.com>",
  2854. b"Auto-signed tag",
  2855. annotated=True,
  2856. # No sign parameter - should use tag.gpgSign config
  2857. )
  2858. tags = self.repo.refs.as_dict(b"refs/tags")
  2859. self.assertEqual(list(tags.keys()), [b"auto-signed-tag"])
  2860. tag = self.repo[b"refs/tags/auto-signed-tag"]
  2861. self.assertIsInstance(tag, Tag)
  2862. # Verify the tag is signed due to config
  2863. tag.verify()
  2864. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2865. def test_tag_gpg_sign_config_disabled(self) -> None:
  2866. """Test that tag.gpgSign=false does not sign tags."""
  2867. _c1, _c2, c3 = build_commit_graph(
  2868. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2869. )
  2870. self.repo.refs[b"HEAD"] = c3.id
  2871. # Set up user.signingKey and tag.gpgSign=false in config
  2872. cfg = self.repo.get_config()
  2873. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2874. cfg.set(("tag",), "gpgSign", False)
  2875. cfg.write_to_path()
  2876. self.import_default_key()
  2877. # Create tag without explicit sign parameter (should not sign)
  2878. porcelain.tag_create(
  2879. self.repo.path,
  2880. b"unsigned-tag",
  2881. b"foo <foo@bar.com>",
  2882. b"Unsigned tag",
  2883. annotated=True,
  2884. # No sign parameter - should use tag.gpgSign=false config
  2885. )
  2886. tags = self.repo.refs.as_dict(b"refs/tags")
  2887. self.assertEqual(list(tags.keys()), [b"unsigned-tag"])
  2888. tag = self.repo[b"refs/tags/unsigned-tag"]
  2889. self.assertIsInstance(tag, Tag)
  2890. # Verify the tag is not signed
  2891. self.assertIsNone(tag._signature)
  2892. def test_tag_gpg_sign_config_no_signing_key(self) -> None:
  2893. """Test that tag.gpgSign=true works without user.signingKey (uses default)."""
  2894. _c1, _c2, c3 = build_commit_graph(
  2895. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2896. )
  2897. self.repo.refs[b"HEAD"] = c3.id
  2898. # Set up tag.gpgSign but no user.signingKey
  2899. cfg = self.repo.get_config()
  2900. cfg.set(("tag",), "gpgSign", True)
  2901. cfg.write_to_path()
  2902. self.import_default_key()
  2903. # Create tag without explicit sign parameter (should auto-sign with default key)
  2904. porcelain.tag_create(
  2905. self.repo.path,
  2906. b"default-signed-tag",
  2907. b"foo <foo@bar.com>",
  2908. b"Default signed tag",
  2909. annotated=True,
  2910. # No sign parameter - should use tag.gpgSign config with default key
  2911. )
  2912. tags = self.repo.refs.as_dict(b"refs/tags")
  2913. self.assertEqual(list(tags.keys()), [b"default-signed-tag"])
  2914. tag = self.repo[b"refs/tags/default-signed-tag"]
  2915. self.assertIsInstance(tag, Tag)
  2916. # Verify the tag is signed with default key
  2917. tag.verify()
  2918. def test_explicit_sign_overrides_config(self) -> None:
  2919. """Test that explicit sign parameter overrides tag.gpgSign config."""
  2920. _c1, _c2, c3 = build_commit_graph(
  2921. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2922. )
  2923. self.repo.refs[b"HEAD"] = c3.id
  2924. # Set up tag.gpgSign=false but explicitly pass sign=True
  2925. cfg = self.repo.get_config()
  2926. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2927. cfg.set(("tag",), "gpgSign", False)
  2928. cfg.write_to_path()
  2929. self.import_default_key()
  2930. # Create tag with explicit sign=True (should override config)
  2931. porcelain.tag_create(
  2932. self.repo.path,
  2933. b"explicit-signed-tag",
  2934. b"foo <foo@bar.com>",
  2935. b"Explicitly signed tag",
  2936. annotated=True,
  2937. sign=True, # This should override tag.gpgSign=false
  2938. )
  2939. tags = self.repo.refs.as_dict(b"refs/tags")
  2940. self.assertEqual(list(tags.keys()), [b"explicit-signed-tag"])
  2941. tag = self.repo[b"refs/tags/explicit-signed-tag"]
  2942. self.assertIsInstance(tag, Tag)
  2943. # Verify the tag is signed despite config=false
  2944. tag.verify()
  2945. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2946. def test_explicit_false_disables_tag_signing(self) -> None:
  2947. """Test that explicit sign=False disables signing even with config=true."""
  2948. _c1, _c2, c3 = build_commit_graph(
  2949. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2950. )
  2951. self.repo.refs[b"HEAD"] = c3.id
  2952. # Set up tag.gpgSign=true but explicitly pass sign=False
  2953. cfg = self.repo.get_config()
  2954. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2955. cfg.set(("tag",), "gpgSign", True)
  2956. cfg.write_to_path()
  2957. self.import_default_key()
  2958. # Create tag with explicit sign=False (should disable signing)
  2959. porcelain.tag_create(
  2960. self.repo.path,
  2961. b"explicit-unsigned-tag",
  2962. b"foo <foo@bar.com>",
  2963. b"Explicitly unsigned tag",
  2964. annotated=True,
  2965. sign=False, # This should override tag.gpgSign=true
  2966. )
  2967. tags = self.repo.refs.as_dict(b"refs/tags")
  2968. self.assertEqual(list(tags.keys()), [b"explicit-unsigned-tag"])
  2969. tag = self.repo[b"refs/tags/explicit-unsigned-tag"]
  2970. self.assertIsInstance(tag, Tag)
  2971. # Verify the tag is NOT signed despite config=true
  2972. self.assertIsNone(tag._signature)
  2973. class TagCreateTests(PorcelainTestCase):
  2974. def test_annotated(self) -> None:
  2975. _c1, _c2, c3 = build_commit_graph(
  2976. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2977. )
  2978. self.repo.refs[b"HEAD"] = c3.id
  2979. porcelain.tag_create(
  2980. self.repo.path,
  2981. b"tryme",
  2982. b"foo <foo@bar.com>",
  2983. b"bar",
  2984. annotated=True,
  2985. )
  2986. tags = self.repo.refs.as_dict(b"refs/tags")
  2987. self.assertEqual(list(tags.keys()), [b"tryme"])
  2988. tag = self.repo[b"refs/tags/tryme"]
  2989. self.assertIsInstance(tag, Tag)
  2990. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2991. self.assertEqual(b"bar\n", tag.message)
  2992. self.assertRecentTimestamp(tag.tag_time)
  2993. def test_unannotated(self) -> None:
  2994. _c1, _c2, c3 = build_commit_graph(
  2995. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2996. )
  2997. self.repo.refs[b"HEAD"] = c3.id
  2998. porcelain.tag_create(self.repo.path, b"tryme", annotated=False)
  2999. tags = self.repo.refs.as_dict(b"refs/tags")
  3000. self.assertEqual(list(tags.keys()), [b"tryme"])
  3001. self.repo[b"refs/tags/tryme"]
  3002. self.assertEqual(list(tags.values()), [self.repo.head()])
  3003. def test_unannotated_unicode(self) -> None:
  3004. _c1, _c2, c3 = build_commit_graph(
  3005. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  3006. )
  3007. self.repo.refs[b"HEAD"] = c3.id
  3008. porcelain.tag_create(self.repo.path, "tryme", annotated=False)
  3009. tags = self.repo.refs.as_dict(b"refs/tags")
  3010. self.assertEqual(list(tags.keys()), [b"tryme"])
  3011. self.repo[b"refs/tags/tryme"]
  3012. self.assertEqual(list(tags.values()), [self.repo.head()])
  3013. class TagListTests(PorcelainTestCase):
  3014. def test_empty(self) -> None:
  3015. tags = porcelain.tag_list(self.repo.path)
  3016. self.assertEqual([], tags)
  3017. def test_simple(self) -> None:
  3018. self.repo.refs[b"refs/tags/foo"] = b"aa" * 20
  3019. self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20
  3020. tags = porcelain.tag_list(self.repo.path)
  3021. self.assertEqual([b"bar/bla", b"foo"], tags)
  3022. class TagDeleteTests(PorcelainTestCase):
  3023. def test_simple(self) -> None:
  3024. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3025. self.repo[b"HEAD"] = c1.id
  3026. porcelain.tag_create(self.repo, b"foo")
  3027. self.assertIn(b"foo", porcelain.tag_list(self.repo))
  3028. porcelain.tag_delete(self.repo, b"foo")
  3029. self.assertNotIn(b"foo", porcelain.tag_list(self.repo))
  3030. class ResetTests(PorcelainTestCase):
  3031. def test_hard_head(self) -> None:
  3032. fullpath = os.path.join(self.repo.path, "foo")
  3033. with open(fullpath, "w") as f:
  3034. f.write("BAR")
  3035. porcelain.add(self.repo.path, paths=[fullpath])
  3036. porcelain.commit(
  3037. self.repo.path,
  3038. message=b"Some message",
  3039. committer=b"Jane <jane@example.com>",
  3040. author=b"John <john@example.com>",
  3041. )
  3042. with open(os.path.join(self.repo.path, "foo"), "wb") as f:
  3043. f.write(b"OOH")
  3044. porcelain.reset(self.repo, "hard", b"HEAD")
  3045. index = self.repo.open_index()
  3046. changes = list(
  3047. tree_changes(
  3048. self.repo.object_store,
  3049. index.commit(self.repo.object_store),
  3050. self.repo[b"HEAD"].tree,
  3051. )
  3052. )
  3053. self.assertEqual([], changes)
  3054. def test_hard_commit(self) -> None:
  3055. fullpath = os.path.join(self.repo.path, "foo")
  3056. with open(fullpath, "w") as f:
  3057. f.write("BAR")
  3058. porcelain.add(self.repo.path, paths=[fullpath])
  3059. sha = porcelain.commit(
  3060. self.repo.path,
  3061. message=b"Some message",
  3062. committer=b"Jane <jane@example.com>",
  3063. author=b"John <john@example.com>",
  3064. )
  3065. with open(fullpath, "wb") as f:
  3066. f.write(b"BAZ")
  3067. porcelain.add(self.repo.path, paths=[fullpath])
  3068. porcelain.commit(
  3069. self.repo.path,
  3070. message=b"Some other message",
  3071. committer=b"Jane <jane@example.com>",
  3072. author=b"John <john@example.com>",
  3073. )
  3074. porcelain.reset(self.repo, "hard", sha)
  3075. index = self.repo.open_index()
  3076. changes = list(
  3077. tree_changes(
  3078. self.repo.object_store,
  3079. index.commit(self.repo.object_store),
  3080. self.repo[sha].tree,
  3081. )
  3082. )
  3083. self.assertEqual([], changes)
  3084. def test_hard_commit_short_hash(self) -> None:
  3085. fullpath = os.path.join(self.repo.path, "foo")
  3086. with open(fullpath, "w") as f:
  3087. f.write("BAR")
  3088. porcelain.add(self.repo.path, paths=[fullpath])
  3089. sha = porcelain.commit(
  3090. self.repo.path,
  3091. message=b"Some message",
  3092. committer=b"Jane <jane@example.com>",
  3093. author=b"John <john@example.com>",
  3094. )
  3095. with open(fullpath, "wb") as f:
  3096. f.write(b"BAZ")
  3097. porcelain.add(self.repo.path, paths=[fullpath])
  3098. porcelain.commit(
  3099. self.repo.path,
  3100. message=b"Some other message",
  3101. committer=b"Jane <jane@example.com>",
  3102. author=b"John <john@example.com>",
  3103. )
  3104. # Test with short hash (7 characters)
  3105. short_sha = sha[:7].decode("ascii")
  3106. porcelain.reset(self.repo, "hard", short_sha)
  3107. index = self.repo.open_index()
  3108. changes = list(
  3109. tree_changes(
  3110. self.repo.object_store,
  3111. index.commit(self.repo.object_store),
  3112. self.repo[sha].tree,
  3113. )
  3114. )
  3115. self.assertEqual([], changes)
  3116. def test_hard_deletes_untracked_files(self) -> None:
  3117. """Test that reset --hard deletes files that don't exist in target tree."""
  3118. # Create and commit a file
  3119. fullpath = os.path.join(self.repo.path, "foo")
  3120. with open(fullpath, "w") as f:
  3121. f.write("BAR")
  3122. porcelain.add(self.repo.path, paths=[fullpath])
  3123. sha1 = porcelain.commit(
  3124. self.repo.path,
  3125. message=b"First commit",
  3126. committer=b"Jane <jane@example.com>",
  3127. author=b"John <john@example.com>",
  3128. )
  3129. # Create another file and commit
  3130. fullpath2 = os.path.join(self.repo.path, "bar")
  3131. with open(fullpath2, "w") as f:
  3132. f.write("BAZ")
  3133. porcelain.add(self.repo.path, paths=[fullpath2])
  3134. porcelain.commit(
  3135. self.repo.path,
  3136. message=b"Second commit",
  3137. committer=b"Jane <jane@example.com>",
  3138. author=b"John <john@example.com>",
  3139. )
  3140. # Reset hard to first commit - this should delete 'bar'
  3141. porcelain.reset(self.repo, "hard", sha1)
  3142. # Check that 'foo' still exists and 'bar' is deleted
  3143. self.assertTrue(os.path.exists(fullpath))
  3144. self.assertFalse(os.path.exists(fullpath2))
  3145. # Check index matches first commit
  3146. index = self.repo.open_index()
  3147. self.assertIn(b"foo", index)
  3148. self.assertNotIn(b"bar", index)
  3149. def test_hard_deletes_files_in_subdirs(self) -> None:
  3150. """Test that reset --hard deletes files in subdirectories."""
  3151. # Create and commit files in subdirectory
  3152. subdir = os.path.join(self.repo.path, "subdir")
  3153. os.makedirs(subdir)
  3154. file1 = os.path.join(subdir, "file1")
  3155. file2 = os.path.join(subdir, "file2")
  3156. with open(file1, "w") as f:
  3157. f.write("content1")
  3158. with open(file2, "w") as f:
  3159. f.write("content2")
  3160. porcelain.add(self.repo.path, paths=[file1, file2])
  3161. porcelain.commit(
  3162. self.repo.path,
  3163. message=b"First commit",
  3164. committer=b"Jane <jane@example.com>",
  3165. author=b"John <john@example.com>",
  3166. )
  3167. # Remove one file from subdirectory and commit
  3168. porcelain.rm(self.repo.path, paths=[file2])
  3169. sha2 = porcelain.commit(
  3170. self.repo.path,
  3171. message=b"Remove file2",
  3172. committer=b"Jane <jane@example.com>",
  3173. author=b"John <john@example.com>",
  3174. )
  3175. # Create file2 again (untracked)
  3176. with open(file2, "w") as f:
  3177. f.write("new content")
  3178. # Reset to commit that has file2 removed - untracked file2 should remain
  3179. porcelain.reset(self.repo, "hard", sha2)
  3180. self.assertTrue(os.path.exists(file1))
  3181. # Untracked files are not removed by reset --hard
  3182. self.assertTrue(os.path.exists(file2))
  3183. def test_hard_reset_to_remote_branch(self) -> None:
  3184. """Test reset --hard to remote branch deletes local files not in remote."""
  3185. # Create a file and commit
  3186. file1 = os.path.join(self.repo.path, "file1")
  3187. with open(file1, "w") as f:
  3188. f.write("content1")
  3189. porcelain.add(self.repo.path, paths=[file1])
  3190. sha1 = porcelain.commit(
  3191. self.repo.path,
  3192. message=b"Initial commit",
  3193. committer=b"Jane <jane@example.com>",
  3194. author=b"John <john@example.com>",
  3195. )
  3196. # Create a "remote" ref that doesn't have additional files
  3197. self.repo.refs[b"refs/remotes/origin/master"] = sha1
  3198. # Add another file locally and commit
  3199. file2 = os.path.join(self.repo.path, "file2")
  3200. with open(file2, "w") as f:
  3201. f.write("content2")
  3202. porcelain.add(self.repo.path, paths=[file2])
  3203. porcelain.commit(
  3204. self.repo.path,
  3205. message=b"Add file2",
  3206. committer=b"Jane <jane@example.com>",
  3207. author=b"John <john@example.com>",
  3208. )
  3209. # Both files should exist
  3210. self.assertTrue(os.path.exists(file1))
  3211. self.assertTrue(os.path.exists(file2))
  3212. # Reset to remote branch - should delete file2
  3213. porcelain.reset(self.repo, "hard", b"refs/remotes/origin/master")
  3214. # file1 should exist, file2 should be deleted
  3215. self.assertTrue(os.path.exists(file1))
  3216. self.assertFalse(os.path.exists(file2))
  3217. def test_mixed_reset(self) -> None:
  3218. # Create initial commit
  3219. fullpath = os.path.join(self.repo.path, "foo")
  3220. with open(fullpath, "w") as f:
  3221. f.write("BAR")
  3222. porcelain.add(self.repo.path, paths=[fullpath])
  3223. first_sha = porcelain.commit(
  3224. self.repo.path,
  3225. message=b"First commit",
  3226. committer=b"Jane <jane@example.com>",
  3227. author=b"John <john@example.com>",
  3228. )
  3229. # Make second commit with modified content
  3230. with open(fullpath, "w") as f:
  3231. f.write("BAZ")
  3232. porcelain.add(self.repo.path, paths=[fullpath])
  3233. porcelain.commit(
  3234. self.repo.path,
  3235. message=b"Second commit",
  3236. committer=b"Jane <jane@example.com>",
  3237. author=b"John <john@example.com>",
  3238. )
  3239. # Modify working tree without staging
  3240. with open(fullpath, "w") as f:
  3241. f.write("MODIFIED")
  3242. # Mixed reset to first commit
  3243. porcelain.reset(self.repo, "mixed", first_sha)
  3244. # Check that HEAD points to first commit
  3245. self.assertEqual(self.repo.head(), first_sha)
  3246. # Check that index matches first commit
  3247. index = self.repo.open_index()
  3248. changes = list(
  3249. tree_changes(
  3250. self.repo.object_store,
  3251. index.commit(self.repo.object_store),
  3252. self.repo[first_sha].tree,
  3253. )
  3254. )
  3255. self.assertEqual([], changes)
  3256. # Check that working tree is unchanged (still has "MODIFIED")
  3257. with open(fullpath) as f:
  3258. self.assertEqual(f.read(), "MODIFIED")
  3259. def test_soft_reset(self) -> None:
  3260. # Create initial commit
  3261. fullpath = os.path.join(self.repo.path, "foo")
  3262. with open(fullpath, "w") as f:
  3263. f.write("BAR")
  3264. porcelain.add(self.repo.path, paths=[fullpath])
  3265. first_sha = porcelain.commit(
  3266. self.repo.path,
  3267. message=b"First commit",
  3268. committer=b"Jane <jane@example.com>",
  3269. author=b"John <john@example.com>",
  3270. )
  3271. # Make second commit with modified content
  3272. with open(fullpath, "w") as f:
  3273. f.write("BAZ")
  3274. porcelain.add(self.repo.path, paths=[fullpath])
  3275. porcelain.commit(
  3276. self.repo.path,
  3277. message=b"Second commit",
  3278. committer=b"Jane <jane@example.com>",
  3279. author=b"John <john@example.com>",
  3280. )
  3281. # Stage a new change
  3282. with open(fullpath, "w") as f:
  3283. f.write("STAGED")
  3284. porcelain.add(self.repo.path, paths=[fullpath])
  3285. # Soft reset to first commit
  3286. porcelain.reset(self.repo, "soft", first_sha)
  3287. # Check that HEAD points to first commit
  3288. self.assertEqual(self.repo.head(), first_sha)
  3289. # Check that index still has the staged change (not reset)
  3290. index = self.repo.open_index()
  3291. # The index should still contain the staged content, not the first commit's content
  3292. self.assertIn(b"foo", index)
  3293. # Check that working tree is unchanged
  3294. with open(fullpath) as f:
  3295. self.assertEqual(f.read(), "STAGED")
  3296. class ResetFileTests(PorcelainTestCase):
  3297. def test_reset_modify_file_to_commit(self) -> None:
  3298. file = "foo"
  3299. full_path = os.path.join(self.repo.path, file)
  3300. with open(full_path, "w") as f:
  3301. f.write("hello")
  3302. porcelain.add(self.repo, paths=[full_path])
  3303. sha = porcelain.commit(
  3304. self.repo,
  3305. message=b"unitest",
  3306. committer=b"Jane <jane@example.com>",
  3307. author=b"John <john@example.com>",
  3308. )
  3309. with open(full_path, "a") as f:
  3310. f.write("something new")
  3311. porcelain.reset_file(self.repo, file, target=sha)
  3312. with open(full_path) as f:
  3313. self.assertEqual("hello", f.read())
  3314. def test_reset_remove_file_to_commit(self) -> None:
  3315. file = "foo"
  3316. full_path = os.path.join(self.repo.path, file)
  3317. with open(full_path, "w") as f:
  3318. f.write("hello")
  3319. porcelain.add(self.repo, paths=[full_path])
  3320. sha = porcelain.commit(
  3321. self.repo,
  3322. message=b"unitest",
  3323. committer=b"Jane <jane@example.com>",
  3324. author=b"John <john@example.com>",
  3325. )
  3326. os.remove(full_path)
  3327. porcelain.reset_file(self.repo, file, target=sha)
  3328. with open(full_path) as f:
  3329. self.assertEqual("hello", f.read())
  3330. def test_resetfile_with_dir(self) -> None:
  3331. os.mkdir(os.path.join(self.repo.path, "new_dir"))
  3332. full_path = os.path.join(self.repo.path, "new_dir", "foo")
  3333. with open(full_path, "w") as f:
  3334. f.write("hello")
  3335. porcelain.add(self.repo, paths=[full_path])
  3336. sha = porcelain.commit(
  3337. self.repo,
  3338. message=b"unitest",
  3339. committer=b"Jane <jane@example.com>",
  3340. author=b"John <john@example.com>",
  3341. )
  3342. with open(full_path, "a") as f:
  3343. f.write("something new")
  3344. porcelain.commit(
  3345. self.repo,
  3346. message=b"unitest 2",
  3347. committer=b"Jane <jane@example.com>",
  3348. author=b"John <john@example.com>",
  3349. )
  3350. porcelain.reset_file(self.repo, os.path.join("new_dir", "foo"), target=sha)
  3351. with open(full_path) as f:
  3352. self.assertEqual("hello", f.read())
  3353. def _commit_file_with_content(repo, filename, content):
  3354. file_path = os.path.join(repo.path, filename)
  3355. with open(file_path, "w") as f:
  3356. f.write(content)
  3357. porcelain.add(repo, paths=[file_path])
  3358. sha = porcelain.commit(
  3359. repo,
  3360. message=b"add " + filename.encode(),
  3361. committer=b"Jane <jane@example.com>",
  3362. author=b"John <john@example.com>",
  3363. )
  3364. return sha, file_path
  3365. class RevertTests(PorcelainTestCase):
  3366. def test_revert_simple(self) -> None:
  3367. # Create initial commit
  3368. fullpath = os.path.join(self.repo.path, "foo")
  3369. with open(fullpath, "w") as f:
  3370. f.write("initial content\n")
  3371. porcelain.add(self.repo.path, paths=[fullpath])
  3372. porcelain.commit(
  3373. self.repo.path,
  3374. message=b"Initial commit",
  3375. committer=b"Jane <jane@example.com>",
  3376. author=b"John <john@example.com>",
  3377. )
  3378. # Make a change
  3379. with open(fullpath, "w") as f:
  3380. f.write("modified content\n")
  3381. porcelain.add(self.repo.path, paths=[fullpath])
  3382. change_sha = porcelain.commit(
  3383. self.repo.path,
  3384. message=b"Change content",
  3385. committer=b"Jane <jane@example.com>",
  3386. author=b"John <john@example.com>",
  3387. )
  3388. # Revert the change
  3389. revert_sha = porcelain.revert(self.repo.path, commits=[change_sha])
  3390. # Check the file content is back to initial
  3391. with open(fullpath) as f:
  3392. self.assertEqual("initial content\n", f.read())
  3393. # Check the revert commit message
  3394. revert_commit = self.repo[revert_sha]
  3395. self.assertIn(b'Revert "Change content"', revert_commit.message)
  3396. self.assertIn(change_sha[:7], revert_commit.message)
  3397. def test_revert_multiple(self) -> None:
  3398. # Create initial commit
  3399. fullpath = os.path.join(self.repo.path, "foo")
  3400. with open(fullpath, "w") as f:
  3401. f.write("line1\n")
  3402. porcelain.add(self.repo.path, paths=[fullpath])
  3403. porcelain.commit(
  3404. self.repo.path,
  3405. message=b"Initial commit",
  3406. committer=b"Jane <jane@example.com>",
  3407. author=b"John <john@example.com>",
  3408. )
  3409. # Add line2
  3410. with open(fullpath, "a") as f:
  3411. f.write("line2\n")
  3412. porcelain.add(self.repo.path, paths=[fullpath])
  3413. commit1 = porcelain.commit(
  3414. self.repo.path,
  3415. message=b"Add line2",
  3416. committer=b"Jane <jane@example.com>",
  3417. author=b"John <john@example.com>",
  3418. )
  3419. # Add line3
  3420. with open(fullpath, "a") as f:
  3421. f.write("line3\n")
  3422. porcelain.add(self.repo.path, paths=[fullpath])
  3423. commit2 = porcelain.commit(
  3424. self.repo.path,
  3425. message=b"Add line3",
  3426. committer=b"Jane <jane@example.com>",
  3427. author=b"John <john@example.com>",
  3428. )
  3429. # Revert both commits (in reverse order)
  3430. porcelain.revert(self.repo.path, commits=[commit2, commit1])
  3431. # Check file is back to initial state
  3432. with open(fullpath) as f:
  3433. self.assertEqual("line1\n", f.read())
  3434. def test_revert_no_commit(self) -> None:
  3435. # Create initial commit
  3436. fullpath = os.path.join(self.repo.path, "foo")
  3437. with open(fullpath, "w") as f:
  3438. f.write("initial\n")
  3439. porcelain.add(self.repo.path, paths=[fullpath])
  3440. porcelain.commit(
  3441. self.repo.path,
  3442. message=b"Initial",
  3443. committer=b"Jane <jane@example.com>",
  3444. author=b"John <john@example.com>",
  3445. )
  3446. # Make a change
  3447. with open(fullpath, "w") as f:
  3448. f.write("changed\n")
  3449. porcelain.add(self.repo.path, paths=[fullpath])
  3450. change_sha = porcelain.commit(
  3451. self.repo.path,
  3452. message=b"Change",
  3453. committer=b"Jane <jane@example.com>",
  3454. author=b"John <john@example.com>",
  3455. )
  3456. # Revert with no_commit
  3457. result = porcelain.revert(self.repo.path, commits=[change_sha], no_commit=True)
  3458. # Should return None
  3459. self.assertIsNone(result)
  3460. # File should be reverted
  3461. with open(fullpath) as f:
  3462. self.assertEqual("initial\n", f.read())
  3463. # HEAD should still point to the change commit
  3464. self.assertEqual(self.repo.refs[b"HEAD"], change_sha)
  3465. def test_revert_custom_message(self) -> None:
  3466. # Create commits
  3467. fullpath = os.path.join(self.repo.path, "foo")
  3468. with open(fullpath, "w") as f:
  3469. f.write("initial\n")
  3470. porcelain.add(self.repo.path, paths=[fullpath])
  3471. porcelain.commit(
  3472. self.repo.path,
  3473. message=b"Initial",
  3474. committer=b"Jane <jane@example.com>",
  3475. author=b"John <john@example.com>",
  3476. )
  3477. with open(fullpath, "w") as f:
  3478. f.write("changed\n")
  3479. porcelain.add(self.repo.path, paths=[fullpath])
  3480. change_sha = porcelain.commit(
  3481. self.repo.path,
  3482. message=b"Change",
  3483. committer=b"Jane <jane@example.com>",
  3484. author=b"John <john@example.com>",
  3485. )
  3486. # Revert with custom message
  3487. custom_msg = "Custom revert message"
  3488. revert_sha = porcelain.revert(
  3489. self.repo.path, commits=[change_sha], message=custom_msg
  3490. )
  3491. # Check the message
  3492. revert_commit = self.repo[revert_sha]
  3493. self.assertEqual(custom_msg.encode("utf-8"), revert_commit.message)
  3494. def test_revert_no_parent(self) -> None:
  3495. # Try to revert the initial commit (no parent)
  3496. fullpath = os.path.join(self.repo.path, "foo")
  3497. with open(fullpath, "w") as f:
  3498. f.write("content\n")
  3499. porcelain.add(self.repo.path, paths=[fullpath])
  3500. initial_sha = porcelain.commit(
  3501. self.repo.path,
  3502. message=b"Initial",
  3503. committer=b"Jane <jane@example.com>",
  3504. author=b"John <john@example.com>",
  3505. )
  3506. # Should raise an error
  3507. with self.assertRaises(porcelain.Error) as cm:
  3508. porcelain.revert(self.repo.path, commits=[initial_sha])
  3509. self.assertIn("no parents", str(cm.exception))
  3510. class CheckoutTests(PorcelainTestCase):
  3511. def setUp(self) -> None:
  3512. super().setUp()
  3513. self._sha, self._foo_path = _commit_file_with_content(
  3514. self.repo, "foo", "hello\n"
  3515. )
  3516. porcelain.branch_create(self.repo, "uni")
  3517. def test_checkout_to_existing_branch(self) -> None:
  3518. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3519. porcelain.checkout(self.repo, b"uni")
  3520. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3521. def test_checkout_to_non_existing_branch(self) -> None:
  3522. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3523. with self.assertRaises(KeyError):
  3524. porcelain.checkout(self.repo, b"bob")
  3525. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3526. def test_checkout_to_branch_with_modified_files(self) -> None:
  3527. with open(self._foo_path, "a") as f:
  3528. f.write("new message\n")
  3529. porcelain.add(self.repo, paths=[self._foo_path])
  3530. status = list(porcelain.status(self.repo))
  3531. self.assertEqual(
  3532. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  3533. )
  3534. # The new checkout behavior prevents switching with staged changes
  3535. with self.assertRaises(porcelain.CheckoutError):
  3536. porcelain.checkout(self.repo, b"uni")
  3537. # Should still be on master
  3538. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3539. # Force checkout should work
  3540. porcelain.checkout(self.repo, b"uni", force=True)
  3541. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3542. def test_checkout_with_deleted_files(self) -> None:
  3543. porcelain.remove(self.repo.path, [os.path.join(self.repo.path, "foo")])
  3544. status = list(porcelain.status(self.repo))
  3545. self.assertEqual(
  3546. [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status
  3547. )
  3548. # The new checkout behavior prevents switching with staged deletions
  3549. with self.assertRaises(porcelain.CheckoutError):
  3550. porcelain.checkout(self.repo, b"uni")
  3551. # Should still be on master
  3552. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3553. # Force checkout should work
  3554. porcelain.checkout(self.repo, b"uni", force=True)
  3555. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3556. def test_checkout_to_branch_with_added_files(self) -> None:
  3557. file_path = os.path.join(self.repo.path, "bar")
  3558. with open(file_path, "w") as f:
  3559. f.write("bar content\n")
  3560. porcelain.add(self.repo, paths=[file_path])
  3561. status = list(porcelain.status(self.repo))
  3562. self.assertEqual(
  3563. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3564. )
  3565. # Both branches have file 'foo' checkout should be fine.
  3566. porcelain.checkout(self.repo, b"uni")
  3567. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3568. status = list(porcelain.status(self.repo))
  3569. self.assertEqual(
  3570. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3571. )
  3572. def test_checkout_to_branch_with_modified_file_not_present(self) -> None:
  3573. # Commit a new file that the other branch doesn't have.
  3574. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3575. # Modify the file the other branch doesn't have.
  3576. with open(nee_path, "a") as f:
  3577. f.write("bar content\n")
  3578. porcelain.add(self.repo, paths=[nee_path])
  3579. status = list(porcelain.status(self.repo))
  3580. self.assertEqual(
  3581. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3582. )
  3583. # Checkout should fail when there are staged changes that would be lost
  3584. # This matches Git's behavior to prevent data loss
  3585. from dulwich.errors import WorkingTreeModifiedError
  3586. with self.assertRaises(WorkingTreeModifiedError) as cm:
  3587. porcelain.checkout(self.repo, b"uni")
  3588. self.assertIn("nee", str(cm.exception))
  3589. # Should still be on master branch
  3590. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3591. # The staged changes should still be present
  3592. status = list(porcelain.status(self.repo))
  3593. self.assertEqual(
  3594. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3595. )
  3596. self.assertTrue(os.path.exists(nee_path))
  3597. # Force checkout should work and lose the changes
  3598. porcelain.checkout(self.repo, b"uni", force=True)
  3599. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3600. # Now the file should be gone
  3601. self.assertFalse(os.path.exists(nee_path))
  3602. def test_checkout_to_branch_with_modified_file_not_present_forced(self) -> None:
  3603. # Commit a new file that the other branch doesn't have.
  3604. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3605. # Modify the file the other branch doesn't have.
  3606. with open(nee_path, "a") as f:
  3607. f.write("bar content\n")
  3608. porcelain.add(self.repo, paths=[nee_path])
  3609. status = list(porcelain.status(self.repo))
  3610. self.assertEqual(
  3611. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3612. )
  3613. # 'uni' branch doesn't have 'nee' and it has been modified, but we force to reset the entire index.
  3614. porcelain.checkout(self.repo, b"uni", force=True)
  3615. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3616. status = list(porcelain.status(self.repo))
  3617. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3618. def test_checkout_to_branch_with_unstaged_files(self) -> None:
  3619. # Edit `foo`.
  3620. with open(self._foo_path, "a") as f:
  3621. f.write("new message")
  3622. status = list(porcelain.status(self.repo))
  3623. self.assertEqual(
  3624. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  3625. )
  3626. # The new checkout behavior prevents switching with unstaged changes
  3627. with self.assertRaises(porcelain.CheckoutError):
  3628. porcelain.checkout(self.repo, b"uni")
  3629. # Should still be on master
  3630. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3631. # Force checkout should work
  3632. porcelain.checkout(self.repo, b"uni", force=True)
  3633. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3634. def test_checkout_to_branch_with_untracked_files(self) -> None:
  3635. with open(os.path.join(self.repo.path, "neu"), "a") as f:
  3636. f.write("new message\n")
  3637. status = list(porcelain.status(self.repo))
  3638. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3639. porcelain.checkout(self.repo, b"uni")
  3640. status = list(porcelain.status(self.repo))
  3641. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3642. def test_checkout_to_branch_with_new_files(self) -> None:
  3643. porcelain.checkout(self.repo, b"uni")
  3644. sub_directory = os.path.join(self.repo.path, "sub1")
  3645. os.mkdir(sub_directory)
  3646. for index in range(5):
  3647. _commit_file_with_content(
  3648. self.repo, "new_file_" + str(index + 1), "Some content\n"
  3649. )
  3650. _commit_file_with_content(
  3651. self.repo,
  3652. os.path.join("sub1", "new_file_" + str(index + 10)),
  3653. "Good content\n",
  3654. )
  3655. status = list(porcelain.status(self.repo))
  3656. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3657. porcelain.checkout(self.repo, b"master")
  3658. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3659. status = list(porcelain.status(self.repo))
  3660. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3661. porcelain.checkout(self.repo, b"uni")
  3662. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3663. status = list(porcelain.status(self.repo))
  3664. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3665. def test_checkout_to_branch_with_file_in_sub_directory(self) -> None:
  3666. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3667. os.makedirs(sub_directory)
  3668. sub_directory_file = os.path.join(sub_directory, "neu")
  3669. with open(sub_directory_file, "w") as f:
  3670. f.write("new message\n")
  3671. porcelain.add(self.repo, paths=[sub_directory_file])
  3672. porcelain.commit(
  3673. self.repo,
  3674. message=b"add " + sub_directory_file.encode(),
  3675. committer=b"Jane <jane@example.com>",
  3676. author=b"John <john@example.com>",
  3677. )
  3678. status = list(porcelain.status(self.repo))
  3679. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3680. self.assertTrue(os.path.isdir(sub_directory))
  3681. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3682. porcelain.checkout(self.repo, b"uni")
  3683. status = list(porcelain.status(self.repo))
  3684. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3685. self.assertFalse(os.path.isdir(sub_directory))
  3686. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3687. porcelain.checkout(self.repo, b"master")
  3688. self.assertTrue(os.path.isdir(sub_directory))
  3689. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3690. def test_checkout_to_branch_with_multiple_files_in_sub_directory(self) -> None:
  3691. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3692. os.makedirs(sub_directory)
  3693. sub_directory_file_1 = os.path.join(sub_directory, "neu")
  3694. with open(sub_directory_file_1, "w") as f:
  3695. f.write("new message\n")
  3696. sub_directory_file_2 = os.path.join(sub_directory, "gus")
  3697. with open(sub_directory_file_2, "w") as f:
  3698. f.write("alternative message\n")
  3699. porcelain.add(self.repo, paths=[sub_directory_file_1, sub_directory_file_2])
  3700. porcelain.commit(
  3701. self.repo,
  3702. message=b"add files neu and gus.",
  3703. committer=b"Jane <jane@example.com>",
  3704. author=b"John <john@example.com>",
  3705. )
  3706. status = list(porcelain.status(self.repo))
  3707. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3708. self.assertTrue(os.path.isdir(sub_directory))
  3709. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3710. porcelain.checkout(self.repo, b"uni")
  3711. status = list(porcelain.status(self.repo))
  3712. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3713. self.assertFalse(os.path.isdir(sub_directory))
  3714. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3715. def _commit_something_wrong(self):
  3716. with open(self._foo_path, "a") as f:
  3717. f.write("something wrong")
  3718. porcelain.add(self.repo, paths=[self._foo_path])
  3719. return porcelain.commit(
  3720. self.repo,
  3721. message=b"I may added something wrong",
  3722. committer=b"Jane <jane@example.com>",
  3723. author=b"John <john@example.com>",
  3724. )
  3725. def test_checkout_to_commit_sha(self) -> None:
  3726. self._commit_something_wrong()
  3727. porcelain.checkout(self.repo, self._sha)
  3728. self.assertEqual(self._sha, self.repo.head())
  3729. def test_checkout_to_head(self) -> None:
  3730. new_sha = self._commit_something_wrong()
  3731. porcelain.checkout(self.repo, b"HEAD")
  3732. self.assertEqual(new_sha, self.repo.head())
  3733. def _checkout_remote_branch(self):
  3734. errstream = BytesIO()
  3735. outstream = BytesIO()
  3736. porcelain.commit(
  3737. repo=self.repo.path,
  3738. message=b"init",
  3739. author=b"author <email>",
  3740. committer=b"committer <email>",
  3741. )
  3742. # Setup target repo cloned from temp test repo
  3743. clone_path = tempfile.mkdtemp()
  3744. self.addCleanup(shutil.rmtree, clone_path)
  3745. target_repo = porcelain.clone(
  3746. self.repo.path, target=clone_path, errstream=errstream
  3747. )
  3748. self.addCleanup(target_repo.close)
  3749. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  3750. # create a second file to be pushed back to origin
  3751. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3752. os.close(handle)
  3753. porcelain.add(repo=clone_path, paths=[fullpath])
  3754. porcelain.commit(
  3755. repo=clone_path,
  3756. message=b"push",
  3757. author=b"author <email>",
  3758. committer=b"committer <email>",
  3759. )
  3760. # Setup a non-checked out branch in the remote
  3761. refs_path = b"refs/heads/foo"
  3762. new_id = self.repo[b"HEAD"].id
  3763. self.assertNotEqual(new_id, ZERO_SHA)
  3764. self.repo.refs[refs_path] = new_id
  3765. # Push to the remote
  3766. porcelain.push(
  3767. clone_path,
  3768. "origin",
  3769. b"HEAD:" + refs_path,
  3770. outstream=outstream,
  3771. errstream=errstream,
  3772. )
  3773. self.assertEqual(
  3774. target_repo.refs[b"refs/remotes/origin/foo"],
  3775. target_repo.refs[b"HEAD"],
  3776. )
  3777. # The new checkout behavior treats origin/foo as a ref and creates detached HEAD
  3778. porcelain.checkout(target_repo, b"origin/foo")
  3779. original_id = target_repo[b"HEAD"].id
  3780. uni_id = target_repo[b"refs/remotes/origin/uni"].id
  3781. # Should be in detached HEAD state
  3782. with self.assertRaises((ValueError, IndexError)):
  3783. porcelain.active_branch(target_repo)
  3784. expected_refs = {
  3785. b"HEAD": original_id,
  3786. b"refs/heads/master": original_id,
  3787. # No local foo branch is created anymore
  3788. b"refs/remotes/origin/foo": original_id,
  3789. b"refs/remotes/origin/uni": uni_id,
  3790. b"refs/remotes/origin/HEAD": new_id,
  3791. b"refs/remotes/origin/master": new_id,
  3792. }
  3793. self.assertEqual(expected_refs, target_repo.get_refs())
  3794. return target_repo
  3795. def test_checkout_remote_branch(self) -> None:
  3796. repo = self._checkout_remote_branch()
  3797. repo.close()
  3798. def test_checkout_remote_branch_then_master_then_remote_branch_again(self) -> None:
  3799. target_repo = self._checkout_remote_branch()
  3800. # Should be in detached HEAD state
  3801. with self.assertRaises((ValueError, IndexError)):
  3802. porcelain.active_branch(target_repo)
  3803. # Save the commit SHA before adding bar
  3804. detached_commit_sha, _ = _commit_file_with_content(
  3805. target_repo, "bar", "something\n"
  3806. )
  3807. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3808. porcelain.checkout(target_repo, b"master")
  3809. self.assertEqual(b"master", porcelain.active_branch(target_repo))
  3810. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3811. # Going back to origin/foo won't have bar because the commit was made in detached state
  3812. porcelain.checkout(target_repo, b"origin/foo")
  3813. # Should be in detached HEAD state again
  3814. with self.assertRaises((ValueError, IndexError)):
  3815. porcelain.active_branch(target_repo)
  3816. # bar is NOT there because we're back at the original origin/foo commit
  3817. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3818. # But we can checkout the specific commit to get bar back
  3819. porcelain.checkout(target_repo, detached_commit_sha.decode())
  3820. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3821. target_repo.close()
  3822. def test_checkout_new_branch_from_remote_sets_tracking(self) -> None:
  3823. # Create a "remote" repository
  3824. remote_path = tempfile.mkdtemp()
  3825. self.addCleanup(shutil.rmtree, remote_path)
  3826. remote_repo = porcelain.init(remote_path)
  3827. # Add a commit to the remote
  3828. remote_sha, _ = _commit_file_with_content(
  3829. remote_repo, "bar", "remote content\n"
  3830. )
  3831. # Clone the remote repository
  3832. target_path = tempfile.mkdtemp()
  3833. self.addCleanup(shutil.rmtree, target_path)
  3834. target_repo = porcelain.clone(remote_path, target_path)
  3835. self.addCleanup(target_repo.close)
  3836. # Create a remote tracking branch reference
  3837. remote_branch_ref = b"refs/remotes/origin/feature"
  3838. target_repo.refs[remote_branch_ref] = remote_sha
  3839. # Checkout a new branch from the remote branch
  3840. porcelain.checkout(target_repo, remote_branch_ref, new_branch=b"local-feature")
  3841. # Verify the branch was created and is active
  3842. self.assertEqual(b"local-feature", porcelain.active_branch(target_repo))
  3843. # Verify tracking configuration was set
  3844. config = target_repo.get_config()
  3845. self.assertEqual(
  3846. b"origin", config.get((b"branch", b"local-feature"), b"remote")
  3847. )
  3848. self.assertEqual(
  3849. b"refs/heads/feature", config.get((b"branch", b"local-feature"), b"merge")
  3850. )
  3851. target_repo.close()
  3852. remote_repo.close()
  3853. class RestoreTests(PorcelainTestCase):
  3854. """Tests for the restore command."""
  3855. def setUp(self) -> None:
  3856. super().setUp()
  3857. self._sha, self._foo_path = _commit_file_with_content(
  3858. self.repo, "foo", "original\n"
  3859. )
  3860. def test_restore_worktree_from_index(self) -> None:
  3861. # Modify the working tree file
  3862. with open(self._foo_path, "w") as f:
  3863. f.write("modified\n")
  3864. # Restore from index (should restore to original)
  3865. porcelain.restore(self.repo, paths=["foo"])
  3866. with open(self._foo_path) as f:
  3867. content = f.read()
  3868. self.assertEqual("original\n", content)
  3869. def test_restore_worktree_from_head(self) -> None:
  3870. # Modify and stage the file
  3871. with open(self._foo_path, "w") as f:
  3872. f.write("staged\n")
  3873. porcelain.add(self.repo, paths=[self._foo_path])
  3874. # Now modify it again in worktree
  3875. with open(self._foo_path, "w") as f:
  3876. f.write("worktree\n")
  3877. # Restore from HEAD (should restore to original, not staged)
  3878. porcelain.restore(self.repo, paths=["foo"], source="HEAD")
  3879. with open(self._foo_path) as f:
  3880. content = f.read()
  3881. self.assertEqual("original\n", content)
  3882. def test_restore_staged_from_head(self) -> None:
  3883. # Modify and stage the file
  3884. with open(self._foo_path, "w") as f:
  3885. f.write("staged\n")
  3886. porcelain.add(self.repo, paths=[self._foo_path])
  3887. # Verify it's staged
  3888. status = list(porcelain.status(self.repo))
  3889. self.assertEqual(
  3890. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  3891. )
  3892. # Restore staged from HEAD
  3893. porcelain.restore(self.repo, paths=["foo"], staged=True, worktree=False)
  3894. # Verify it's no longer staged
  3895. status = list(porcelain.status(self.repo))
  3896. # Now it should show as unstaged modification
  3897. self.assertEqual(
  3898. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  3899. )
  3900. def test_restore_both_staged_and_worktree(self) -> None:
  3901. # Modify and stage the file
  3902. with open(self._foo_path, "w") as f:
  3903. f.write("staged\n")
  3904. porcelain.add(self.repo, paths=[self._foo_path])
  3905. # Now modify it again in worktree
  3906. with open(self._foo_path, "w") as f:
  3907. f.write("worktree\n")
  3908. # Restore both from HEAD
  3909. porcelain.restore(self.repo, paths=["foo"], staged=True, worktree=True)
  3910. # Verify content is restored
  3911. with open(self._foo_path) as f:
  3912. content = f.read()
  3913. self.assertEqual("original\n", content)
  3914. # Verify nothing is staged
  3915. status = list(porcelain.status(self.repo))
  3916. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3917. def test_restore_nonexistent_path(self) -> None:
  3918. with self.assertRaises(porcelain.CheckoutError):
  3919. porcelain.restore(self.repo, paths=["nonexistent"])
  3920. class SwitchTests(PorcelainTestCase):
  3921. """Tests for the switch command."""
  3922. def setUp(self) -> None:
  3923. super().setUp()
  3924. self._sha, self._foo_path = _commit_file_with_content(
  3925. self.repo, "foo", "hello\n"
  3926. )
  3927. porcelain.branch_create(self.repo, "dev")
  3928. def test_switch_to_existing_branch(self) -> None:
  3929. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3930. porcelain.switch(self.repo, "dev")
  3931. self.assertEqual(b"dev", porcelain.active_branch(self.repo))
  3932. def test_switch_to_non_existing_branch(self) -> None:
  3933. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3934. with self.assertRaises(KeyError):
  3935. porcelain.switch(self.repo, "nonexistent")
  3936. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3937. def test_switch_with_create(self) -> None:
  3938. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3939. porcelain.switch(self.repo, "master", create="feature")
  3940. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3941. def test_switch_with_detach(self) -> None:
  3942. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3943. porcelain.switch(self.repo, self._sha.decode(), detach=True)
  3944. # In detached HEAD state, active_branch raises IndexError
  3945. with self.assertRaises(IndexError):
  3946. porcelain.active_branch(self.repo)
  3947. def test_switch_with_uncommitted_changes(self) -> None:
  3948. # Modify the file
  3949. with open(self._foo_path, "a") as f:
  3950. f.write("new content\n")
  3951. porcelain.add(self.repo, paths=[self._foo_path])
  3952. # Switch should fail due to uncommitted changes
  3953. with self.assertRaises(porcelain.CheckoutError):
  3954. porcelain.switch(self.repo, "dev")
  3955. # Should still be on master
  3956. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3957. def test_switch_with_force(self) -> None:
  3958. # Modify the file
  3959. with open(self._foo_path, "a") as f:
  3960. f.write("new content\n")
  3961. porcelain.add(self.repo, paths=[self._foo_path])
  3962. # Force switch should work
  3963. porcelain.switch(self.repo, "dev", force=True)
  3964. self.assertEqual(b"dev", porcelain.active_branch(self.repo))
  3965. def test_switch_to_commit_without_detach(self) -> None:
  3966. # Switching to a commit SHA without --detach should fail
  3967. with self.assertRaises(porcelain.CheckoutError):
  3968. porcelain.switch(self.repo, self._sha.decode())
  3969. class GeneralCheckoutTests(PorcelainTestCase):
  3970. """Tests for the general checkout function that handles branches, tags, and commits."""
  3971. def setUp(self) -> None:
  3972. super().setUp()
  3973. # Create initial commit
  3974. self._sha1, self._foo_path = _commit_file_with_content(
  3975. self.repo, "foo", "initial content\n"
  3976. )
  3977. # Create a branch
  3978. porcelain.branch_create(self.repo, "feature")
  3979. # Create another commit on master
  3980. self._sha2, self._bar_path = _commit_file_with_content(
  3981. self.repo, "bar", "bar content\n"
  3982. )
  3983. # Create a tag
  3984. porcelain.tag_create(self.repo, "v1.0", objectish=self._sha1)
  3985. def test_checkout_branch(self) -> None:
  3986. """Test checking out a branch."""
  3987. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3988. # Checkout feature branch
  3989. porcelain.checkout(self.repo, "feature")
  3990. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3991. # File 'bar' should not exist in feature branch
  3992. self.assertFalse(os.path.exists(self._bar_path))
  3993. # Go back to master
  3994. porcelain.checkout(self.repo, "master")
  3995. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3996. # File 'bar' should exist again
  3997. self.assertTrue(os.path.exists(self._bar_path))
  3998. def test_checkout_commit(self) -> None:
  3999. """Test checking out a specific commit (detached HEAD)."""
  4000. # Checkout first commit by SHA
  4001. porcelain.checkout(self.repo, self._sha1.decode("ascii"))
  4002. # Should be in detached HEAD state - active_branch raises IndexError
  4003. with self.assertRaises((ValueError, IndexError)):
  4004. porcelain.active_branch(self.repo)
  4005. # File 'bar' should not exist
  4006. self.assertFalse(os.path.exists(self._bar_path))
  4007. # HEAD should point to the commit
  4008. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  4009. def test_checkout_tag(self) -> None:
  4010. """Test checking out a tag (detached HEAD)."""
  4011. # Checkout tag
  4012. porcelain.checkout(self.repo, "v1.0")
  4013. # Should be in detached HEAD state - active_branch raises IndexError
  4014. with self.assertRaises((ValueError, IndexError)):
  4015. porcelain.active_branch(self.repo)
  4016. # File 'bar' should not exist (tag points to first commit)
  4017. self.assertFalse(os.path.exists(self._bar_path))
  4018. # HEAD should point to the tagged commit
  4019. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  4020. def test_checkout_new_branch(self) -> None:
  4021. """Test creating a new branch during checkout (like git checkout -b)."""
  4022. # Create and checkout new branch from current HEAD
  4023. porcelain.checkout(self.repo, "master", new_branch="new-feature")
  4024. self.assertEqual(b"new-feature", porcelain.active_branch(self.repo))
  4025. self.assertTrue(os.path.exists(self._bar_path))
  4026. # Create and checkout new branch from specific commit
  4027. porcelain.checkout(self.repo, self._sha1.decode("ascii"), new_branch="from-old")
  4028. self.assertEqual(b"from-old", porcelain.active_branch(self.repo))
  4029. self.assertFalse(os.path.exists(self._bar_path))
  4030. def test_checkout_with_uncommitted_changes(self) -> None:
  4031. """Test checkout behavior with uncommitted changes."""
  4032. # Modify a file
  4033. with open(self._foo_path, "w") as f:
  4034. f.write("modified content\n")
  4035. # Should raise error when trying to checkout
  4036. with self.assertRaises(porcelain.CheckoutError) as cm:
  4037. porcelain.checkout(self.repo, "feature")
  4038. self.assertIn("local changes", str(cm.exception))
  4039. self.assertIn("foo", str(cm.exception))
  4040. # Should still be on master
  4041. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4042. def test_checkout_force(self) -> None:
  4043. """Test forced checkout discards local changes for files that differ between branches."""
  4044. # Modify a file
  4045. with open(self._foo_path, "w") as f:
  4046. f.write("modified content\n")
  4047. # Force checkout should succeed
  4048. porcelain.checkout(self.repo, "feature", force=True)
  4049. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4050. # Since foo has the same content in master and feature branches,
  4051. # checkout should NOT restore it - the modified content should remain
  4052. with open(self._foo_path) as f:
  4053. content = f.read()
  4054. self.assertEqual("modified content\n", content)
  4055. def test_checkout_nonexistent_ref(self) -> None:
  4056. """Test checkout of non-existent branch/commit."""
  4057. with self.assertRaises(KeyError):
  4058. porcelain.checkout(self.repo, "nonexistent")
  4059. def test_checkout_partial_sha(self) -> None:
  4060. """Test checkout with partial SHA."""
  4061. # Git typically allows checkout with partial SHA
  4062. partial_sha = self._sha1.decode("ascii")[:7]
  4063. porcelain.checkout(self.repo, partial_sha)
  4064. # Should be in detached HEAD state at the right commit
  4065. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  4066. def test_checkout_preserves_untracked_files(self) -> None:
  4067. """Test that checkout preserves untracked files."""
  4068. # Create an untracked file
  4069. untracked_path = os.path.join(self.repo.path, "untracked.txt")
  4070. with open(untracked_path, "w") as f:
  4071. f.write("untracked content\n")
  4072. # Checkout another branch
  4073. porcelain.checkout(self.repo, "feature")
  4074. # Untracked file should still exist
  4075. self.assertTrue(os.path.exists(untracked_path))
  4076. with open(untracked_path) as f:
  4077. content = f.read()
  4078. self.assertEqual("untracked content\n", content)
  4079. def test_checkout_full_ref_paths(self) -> None:
  4080. """Test checkout with full ref paths."""
  4081. # Test checkout with full branch ref path
  4082. porcelain.checkout(self.repo, "refs/heads/feature")
  4083. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4084. # Test checkout with full tag ref path
  4085. porcelain.checkout(self.repo, "refs/tags/v1.0")
  4086. # Should be in detached HEAD state
  4087. with self.assertRaises((ValueError, IndexError)):
  4088. porcelain.active_branch(self.repo)
  4089. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  4090. def test_checkout_bytes_vs_string_target(self) -> None:
  4091. """Test that checkout works with both bytes and string targets."""
  4092. # Test with string target
  4093. porcelain.checkout(self.repo, "feature")
  4094. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4095. # Test with bytes target
  4096. porcelain.checkout(self.repo, b"master")
  4097. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4098. def test_checkout_new_branch_from_commit(self) -> None:
  4099. """Test creating a new branch from a specific commit."""
  4100. # Create new branch from first commit
  4101. porcelain.checkout(self.repo, self._sha1.decode(), new_branch="from-commit")
  4102. self.assertEqual(b"from-commit", porcelain.active_branch(self.repo))
  4103. # Should be at the first commit (no bar file)
  4104. self.assertFalse(os.path.exists(self._bar_path))
  4105. def test_checkout_with_staged_addition(self) -> None:
  4106. """Test checkout behavior with staged file additions."""
  4107. # Create and stage a new file that doesn't exist in target branch
  4108. new_file_path = os.path.join(self.repo.path, "new.txt")
  4109. with open(new_file_path, "w") as f:
  4110. f.write("new file content\n")
  4111. porcelain.add(self.repo, [new_file_path])
  4112. # This should succeed because the file doesn't exist in target branch
  4113. porcelain.checkout(self.repo, "feature")
  4114. # Should be on feature branch
  4115. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4116. # The new file should still exist and be staged
  4117. self.assertTrue(os.path.exists(new_file_path))
  4118. status = porcelain.status(self.repo)
  4119. self.assertIn(b"new.txt", status.staged["add"])
  4120. def test_checkout_with_staged_modification_conflict(self) -> None:
  4121. """Test checkout behavior with staged modifications that would conflict."""
  4122. # Stage changes to a file that exists in both branches
  4123. with open(self._foo_path, "w") as f:
  4124. f.write("modified content\n")
  4125. porcelain.add(self.repo, [self._foo_path])
  4126. # Should prevent checkout due to staged changes to existing file
  4127. with self.assertRaises(porcelain.CheckoutError) as cm:
  4128. porcelain.checkout(self.repo, "feature")
  4129. self.assertIn("local changes", str(cm.exception))
  4130. self.assertIn("foo", str(cm.exception))
  4131. def test_checkout_head_reference(self) -> None:
  4132. """Test checkout of HEAD reference."""
  4133. # Move to feature branch first
  4134. porcelain.checkout(self.repo, "feature")
  4135. # Checkout HEAD creates detached HEAD state
  4136. porcelain.checkout(self.repo, "HEAD")
  4137. # Should be in detached HEAD state
  4138. with self.assertRaises((ValueError, IndexError)):
  4139. porcelain.active_branch(self.repo)
  4140. def test_checkout_error_messages(self) -> None:
  4141. """Test that checkout error messages are helpful."""
  4142. # Create uncommitted changes
  4143. with open(self._foo_path, "w") as f:
  4144. f.write("uncommitted changes\n")
  4145. # Try to checkout
  4146. with self.assertRaises(porcelain.CheckoutError) as cm:
  4147. porcelain.checkout(self.repo, "feature")
  4148. error_msg = str(cm.exception)
  4149. self.assertIn("local changes", error_msg)
  4150. self.assertIn("foo", error_msg)
  4151. self.assertIn("overwritten", error_msg)
  4152. self.assertIn("commit or stash", error_msg)
  4153. class SubmoduleTests(PorcelainTestCase):
  4154. def test_empty(self) -> None:
  4155. porcelain.commit(
  4156. repo=self.repo.path,
  4157. message=b"init",
  4158. author=b"author <email>",
  4159. committer=b"committer <email>",
  4160. )
  4161. self.assertEqual([], list(porcelain.submodule_list(self.repo)))
  4162. def test_add(self) -> None:
  4163. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  4164. with open(f"{self.repo.path}/.gitmodules") as f:
  4165. self.assertEqual(
  4166. """\
  4167. [submodule "bar"]
  4168. \turl = ../bar.git
  4169. \tpath = bar
  4170. """,
  4171. f.read(),
  4172. )
  4173. def test_init(self) -> None:
  4174. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  4175. porcelain.submodule_init(self.repo)
  4176. def test_update(self) -> None:
  4177. # Create a submodule repository
  4178. sub_repo_path = tempfile.mkdtemp()
  4179. self.addCleanup(shutil.rmtree, sub_repo_path)
  4180. sub_repo = Repo.init(sub_repo_path)
  4181. self.addCleanup(sub_repo.close)
  4182. # Add a file to the submodule repo
  4183. sub_file = os.path.join(sub_repo_path, "test.txt")
  4184. with open(sub_file, "w") as f:
  4185. f.write("submodule content")
  4186. porcelain.add(sub_repo, paths=[sub_file])
  4187. sub_commit = porcelain.commit(
  4188. sub_repo,
  4189. message=b"Initial submodule commit",
  4190. author=b"Test Author <test@example.com>",
  4191. committer=b"Test Committer <test@example.com>",
  4192. )
  4193. # Add the submodule to the main repository
  4194. porcelain.submodule_add(self.repo, sub_repo_path, "test_submodule")
  4195. # Manually add the submodule to the index
  4196. from dulwich.index import IndexEntry
  4197. from dulwich.objects import S_IFGITLINK
  4198. index = self.repo.open_index()
  4199. index[b"test_submodule"] = IndexEntry(
  4200. ctime=0,
  4201. mtime=0,
  4202. dev=0,
  4203. ino=0,
  4204. mode=S_IFGITLINK,
  4205. uid=0,
  4206. gid=0,
  4207. size=0,
  4208. sha=sub_commit,
  4209. flags=0,
  4210. )
  4211. index.write()
  4212. porcelain.add(self.repo, paths=[".gitmodules"])
  4213. porcelain.commit(
  4214. self.repo,
  4215. message=b"Add submodule",
  4216. author=b"Test Author <test@example.com>",
  4217. committer=b"Test Committer <test@example.com>",
  4218. )
  4219. # Initialize and update the submodule
  4220. porcelain.submodule_init(self.repo)
  4221. porcelain.submodule_update(self.repo)
  4222. # Check that the submodule directory exists
  4223. submodule_path = os.path.join(self.repo.path, "test_submodule")
  4224. self.assertTrue(os.path.exists(submodule_path))
  4225. # Check that the submodule file exists
  4226. submodule_file = os.path.join(submodule_path, "test.txt")
  4227. self.assertTrue(os.path.exists(submodule_file))
  4228. with open(submodule_file) as f:
  4229. self.assertEqual(f.read(), "submodule content")
  4230. def test_update_recursive(self) -> None:
  4231. # Create a nested (innermost) submodule repository
  4232. nested_repo_path = tempfile.mkdtemp()
  4233. self.addCleanup(shutil.rmtree, nested_repo_path)
  4234. nested_repo = Repo.init(nested_repo_path)
  4235. self.addCleanup(nested_repo.close)
  4236. # Add a file to the nested repo
  4237. nested_file = os.path.join(nested_repo_path, "nested.txt")
  4238. with open(nested_file, "w") as f:
  4239. f.write("nested submodule content")
  4240. porcelain.add(nested_repo, paths=[nested_file])
  4241. nested_commit = porcelain.commit(
  4242. nested_repo,
  4243. message=b"Initial nested commit",
  4244. author=b"Test Author <test@example.com>",
  4245. committer=b"Test Committer <test@example.com>",
  4246. )
  4247. # Create a middle submodule repository
  4248. middle_repo_path = tempfile.mkdtemp()
  4249. self.addCleanup(shutil.rmtree, middle_repo_path)
  4250. middle_repo = Repo.init(middle_repo_path)
  4251. self.addCleanup(middle_repo.close)
  4252. # Add a file to the middle repo
  4253. middle_file = os.path.join(middle_repo_path, "middle.txt")
  4254. with open(middle_file, "w") as f:
  4255. f.write("middle submodule content")
  4256. porcelain.add(middle_repo, paths=[middle_file])
  4257. # Add the nested submodule to the middle repository
  4258. porcelain.submodule_add(middle_repo, nested_repo_path, "nested")
  4259. # Manually add the nested submodule to the index
  4260. from dulwich.index import IndexEntry
  4261. from dulwich.objects import S_IFGITLINK
  4262. middle_index = middle_repo.open_index()
  4263. middle_index[b"nested"] = IndexEntry(
  4264. ctime=0,
  4265. mtime=0,
  4266. dev=0,
  4267. ino=0,
  4268. mode=S_IFGITLINK,
  4269. uid=0,
  4270. gid=0,
  4271. size=0,
  4272. sha=nested_commit,
  4273. flags=0,
  4274. )
  4275. middle_index.write()
  4276. porcelain.add(middle_repo, paths=[".gitmodules"])
  4277. middle_commit = porcelain.commit(
  4278. middle_repo,
  4279. message=b"Add nested submodule",
  4280. author=b"Test Author <test@example.com>",
  4281. committer=b"Test Committer <test@example.com>",
  4282. )
  4283. # Add the middle submodule to the main repository
  4284. porcelain.submodule_add(self.repo, middle_repo_path, "middle")
  4285. # Manually add the middle submodule to the index
  4286. main_index = self.repo.open_index()
  4287. main_index[b"middle"] = IndexEntry(
  4288. ctime=0,
  4289. mtime=0,
  4290. dev=0,
  4291. ino=0,
  4292. mode=S_IFGITLINK,
  4293. uid=0,
  4294. gid=0,
  4295. size=0,
  4296. sha=middle_commit,
  4297. flags=0,
  4298. )
  4299. main_index.write()
  4300. porcelain.add(self.repo, paths=[".gitmodules"])
  4301. porcelain.commit(
  4302. self.repo,
  4303. message=b"Add middle submodule",
  4304. author=b"Test Author <test@example.com>",
  4305. committer=b"Test Committer <test@example.com>",
  4306. )
  4307. # Initialize and recursively update the submodules
  4308. porcelain.submodule_init(self.repo)
  4309. porcelain.submodule_update(self.repo, recursive=True)
  4310. # Check that the middle submodule directory and file exist
  4311. middle_submodule_path = os.path.join(self.repo.path, "middle")
  4312. self.assertTrue(os.path.exists(middle_submodule_path))
  4313. middle_submodule_file = os.path.join(middle_submodule_path, "middle.txt")
  4314. self.assertTrue(os.path.exists(middle_submodule_file))
  4315. with open(middle_submodule_file) as f:
  4316. self.assertEqual(f.read(), "middle submodule content")
  4317. # Check that the nested submodule directory and file exist
  4318. nested_submodule_path = os.path.join(self.repo.path, "middle", "nested")
  4319. self.assertTrue(os.path.exists(nested_submodule_path))
  4320. nested_submodule_file = os.path.join(nested_submodule_path, "nested.txt")
  4321. self.assertTrue(os.path.exists(nested_submodule_file))
  4322. with open(nested_submodule_file) as f:
  4323. self.assertEqual(f.read(), "nested submodule content")
  4324. class PushTests(PorcelainTestCase):
  4325. def test_simple(self) -> None:
  4326. """Basic test of porcelain push where self.repo is the remote. First
  4327. clone the remote, commit a file to the clone, then push the changes
  4328. back to the remote.
  4329. """
  4330. outstream = BytesIO()
  4331. errstream = BytesIO()
  4332. porcelain.commit(
  4333. repo=self.repo.path,
  4334. message=b"init",
  4335. author=b"author <email>",
  4336. committer=b"committer <email>",
  4337. )
  4338. # Setup target repo cloned from temp test repo
  4339. clone_path = tempfile.mkdtemp()
  4340. self.addCleanup(shutil.rmtree, clone_path)
  4341. target_repo = porcelain.clone(
  4342. self.repo.path, target=clone_path, errstream=errstream
  4343. )
  4344. self.addCleanup(target_repo.close)
  4345. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  4346. # create a second file to be pushed back to origin
  4347. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4348. os.close(handle)
  4349. porcelain.add(repo=clone_path, paths=[fullpath])
  4350. porcelain.commit(
  4351. repo=clone_path,
  4352. message=b"push",
  4353. author=b"author <email>",
  4354. committer=b"committer <email>",
  4355. )
  4356. # Setup a non-checked out branch in the remote
  4357. refs_path = b"refs/heads/foo"
  4358. new_id = self.repo[b"HEAD"].id
  4359. self.assertNotEqual(new_id, ZERO_SHA)
  4360. self.repo.refs[refs_path] = new_id
  4361. # Push to the remote
  4362. porcelain.push(
  4363. clone_path,
  4364. "origin",
  4365. b"HEAD:" + refs_path,
  4366. outstream=outstream,
  4367. errstream=errstream,
  4368. )
  4369. self.assertEqual(
  4370. target_repo.refs[b"refs/remotes/origin/foo"],
  4371. target_repo.refs[b"HEAD"],
  4372. )
  4373. # Check that the target and source
  4374. with Repo(clone_path) as r_clone:
  4375. self.assertEqual(
  4376. {
  4377. b"HEAD": new_id,
  4378. b"refs/heads/foo": r_clone[b"HEAD"].id,
  4379. b"refs/heads/master": new_id,
  4380. },
  4381. self.repo.get_refs(),
  4382. )
  4383. self.assertEqual(r_clone[b"HEAD"].id, self.repo[refs_path].id)
  4384. # Get the change in the target repo corresponding to the add
  4385. # this will be in the foo branch.
  4386. change = next(
  4387. iter(
  4388. tree_changes(
  4389. self.repo.object_store,
  4390. self.repo[b"HEAD"].tree,
  4391. self.repo[b"refs/heads/foo"].tree,
  4392. )
  4393. )
  4394. )
  4395. self.assertEqual(
  4396. os.path.basename(fullpath), change.new.path.decode("ascii")
  4397. )
  4398. def test_local_missing(self) -> None:
  4399. """Pushing a new branch."""
  4400. outstream = BytesIO()
  4401. errstream = BytesIO()
  4402. # Setup target repo cloned from temp test repo
  4403. clone_path = tempfile.mkdtemp()
  4404. self.addCleanup(shutil.rmtree, clone_path)
  4405. target_repo = porcelain.init(clone_path)
  4406. target_repo.close()
  4407. self.assertRaises(
  4408. porcelain.Error,
  4409. porcelain.push,
  4410. self.repo,
  4411. clone_path,
  4412. b"HEAD:refs/heads/master",
  4413. outstream=outstream,
  4414. errstream=errstream,
  4415. )
  4416. def test_new(self) -> None:
  4417. """Pushing a new branch."""
  4418. outstream = BytesIO()
  4419. errstream = BytesIO()
  4420. # Setup target repo cloned from temp test repo
  4421. clone_path = tempfile.mkdtemp()
  4422. self.addCleanup(shutil.rmtree, clone_path)
  4423. target_repo = porcelain.init(clone_path)
  4424. target_repo.close()
  4425. # create a second file to be pushed back to origin
  4426. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4427. os.close(handle)
  4428. porcelain.add(repo=clone_path, paths=[fullpath])
  4429. new_id = porcelain.commit(
  4430. repo=self.repo,
  4431. message=b"push",
  4432. author=b"author <email>",
  4433. committer=b"committer <email>",
  4434. )
  4435. # Push to the remote
  4436. porcelain.push(
  4437. self.repo,
  4438. clone_path,
  4439. b"HEAD:refs/heads/master",
  4440. outstream=outstream,
  4441. errstream=errstream,
  4442. )
  4443. with Repo(clone_path) as r_clone:
  4444. self.assertEqual(
  4445. {
  4446. b"HEAD": new_id,
  4447. b"refs/heads/master": new_id,
  4448. },
  4449. r_clone.get_refs(),
  4450. )
  4451. def test_delete(self) -> None:
  4452. """Basic test of porcelain push, removing a branch."""
  4453. outstream = BytesIO()
  4454. errstream = BytesIO()
  4455. porcelain.commit(
  4456. repo=self.repo.path,
  4457. message=b"init",
  4458. author=b"author <email>",
  4459. committer=b"committer <email>",
  4460. )
  4461. # Setup target repo cloned from temp test repo
  4462. clone_path = tempfile.mkdtemp()
  4463. self.addCleanup(shutil.rmtree, clone_path)
  4464. target_repo = porcelain.clone(
  4465. self.repo.path, target=clone_path, errstream=errstream
  4466. )
  4467. target_repo.close()
  4468. # Setup a non-checked out branch in the remote
  4469. refs_path = b"refs/heads/foo"
  4470. new_id = self.repo[b"HEAD"].id
  4471. self.assertNotEqual(new_id, ZERO_SHA)
  4472. self.repo.refs[refs_path] = new_id
  4473. # Push to the remote
  4474. porcelain.push(
  4475. clone_path,
  4476. self.repo.path,
  4477. b":" + refs_path,
  4478. outstream=outstream,
  4479. errstream=errstream,
  4480. )
  4481. self.assertEqual(
  4482. {
  4483. b"HEAD": new_id,
  4484. b"refs/heads/master": new_id,
  4485. },
  4486. self.repo.get_refs(),
  4487. )
  4488. def test_diverged(self) -> None:
  4489. outstream = BytesIO()
  4490. errstream = BytesIO()
  4491. porcelain.commit(
  4492. repo=self.repo.path,
  4493. message=b"init",
  4494. author=b"author <email>",
  4495. committer=b"committer <email>",
  4496. )
  4497. # Setup target repo cloned from temp test repo
  4498. clone_path = tempfile.mkdtemp()
  4499. self.addCleanup(shutil.rmtree, clone_path)
  4500. target_repo = porcelain.clone(
  4501. self.repo.path, target=clone_path, errstream=errstream
  4502. )
  4503. target_repo.close()
  4504. remote_id = porcelain.commit(
  4505. repo=self.repo.path,
  4506. message=b"remote change",
  4507. author=b"author <email>",
  4508. committer=b"committer <email>",
  4509. )
  4510. local_id = porcelain.commit(
  4511. repo=clone_path,
  4512. message=b"local change",
  4513. author=b"author <email>",
  4514. committer=b"committer <email>",
  4515. )
  4516. outstream = BytesIO()
  4517. errstream = BytesIO()
  4518. # Push to the remote
  4519. self.assertRaises(
  4520. porcelain.DivergedBranches,
  4521. porcelain.push,
  4522. clone_path,
  4523. self.repo.path,
  4524. b"refs/heads/master",
  4525. outstream=outstream,
  4526. errstream=errstream,
  4527. )
  4528. self.assertEqual(
  4529. {
  4530. b"HEAD": remote_id,
  4531. b"refs/heads/master": remote_id,
  4532. },
  4533. self.repo.get_refs(),
  4534. )
  4535. self.assertEqual(b"", outstream.getvalue())
  4536. self.assertEqual(b"", errstream.getvalue())
  4537. outstream = BytesIO()
  4538. errstream = BytesIO()
  4539. # Push to the remote with --force
  4540. porcelain.push(
  4541. clone_path,
  4542. self.repo.path,
  4543. b"refs/heads/master",
  4544. outstream=outstream,
  4545. errstream=errstream,
  4546. force=True,
  4547. )
  4548. self.assertEqual(
  4549. {
  4550. b"HEAD": local_id,
  4551. b"refs/heads/master": local_id,
  4552. },
  4553. self.repo.get_refs(),
  4554. )
  4555. self.assertEqual(b"", outstream.getvalue())
  4556. self.assertTrue(re.search(b"Push to .* successful.\n", errstream.getvalue()))
  4557. def test_push_returns_sendpackresult(self) -> None:
  4558. """Test that push returns a SendPackResult with per-ref information."""
  4559. outstream = BytesIO()
  4560. errstream = BytesIO()
  4561. # Create initial commit
  4562. porcelain.commit(
  4563. repo=self.repo.path,
  4564. message=b"init",
  4565. author=b"author <email>",
  4566. committer=b"committer <email>",
  4567. )
  4568. # Setup target repo cloned from temp test repo
  4569. clone_path = tempfile.mkdtemp()
  4570. self.addCleanup(shutil.rmtree, clone_path)
  4571. target_repo = porcelain.clone(
  4572. self.repo.path, target=clone_path, errstream=errstream
  4573. )
  4574. target_repo.close()
  4575. # Create a commit in the clone
  4576. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4577. os.close(handle)
  4578. porcelain.add(repo=clone_path, paths=[fullpath])
  4579. porcelain.commit(
  4580. repo=clone_path,
  4581. message=b"push",
  4582. author=b"author <email>",
  4583. committer=b"committer <email>",
  4584. )
  4585. # Push and check the return value
  4586. result = porcelain.push(
  4587. clone_path,
  4588. "origin",
  4589. b"HEAD:refs/heads/new-branch",
  4590. outstream=outstream,
  4591. errstream=errstream,
  4592. )
  4593. # Verify that we get a SendPackResult
  4594. self.assertIsInstance(result, SendPackResult)
  4595. # Verify that it contains refs
  4596. self.assertIsNotNone(result.refs)
  4597. self.assertIn(b"refs/heads/new-branch", result.refs)
  4598. # Verify ref_status - should be None for successful updates
  4599. if result.ref_status:
  4600. self.assertIsNone(result.ref_status.get(b"refs/heads/new-branch"))
  4601. def test_mirror_mode(self) -> None:
  4602. """Test push with remote.<name>.mirror configuration."""
  4603. outstream = BytesIO()
  4604. errstream = BytesIO()
  4605. # Create initial commit
  4606. porcelain.commit(
  4607. repo=self.repo.path,
  4608. message=b"init",
  4609. author=b"author <email>",
  4610. committer=b"committer <email>",
  4611. )
  4612. # Setup target repo cloned from temp test repo
  4613. clone_path = tempfile.mkdtemp()
  4614. self.addCleanup(shutil.rmtree, clone_path)
  4615. target_repo = porcelain.clone(
  4616. self.repo.path, target=clone_path, errstream=errstream
  4617. )
  4618. target_repo.close()
  4619. # Create multiple refs in the clone
  4620. with Repo(clone_path) as r_clone:
  4621. # Create a new branch
  4622. r_clone.refs[b"refs/heads/feature"] = r_clone[b"HEAD"].id
  4623. # Create a tag
  4624. r_clone.refs[b"refs/tags/v1.0"] = r_clone[b"HEAD"].id
  4625. # Create a remote tracking branch
  4626. r_clone.refs[b"refs/remotes/upstream/main"] = r_clone[b"HEAD"].id
  4627. # Create a branch in the remote that doesn't exist in clone
  4628. self.repo.refs[b"refs/heads/to-be-deleted"] = self.repo[b"HEAD"].id
  4629. # Configure mirror mode
  4630. with Repo(clone_path) as r_clone:
  4631. config = r_clone.get_config()
  4632. config.set((b"remote", b"origin"), b"mirror", True)
  4633. config.write_to_path()
  4634. # Push with mirror mode
  4635. porcelain.push(
  4636. clone_path,
  4637. "origin",
  4638. outstream=outstream,
  4639. errstream=errstream,
  4640. )
  4641. # Verify refs were properly mirrored
  4642. with Repo(clone_path) as r_clone:
  4643. # All local branches should be pushed
  4644. self.assertEqual(
  4645. r_clone.refs[b"refs/heads/feature"],
  4646. self.repo.refs[b"refs/heads/feature"],
  4647. )
  4648. # All tags should be pushed
  4649. self.assertEqual(
  4650. r_clone.refs[b"refs/tags/v1.0"], self.repo.refs[b"refs/tags/v1.0"]
  4651. )
  4652. # Remote tracking branches should be pushed
  4653. self.assertEqual(
  4654. r_clone.refs[b"refs/remotes/upstream/main"],
  4655. self.repo.refs[b"refs/remotes/upstream/main"],
  4656. )
  4657. # Verify the extra branch was deleted
  4658. self.assertNotIn(b"refs/heads/to-be-deleted", self.repo.refs)
  4659. def test_mirror_mode_disabled(self) -> None:
  4660. """Test that mirror mode is properly disabled when set to false."""
  4661. outstream = BytesIO()
  4662. errstream = BytesIO()
  4663. # Create initial commit
  4664. porcelain.commit(
  4665. repo=self.repo.path,
  4666. message=b"init",
  4667. author=b"author <email>",
  4668. committer=b"committer <email>",
  4669. )
  4670. # Setup target repo cloned from temp test repo
  4671. clone_path = tempfile.mkdtemp()
  4672. self.addCleanup(shutil.rmtree, clone_path)
  4673. target_repo = porcelain.clone(
  4674. self.repo.path, target=clone_path, errstream=errstream
  4675. )
  4676. target_repo.close()
  4677. # Create a branch in the remote that doesn't exist in clone
  4678. self.repo.refs[b"refs/heads/should-not-be-deleted"] = self.repo[b"HEAD"].id
  4679. # Explicitly set mirror mode to false
  4680. with Repo(clone_path) as r_clone:
  4681. config = r_clone.get_config()
  4682. config.set((b"remote", b"origin"), b"mirror", False)
  4683. config.write_to_path()
  4684. # Push normally (not mirror mode)
  4685. porcelain.push(
  4686. clone_path,
  4687. "origin",
  4688. outstream=outstream,
  4689. errstream=errstream,
  4690. )
  4691. # Verify the extra branch was NOT deleted
  4692. self.assertIn(b"refs/heads/should-not-be-deleted", self.repo.refs)
  4693. class PullTests(PorcelainTestCase):
  4694. def setUp(self) -> None:
  4695. super().setUp()
  4696. # create a file for initial commit
  4697. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4698. os.close(handle)
  4699. porcelain.add(repo=self.repo.path, paths=fullpath)
  4700. porcelain.commit(
  4701. repo=self.repo.path,
  4702. message=b"test",
  4703. author=b"test <email>",
  4704. committer=b"test <email>",
  4705. )
  4706. # Setup target repo
  4707. self.target_path = tempfile.mkdtemp()
  4708. self.addCleanup(shutil.rmtree, self.target_path)
  4709. target_repo = porcelain.clone(
  4710. self.repo.path, target=self.target_path, errstream=BytesIO()
  4711. )
  4712. target_repo.close()
  4713. # create a second file to be pushed
  4714. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4715. os.close(handle)
  4716. porcelain.add(repo=self.repo.path, paths=fullpath)
  4717. porcelain.commit(
  4718. repo=self.repo.path,
  4719. message=b"test2",
  4720. author=b"test2 <email>",
  4721. committer=b"test2 <email>",
  4722. )
  4723. self.assertIn(b"refs/heads/master", self.repo.refs)
  4724. self.assertIn(b"refs/heads/master", target_repo.refs)
  4725. def test_simple(self) -> None:
  4726. outstream = BytesIO()
  4727. errstream = BytesIO()
  4728. # Pull changes into the cloned repo
  4729. porcelain.pull(
  4730. self.target_path,
  4731. self.repo.path,
  4732. b"refs/heads/master",
  4733. outstream=outstream,
  4734. errstream=errstream,
  4735. )
  4736. # Check the target repo for pushed changes
  4737. with Repo(self.target_path) as r:
  4738. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4739. def test_diverged(self) -> None:
  4740. outstream = BytesIO()
  4741. errstream = BytesIO()
  4742. c3a = porcelain.commit(
  4743. repo=self.target_path,
  4744. message=b"test3a",
  4745. author=b"test2 <email>",
  4746. committer=b"test2 <email>",
  4747. )
  4748. porcelain.commit(
  4749. repo=self.repo.path,
  4750. message=b"test3b",
  4751. author=b"test2 <email>",
  4752. committer=b"test2 <email>",
  4753. )
  4754. # Pull changes into the cloned repo
  4755. self.assertRaises(
  4756. porcelain.DivergedBranches,
  4757. porcelain.pull,
  4758. self.target_path,
  4759. self.repo.path,
  4760. b"refs/heads/master",
  4761. outstream=outstream,
  4762. errstream=errstream,
  4763. )
  4764. # Check the target repo for pushed changes
  4765. with Repo(self.target_path) as r:
  4766. self.assertEqual(r[b"refs/heads/master"].id, c3a)
  4767. # Pull with merge should now work
  4768. porcelain.pull(
  4769. self.target_path,
  4770. self.repo.path,
  4771. b"refs/heads/master",
  4772. outstream=outstream,
  4773. errstream=errstream,
  4774. fast_forward=False,
  4775. )
  4776. # Check the target repo for merged changes
  4777. with Repo(self.target_path) as r:
  4778. # HEAD should now be a merge commit
  4779. head = r[b"HEAD"]
  4780. # It should have two parents
  4781. self.assertEqual(len(head.parents), 2)
  4782. # One parent should be the previous HEAD (c3a)
  4783. self.assertIn(c3a, head.parents)
  4784. # The other parent should be from the source repo
  4785. self.assertIn(self.repo[b"HEAD"].id, head.parents)
  4786. def test_no_refspec(self) -> None:
  4787. outstream = BytesIO()
  4788. errstream = BytesIO()
  4789. # Pull changes into the cloned repo
  4790. porcelain.pull(
  4791. self.target_path,
  4792. self.repo.path,
  4793. outstream=outstream,
  4794. errstream=errstream,
  4795. )
  4796. # Check the target repo for pushed changes
  4797. with Repo(self.target_path) as r:
  4798. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4799. def test_no_remote_location(self) -> None:
  4800. outstream = BytesIO()
  4801. errstream = BytesIO()
  4802. # Pull changes into the cloned repo
  4803. porcelain.pull(
  4804. self.target_path,
  4805. refspecs=b"refs/heads/master",
  4806. outstream=outstream,
  4807. errstream=errstream,
  4808. )
  4809. # Check the target repo for pushed changes
  4810. with Repo(self.target_path) as r:
  4811. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4812. def test_pull_updates_working_tree(self) -> None:
  4813. """Test that pull updates the working tree with new files."""
  4814. outstream = BytesIO()
  4815. errstream = BytesIO()
  4816. # Create a new file with content in the source repo
  4817. new_file = os.path.join(self.repo.path, "newfile.txt")
  4818. with open(new_file, "w") as f:
  4819. f.write("This is new content")
  4820. porcelain.add(repo=self.repo.path, paths=[new_file])
  4821. porcelain.commit(
  4822. repo=self.repo.path,
  4823. message=b"Add new file",
  4824. author=b"test <email>",
  4825. committer=b"test <email>",
  4826. )
  4827. # Before pull, the file should not exist in target
  4828. target_file = os.path.join(self.target_path, "newfile.txt")
  4829. self.assertFalse(os.path.exists(target_file))
  4830. # Pull changes into the cloned repo
  4831. porcelain.pull(
  4832. self.target_path,
  4833. self.repo.path,
  4834. b"refs/heads/master",
  4835. outstream=outstream,
  4836. errstream=errstream,
  4837. )
  4838. # After pull, the file should exist with correct content
  4839. self.assertTrue(os.path.exists(target_file))
  4840. with open(target_file) as f:
  4841. self.assertEqual(f.read(), "This is new content")
  4842. # Check the HEAD is updated too
  4843. with Repo(self.target_path) as r:
  4844. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4845. def test_pull_protects_modified_files(self) -> None:
  4846. """Test that pull refuses to overwrite uncommitted changes by default."""
  4847. from dulwich.errors import WorkingTreeModifiedError
  4848. outstream = BytesIO()
  4849. errstream = BytesIO()
  4850. # Create a file with content in the source repo
  4851. test_file = os.path.join(self.repo.path, "testfile.txt")
  4852. with open(test_file, "w") as f:
  4853. f.write("original content")
  4854. porcelain.add(repo=self.repo.path, paths=[test_file])
  4855. porcelain.commit(
  4856. repo=self.repo.path,
  4857. message=b"Add test file",
  4858. author=b"test <email>",
  4859. committer=b"test <email>",
  4860. )
  4861. # Pull this change to target first
  4862. porcelain.pull(
  4863. self.target_path,
  4864. self.repo.path,
  4865. b"refs/heads/master",
  4866. outstream=outstream,
  4867. errstream=errstream,
  4868. )
  4869. # Now modify the file in source repo
  4870. with open(test_file, "w") as f:
  4871. f.write("updated content")
  4872. porcelain.add(repo=self.repo.path, paths=[test_file])
  4873. porcelain.commit(
  4874. repo=self.repo.path,
  4875. message=b"Update test file",
  4876. author=b"test <email>",
  4877. committer=b"test <email>",
  4878. )
  4879. # Modify the same file in target working directory (uncommitted)
  4880. target_file = os.path.join(self.target_path, "testfile.txt")
  4881. with open(target_file, "w") as f:
  4882. f.write("local modifications")
  4883. # Pull should fail because of uncommitted changes
  4884. with self.assertRaises(WorkingTreeModifiedError) as cm:
  4885. porcelain.pull(
  4886. self.target_path,
  4887. self.repo.path,
  4888. b"refs/heads/master",
  4889. outstream=outstream,
  4890. errstream=errstream,
  4891. )
  4892. self.assertIn("Your local changes", str(cm.exception))
  4893. self.assertIn("testfile.txt", str(cm.exception))
  4894. # Verify the file still has local modifications
  4895. with open(target_file) as f:
  4896. self.assertEqual(f.read(), "local modifications")
  4897. def test_pull_force_overwrites_modified_files(self) -> None:
  4898. """Test that pull with force=True overwrites uncommitted changes."""
  4899. outstream = BytesIO()
  4900. errstream = BytesIO()
  4901. # Create a file with content in the source repo
  4902. test_file = os.path.join(self.repo.path, "testfile.txt")
  4903. with open(test_file, "w") as f:
  4904. f.write("original content")
  4905. porcelain.add(repo=self.repo.path, paths=[test_file])
  4906. porcelain.commit(
  4907. repo=self.repo.path,
  4908. message=b"Add test file",
  4909. author=b"test <email>",
  4910. committer=b"test <email>",
  4911. )
  4912. # Pull this change to target first
  4913. porcelain.pull(
  4914. self.target_path,
  4915. self.repo.path,
  4916. b"refs/heads/master",
  4917. outstream=outstream,
  4918. errstream=errstream,
  4919. )
  4920. # Now modify the file in source repo
  4921. with open(test_file, "w") as f:
  4922. f.write("updated content")
  4923. porcelain.add(repo=self.repo.path, paths=[test_file])
  4924. porcelain.commit(
  4925. repo=self.repo.path,
  4926. message=b"Update test file",
  4927. author=b"test <email>",
  4928. committer=b"test <email>",
  4929. )
  4930. # Modify the same file in target working directory (uncommitted)
  4931. target_file = os.path.join(self.target_path, "testfile.txt")
  4932. with open(target_file, "w") as f:
  4933. f.write("local modifications")
  4934. # Pull with force=True should succeed and overwrite local changes
  4935. porcelain.pull(
  4936. self.target_path,
  4937. self.repo.path,
  4938. b"refs/heads/master",
  4939. outstream=outstream,
  4940. errstream=errstream,
  4941. force=True,
  4942. )
  4943. # Verify the file now has the remote content
  4944. with open(target_file) as f:
  4945. self.assertEqual(f.read(), "updated content")
  4946. # Check the HEAD is updated too
  4947. with Repo(self.target_path) as r:
  4948. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4949. def test_pull_allows_unmodified_files(self) -> None:
  4950. """Test that pull allows updating files that haven't been modified locally."""
  4951. outstream = BytesIO()
  4952. errstream = BytesIO()
  4953. # Create a file with content in the source repo
  4954. test_file = os.path.join(self.repo.path, "testfile.txt")
  4955. with open(test_file, "w") as f:
  4956. f.write("original content")
  4957. porcelain.add(repo=self.repo.path, paths=[test_file])
  4958. porcelain.commit(
  4959. repo=self.repo.path,
  4960. message=b"Add test file",
  4961. author=b"test <email>",
  4962. committer=b"test <email>",
  4963. )
  4964. # Pull this change to target first
  4965. porcelain.pull(
  4966. self.target_path,
  4967. self.repo.path,
  4968. b"refs/heads/master",
  4969. outstream=outstream,
  4970. errstream=errstream,
  4971. )
  4972. # Now modify the file in source repo
  4973. with open(test_file, "w") as f:
  4974. f.write("updated content")
  4975. porcelain.add(repo=self.repo.path, paths=[test_file])
  4976. porcelain.commit(
  4977. repo=self.repo.path,
  4978. message=b"Update test file",
  4979. author=b"test <email>",
  4980. committer=b"test <email>",
  4981. )
  4982. # Don't modify the file in target - it should be safe to update
  4983. target_file = os.path.join(self.target_path, "testfile.txt")
  4984. # Pull should succeed since the file wasn't modified locally
  4985. porcelain.pull(
  4986. self.target_path,
  4987. self.repo.path,
  4988. b"refs/heads/master",
  4989. outstream=outstream,
  4990. errstream=errstream,
  4991. )
  4992. # Verify the file now has the remote content
  4993. with open(target_file) as f:
  4994. self.assertEqual(f.read(), "updated content")
  4995. # Check the HEAD is updated too
  4996. with Repo(self.target_path) as r:
  4997. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4998. class StatusTests(PorcelainTestCase):
  4999. def test_empty(self) -> None:
  5000. results = porcelain.status(self.repo)
  5001. self.assertEqual({"add": [], "delete": [], "modify": []}, results.staged)
  5002. self.assertEqual([], results.unstaged)
  5003. def test_status_base(self) -> None:
  5004. """Integration test for `status` functionality."""
  5005. # Commit a dummy file then modify it
  5006. fullpath = os.path.join(self.repo.path, "foo")
  5007. with open(fullpath, "w") as f:
  5008. f.write("origstuff")
  5009. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5010. porcelain.commit(
  5011. repo=self.repo.path,
  5012. message=b"test status",
  5013. author=b"author <email>",
  5014. committer=b"committer <email>",
  5015. )
  5016. # modify access and modify time of path
  5017. os.utime(fullpath, (0, 0))
  5018. with open(fullpath, "wb") as f:
  5019. f.write(b"stuff")
  5020. # Make a dummy file and stage it
  5021. filename_add = "bar"
  5022. fullpath = os.path.join(self.repo.path, filename_add)
  5023. with open(fullpath, "w") as f:
  5024. f.write("stuff")
  5025. porcelain.add(repo=self.repo.path, paths=fullpath)
  5026. results = porcelain.status(self.repo)
  5027. self.assertEqual(results.staged["add"][0], filename_add.encode("ascii"))
  5028. self.assertEqual(results.unstaged, [b"foo"])
  5029. def test_status_with_core_preloadindex(self) -> None:
  5030. """Test status with core.preloadIndex enabled."""
  5031. # Set core.preloadIndex to true
  5032. config = self.repo.get_config()
  5033. config.set(b"core", b"preloadIndex", b"true")
  5034. config.write_to_path()
  5035. # Create multiple files
  5036. files = []
  5037. for i in range(10):
  5038. filename = f"file{i}"
  5039. fullpath = os.path.join(self.repo.path, filename)
  5040. with open(fullpath, "w") as f:
  5041. f.write(f"content{i}")
  5042. files.append(fullpath)
  5043. porcelain.add(repo=self.repo.path, paths=files)
  5044. porcelain.commit(
  5045. repo=self.repo.path,
  5046. message=b"test preload status",
  5047. author=b"author <email>",
  5048. committer=b"committer <email>",
  5049. )
  5050. # Modify some files
  5051. modified_files = ["file1", "file3", "file5", "file7"]
  5052. for filename in modified_files:
  5053. fullpath = os.path.join(self.repo.path, filename)
  5054. with open(fullpath, "w") as f:
  5055. f.write("modified content")
  5056. os.utime(fullpath, (0, 0))
  5057. # Status should work correctly with preloadIndex enabled
  5058. results = porcelain.status(self.repo)
  5059. # Check that we detected the correct unstaged changes
  5060. unstaged_sorted = sorted(results.unstaged)
  5061. expected_sorted = sorted([f.encode("ascii") for f in modified_files])
  5062. self.assertEqual(unstaged_sorted, expected_sorted)
  5063. def test_status_all(self) -> None:
  5064. del_path = os.path.join(self.repo.path, "foo")
  5065. mod_path = os.path.join(self.repo.path, "bar")
  5066. add_path = os.path.join(self.repo.path, "baz")
  5067. us_path = os.path.join(self.repo.path, "blye")
  5068. ut_path = os.path.join(self.repo.path, "blyat")
  5069. with open(del_path, "w") as f:
  5070. f.write("origstuff")
  5071. with open(mod_path, "w") as f:
  5072. f.write("origstuff")
  5073. with open(us_path, "w") as f:
  5074. f.write("origstuff")
  5075. porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path])
  5076. porcelain.commit(
  5077. repo=self.repo.path,
  5078. message=b"test status",
  5079. author=b"author <email>",
  5080. committer=b"committer <email>",
  5081. )
  5082. porcelain.remove(self.repo.path, [del_path])
  5083. with open(add_path, "w") as f:
  5084. f.write("origstuff")
  5085. with open(mod_path, "w") as f:
  5086. f.write("more_origstuff")
  5087. with open(us_path, "w") as f:
  5088. f.write("more_origstuff")
  5089. porcelain.add(repo=self.repo.path, paths=[add_path, mod_path])
  5090. with open(us_path, "w") as f:
  5091. f.write("\norigstuff")
  5092. with open(ut_path, "w") as f:
  5093. f.write("origstuff")
  5094. results = porcelain.status(self.repo.path)
  5095. self.assertDictEqual(
  5096. {"add": [b"baz"], "delete": [b"foo"], "modify": [b"bar"]},
  5097. results.staged,
  5098. )
  5099. self.assertListEqual(results.unstaged, [b"blye"])
  5100. results_no_untracked = porcelain.status(self.repo.path, untracked_files="no")
  5101. self.assertListEqual(results_no_untracked.untracked, [])
  5102. def test_status_wrong_untracked_files_value(self) -> None:
  5103. with self.assertRaises(ValueError):
  5104. porcelain.status(self.repo.path, untracked_files="antani")
  5105. def test_status_untracked_path(self) -> None:
  5106. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  5107. os.mkdir(untracked_dir)
  5108. untracked_file = os.path.join(untracked_dir, "untracked_file")
  5109. with open(untracked_file, "w") as fh:
  5110. fh.write("untracked")
  5111. _, _, untracked = porcelain.status(self.repo.path, untracked_files="all")
  5112. self.assertEqual(untracked, ["untracked_dir/untracked_file"])
  5113. def test_status_untracked_path_normal(self) -> None:
  5114. # Create an untracked directory with multiple files
  5115. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  5116. os.mkdir(untracked_dir)
  5117. untracked_file1 = os.path.join(untracked_dir, "file1")
  5118. untracked_file2 = os.path.join(untracked_dir, "file2")
  5119. with open(untracked_file1, "w") as fh:
  5120. fh.write("untracked1")
  5121. with open(untracked_file2, "w") as fh:
  5122. fh.write("untracked2")
  5123. # Create a nested untracked directory
  5124. nested_dir = os.path.join(untracked_dir, "nested")
  5125. os.mkdir(nested_dir)
  5126. nested_file = os.path.join(nested_dir, "file3")
  5127. with open(nested_file, "w") as fh:
  5128. fh.write("untracked3")
  5129. # Test "normal" mode - should only show the directory, not individual files
  5130. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  5131. self.assertEqual(untracked, ["untracked_dir/"])
  5132. # Test "all" mode - should show all files
  5133. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  5134. self.assertEqual(
  5135. sorted(untracked_all),
  5136. [
  5137. "untracked_dir/file1",
  5138. "untracked_dir/file2",
  5139. "untracked_dir/nested/file3",
  5140. ],
  5141. )
  5142. def test_status_mixed_tracked_untracked(self) -> None:
  5143. # Create a directory with both tracked and untracked files
  5144. mixed_dir = os.path.join(self.repo_path, "mixed_dir")
  5145. os.mkdir(mixed_dir)
  5146. # Add a tracked file
  5147. tracked_file = os.path.join(mixed_dir, "tracked.txt")
  5148. with open(tracked_file, "w") as fh:
  5149. fh.write("tracked content")
  5150. porcelain.add(self.repo.path, paths=[tracked_file])
  5151. porcelain.commit(
  5152. repo=self.repo.path,
  5153. message=b"add tracked file",
  5154. author=b"author <email>",
  5155. committer=b"committer <email>",
  5156. )
  5157. # Add untracked files to the same directory
  5158. untracked_file = os.path.join(mixed_dir, "untracked.txt")
  5159. with open(untracked_file, "w") as fh:
  5160. fh.write("untracked content")
  5161. # In "normal" mode, should show individual untracked files in mixed dirs
  5162. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  5163. self.assertEqual(untracked, ["mixed_dir/untracked.txt"])
  5164. # In "all" mode, should be the same for mixed directories
  5165. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  5166. self.assertEqual(untracked_all, ["mixed_dir/untracked.txt"])
  5167. def test_status_crlf_mismatch(self) -> None:
  5168. # First make a commit as if the file has been added on a Linux system
  5169. # or with core.autocrlf=True
  5170. file_path = os.path.join(self.repo.path, "crlf")
  5171. with open(file_path, "wb") as f:
  5172. f.write(b"line1\nline2")
  5173. porcelain.add(repo=self.repo.path, paths=[file_path])
  5174. porcelain.commit(
  5175. repo=self.repo.path,
  5176. message=b"test status",
  5177. author=b"author <email>",
  5178. committer=b"committer <email>",
  5179. )
  5180. # Then update the file as if it was created by CGit on a Windows
  5181. # system with core.autocrlf=true
  5182. with open(file_path, "wb") as f:
  5183. f.write(b"line1\r\nline2")
  5184. results = porcelain.status(self.repo)
  5185. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  5186. self.assertListEqual(results.unstaged, [b"crlf"])
  5187. self.assertListEqual(results.untracked, [])
  5188. def test_status_autocrlf_true(self) -> None:
  5189. # First make a commit as if the file has been added on a Linux system
  5190. # or with core.autocrlf=True
  5191. file_path = os.path.join(self.repo.path, "crlf")
  5192. with open(file_path, "wb") as f:
  5193. f.write(b"line1\nline2")
  5194. porcelain.add(repo=self.repo.path, paths=[file_path])
  5195. porcelain.commit(
  5196. repo=self.repo.path,
  5197. message=b"test status",
  5198. author=b"author <email>",
  5199. committer=b"committer <email>",
  5200. )
  5201. # Then update the file as if it was created by CGit on a Windows
  5202. # system with core.autocrlf=true
  5203. with open(file_path, "wb") as f:
  5204. f.write(b"line1\r\nline2")
  5205. # TODO: It should be set automatically by looking at the configuration
  5206. c = self.repo.get_config()
  5207. c.set("core", "autocrlf", True)
  5208. c.write_to_path()
  5209. results = porcelain.status(self.repo)
  5210. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  5211. self.assertListEqual(results.unstaged, [])
  5212. self.assertListEqual(results.untracked, [])
  5213. def test_status_autocrlf_input(self) -> None:
  5214. # Commit existing file with CRLF
  5215. file_path = os.path.join(self.repo.path, "crlf-exists")
  5216. with open(file_path, "wb") as f:
  5217. f.write(b"line1\r\nline2")
  5218. porcelain.add(repo=self.repo.path, paths=[file_path])
  5219. porcelain.commit(
  5220. repo=self.repo.path,
  5221. message=b"test status",
  5222. author=b"author <email>",
  5223. committer=b"committer <email>",
  5224. )
  5225. # Get the index entry mtime and set the file mtime to match it exactly
  5226. # This ensures stat matching works correctly with nanosecond precision
  5227. index = self.repo.open_index()
  5228. entry = index[b"crlf-exists"]
  5229. if isinstance(entry.mtime, tuple):
  5230. mtime_nsec = entry.mtime[0] * 1_000_000_000 + entry.mtime[1]
  5231. else:
  5232. mtime_nsec = int(entry.mtime * 1_000_000_000)
  5233. # Use ns parameter to preserve nanosecond precision
  5234. os.utime(file_path, ns=(mtime_nsec, mtime_nsec))
  5235. c = self.repo.get_config()
  5236. c.set("core", "autocrlf", "input")
  5237. c.write_to_path()
  5238. # Add new (untracked) file
  5239. file_path = os.path.join(self.repo.path, "crlf-new")
  5240. with open(file_path, "wb") as f:
  5241. f.write(b"line1\r\nline2")
  5242. porcelain.add(repo=self.repo.path, paths=[file_path])
  5243. results = porcelain.status(self.repo)
  5244. self.assertDictEqual(
  5245. {"add": [b"crlf-new"], "delete": [], "modify": []}, results.staged
  5246. )
  5247. # File committed with CRLF before autocrlf=input was enabled
  5248. # will NOT appear as unstaged because stat matching optimization
  5249. # skips filter processing when file hasn't been modified.
  5250. # This matches Git's behavior, which uses stat matching to avoid
  5251. # expensive filter operations. Git shows a warning instead.
  5252. self.assertListEqual(results.unstaged, [])
  5253. self.assertListEqual(results.untracked, [])
  5254. def test_status_autocrlf_input_modified(self) -> None:
  5255. """Test that modified files with CRLF are correctly detected with autocrlf=input."""
  5256. # Commit existing file with CRLF
  5257. file_path = os.path.join(self.repo.path, "crlf-file.txt")
  5258. with open(file_path, "wb") as f:
  5259. f.write(b"line1\r\nline2\r\nline3\r\n")
  5260. porcelain.add(repo=self.repo.path, paths=[file_path])
  5261. porcelain.commit(
  5262. repo=self.repo.path,
  5263. message=b"initial commit",
  5264. author=b"author <email>",
  5265. committer=b"committer <email>",
  5266. )
  5267. c = self.repo.get_config()
  5268. c.set("core", "autocrlf", "input")
  5269. c.write_to_path()
  5270. # Modify the file content but keep CRLF
  5271. with open(file_path, "wb") as f:
  5272. f.write(b"line1\r\nline2 modified\r\nline3\r\n")
  5273. results = porcelain.status(self.repo)
  5274. # Modified file should be detected as unstaged
  5275. self.assertListEqual(results.unstaged, [b"crlf-file.txt"])
  5276. def test_status_autocrlf_input_binary(self) -> None:
  5277. """Test that binary files are not affected by autocrlf=input."""
  5278. # Set autocrlf=input first
  5279. c = self.repo.get_config()
  5280. c.set("core", "autocrlf", "input")
  5281. c.write_to_path()
  5282. # Commit binary file with CRLF-like sequences
  5283. file_path = os.path.join(self.repo.path, "binary.dat")
  5284. with open(file_path, "wb") as f:
  5285. f.write(b"binary\r\ndata\x00\xff\r\nmore")
  5286. porcelain.add(repo=self.repo.path, paths=[file_path])
  5287. porcelain.commit(
  5288. repo=self.repo.path,
  5289. message=b"add binary",
  5290. author=b"author <email>",
  5291. committer=b"committer <email>",
  5292. )
  5293. # Status should be clean - binary files not normalized
  5294. results = porcelain.status(self.repo)
  5295. self.assertListEqual(results.unstaged, [])
  5296. def test_status_autocrlf_input_mixed_endings(self) -> None:
  5297. """Test files with mixed line endings with autocrlf=input."""
  5298. # Set autocrlf=input
  5299. c = self.repo.get_config()
  5300. c.set("core", "autocrlf", "input")
  5301. c.write_to_path()
  5302. # Create file with mixed line endings
  5303. file_path = os.path.join(self.repo.path, "mixed.txt")
  5304. with open(file_path, "wb") as f:
  5305. f.write(b"line1\r\nline2\nline3\r\n")
  5306. porcelain.add(repo=self.repo.path, paths=[file_path])
  5307. porcelain.commit(
  5308. repo=self.repo.path,
  5309. message=b"add mixed",
  5310. author=b"author <email>",
  5311. committer=b"committer <email>",
  5312. )
  5313. # The file was normalized on commit, so working tree should match
  5314. results = porcelain.status(self.repo)
  5315. self.assertListEqual(results.unstaged, [])
  5316. def test_status_autocrlf_input_issue_1770(self) -> None:
  5317. """Test the specific scenario from issue #1770.
  5318. Files with CRLF committed with autocrlf=input should not show as unstaged
  5319. when their content hasn't changed.
  5320. """
  5321. # Set autocrlf=input BEFORE committing
  5322. c = self.repo.get_config()
  5323. c.set("core", "autocrlf", "input")
  5324. c.write_to_path()
  5325. # Create and commit file with CRLF endings
  5326. file_path = os.path.join(self.repo.path, "crlf-test.dsp")
  5327. with open(file_path, "wb") as f:
  5328. f.write(b"# Microsoft DSP file\r\n\r\nContent here\r\n")
  5329. porcelain.add(repo=self.repo.path, paths=[file_path])
  5330. porcelain.commit(
  5331. repo=self.repo.path,
  5332. message=b"add dsp file",
  5333. author=b"author <email>",
  5334. committer=b"committer <email>",
  5335. )
  5336. # File was normalized to LF in index, but working tree still has CRLF
  5337. # Status should be clean because comparison normalizes working tree too
  5338. results = porcelain.status(self.repo)
  5339. self.assertListEqual(results.unstaged, [])
  5340. def test_get_tree_changes_add(self) -> None:
  5341. """Unit test for get_tree_changes add."""
  5342. # Make a dummy file, stage
  5343. filename = "bar"
  5344. fullpath = os.path.join(self.repo.path, filename)
  5345. with open(fullpath, "w") as f:
  5346. f.write("stuff")
  5347. porcelain.add(repo=self.repo.path, paths=fullpath)
  5348. porcelain.commit(
  5349. repo=self.repo.path,
  5350. message=b"test status",
  5351. author=b"author <email>",
  5352. committer=b"committer <email>",
  5353. )
  5354. filename = "foo"
  5355. fullpath = os.path.join(self.repo.path, filename)
  5356. with open(fullpath, "w") as f:
  5357. f.write("stuff")
  5358. porcelain.add(repo=self.repo.path, paths=fullpath)
  5359. changes = porcelain.get_tree_changes(self.repo.path)
  5360. self.assertEqual(changes["add"][0], filename.encode("ascii"))
  5361. self.assertEqual(len(changes["add"]), 1)
  5362. self.assertEqual(len(changes["modify"]), 0)
  5363. self.assertEqual(len(changes["delete"]), 0)
  5364. def test_get_tree_changes_modify(self) -> None:
  5365. """Unit test for get_tree_changes modify."""
  5366. # Make a dummy file, stage, commit, modify
  5367. filename = "foo"
  5368. fullpath = os.path.join(self.repo.path, filename)
  5369. with open(fullpath, "w") as f:
  5370. f.write("stuff")
  5371. porcelain.add(repo=self.repo.path, paths=fullpath)
  5372. porcelain.commit(
  5373. repo=self.repo.path,
  5374. message=b"test status",
  5375. author=b"author <email>",
  5376. committer=b"committer <email>",
  5377. )
  5378. with open(fullpath, "w") as f:
  5379. f.write("otherstuff")
  5380. porcelain.add(repo=self.repo.path, paths=fullpath)
  5381. changes = porcelain.get_tree_changes(self.repo.path)
  5382. self.assertEqual(changes["modify"][0], filename.encode("ascii"))
  5383. self.assertEqual(len(changes["add"]), 0)
  5384. self.assertEqual(len(changes["modify"]), 1)
  5385. self.assertEqual(len(changes["delete"]), 0)
  5386. def test_get_tree_changes_delete(self) -> None:
  5387. """Unit test for get_tree_changes delete."""
  5388. # Make a dummy file, stage, commit, remove
  5389. filename = "foo"
  5390. fullpath = os.path.join(self.repo.path, filename)
  5391. with open(fullpath, "w") as f:
  5392. f.write("stuff")
  5393. porcelain.add(repo=self.repo.path, paths=fullpath)
  5394. porcelain.commit(
  5395. repo=self.repo.path,
  5396. message=b"test status",
  5397. author=b"author <email>",
  5398. committer=b"committer <email>",
  5399. )
  5400. cwd = os.getcwd()
  5401. self.addCleanup(os.chdir, cwd)
  5402. os.chdir(self.repo.path)
  5403. porcelain.remove(repo=self.repo.path, paths=[filename])
  5404. changes = porcelain.get_tree_changes(self.repo.path)
  5405. self.assertEqual(changes["delete"][0], filename.encode("ascii"))
  5406. self.assertEqual(len(changes["add"]), 0)
  5407. self.assertEqual(len(changes["modify"]), 0)
  5408. self.assertEqual(len(changes["delete"]), 1)
  5409. def test_get_untracked_paths(self) -> None:
  5410. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5411. f.write("ignored\n")
  5412. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  5413. f.write("blah\n")
  5414. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5415. f.write("blah\n")
  5416. os.symlink(
  5417. os.path.join(self.repo.path, os.pardir, "external_target"),
  5418. os.path.join(self.repo.path, "link"),
  5419. )
  5420. self.assertEqual(
  5421. {"ignored", "notignored", ".gitignore", "link"},
  5422. set(
  5423. porcelain.get_untracked_paths(
  5424. self.repo.path, self.repo.path, self.repo.open_index()
  5425. )
  5426. ),
  5427. )
  5428. self.assertEqual(
  5429. {".gitignore", "notignored", "link"},
  5430. set(porcelain.status(self.repo).untracked),
  5431. )
  5432. self.assertEqual(
  5433. {".gitignore", "notignored", "ignored", "link"},
  5434. set(porcelain.status(self.repo, ignored=True).untracked),
  5435. )
  5436. def test_get_untracked_paths_subrepo(self) -> None:
  5437. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5438. f.write("nested/\n")
  5439. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5440. f.write("blah\n")
  5441. subrepo = Repo.init(os.path.join(self.repo.path, "nested"), mkdir=True)
  5442. with open(os.path.join(subrepo.path, "ignored"), "w") as f:
  5443. f.write("bleep\n")
  5444. with open(os.path.join(subrepo.path, "with"), "w") as f:
  5445. f.write("bloop\n")
  5446. with open(os.path.join(subrepo.path, "manager"), "w") as f:
  5447. f.write("blop\n")
  5448. self.assertEqual(
  5449. {".gitignore", "notignored", os.path.join("nested", "")},
  5450. set(
  5451. porcelain.get_untracked_paths(
  5452. self.repo.path, self.repo.path, self.repo.open_index()
  5453. )
  5454. ),
  5455. )
  5456. self.assertEqual(
  5457. {".gitignore", "notignored"},
  5458. set(
  5459. porcelain.get_untracked_paths(
  5460. self.repo.path,
  5461. self.repo.path,
  5462. self.repo.open_index(),
  5463. exclude_ignored=True,
  5464. )
  5465. ),
  5466. )
  5467. self.assertEqual(
  5468. {"ignored", "with", "manager"},
  5469. set(
  5470. porcelain.get_untracked_paths(
  5471. subrepo.path, subrepo.path, subrepo.open_index()
  5472. )
  5473. ),
  5474. )
  5475. self.assertEqual(
  5476. set(),
  5477. set(
  5478. porcelain.get_untracked_paths(
  5479. subrepo.path,
  5480. self.repo.path,
  5481. self.repo.open_index(),
  5482. )
  5483. ),
  5484. )
  5485. self.assertEqual(
  5486. {
  5487. os.path.join("nested", "ignored"),
  5488. os.path.join("nested", "with"),
  5489. os.path.join("nested", "manager"),
  5490. },
  5491. set(
  5492. porcelain.get_untracked_paths(
  5493. self.repo.path,
  5494. subrepo.path,
  5495. self.repo.open_index(),
  5496. )
  5497. ),
  5498. )
  5499. def test_get_untracked_paths_nested_gitignore(self) -> None:
  5500. """Test directories with nested .gitignore files that ignore all contents."""
  5501. # Create cache directories with .gitignore files that contain "*"
  5502. cache_dirs = [".ruff_cache", ".pytest_cache", "__pycache__"]
  5503. for cache_dir in cache_dirs:
  5504. cache_path = os.path.join(self.repo.path, cache_dir)
  5505. os.mkdir(cache_path)
  5506. # Create .gitignore with * pattern (ignores everything)
  5507. with open(os.path.join(cache_path, ".gitignore"), "w") as f:
  5508. f.write("*\n")
  5509. # Create some files in the cache directory
  5510. with open(os.path.join(cache_path, "somefile.txt"), "w") as f:
  5511. f.write("cached data\n")
  5512. with open(os.path.join(cache_path, "data.json"), "w") as f:
  5513. f.write("{}\n")
  5514. # Create a normal untracked file
  5515. with open(os.path.join(self.repo.path, "untracked.txt"), "w") as f:
  5516. f.write("untracked content\n")
  5517. # Test with exclude_ignored=True (default for status)
  5518. untracked = set(
  5519. porcelain.get_untracked_paths(
  5520. self.repo.path,
  5521. self.repo.path,
  5522. self.repo.open_index(),
  5523. exclude_ignored=True,
  5524. untracked_files="normal",
  5525. )
  5526. )
  5527. # Cache directories should NOT be in untracked since all their contents are ignored
  5528. self.assertEqual({"untracked.txt"}, untracked)
  5529. # Test with exclude_ignored=False
  5530. untracked_with_ignored = set(
  5531. porcelain.get_untracked_paths(
  5532. self.repo.path,
  5533. self.repo.path,
  5534. self.repo.open_index(),
  5535. exclude_ignored=False,
  5536. untracked_files="normal",
  5537. )
  5538. )
  5539. # Cache directories should be included when not excluding ignored
  5540. expected = {"untracked.txt"}
  5541. for cache_dir in cache_dirs:
  5542. expected.add(cache_dir + os.sep)
  5543. self.assertEqual(expected, untracked_with_ignored)
  5544. # Test status() which uses exclude_ignored=True by default
  5545. status = porcelain.status(self.repo)
  5546. self.assertEqual(["untracked.txt"], status.untracked)
  5547. # Test status() with ignored=True which uses exclude_ignored=False
  5548. status_with_ignored = porcelain.status(self.repo, ignored=True)
  5549. # Should include cache directories
  5550. self.assertIn("untracked.txt", status_with_ignored.untracked)
  5551. for cache_dir in cache_dirs:
  5552. self.assertIn(cache_dir + "/", status_with_ignored.untracked)
  5553. def test_get_untracked_paths_mixed_directory(self) -> None:
  5554. """Test directory with both ignored and non-ignored files."""
  5555. # Create a directory with mixed content
  5556. mixed_dir = os.path.join(self.repo.path, "mixed")
  5557. os.mkdir(mixed_dir)
  5558. # Create .gitignore that ignores .log files
  5559. with open(os.path.join(mixed_dir, ".gitignore"), "w") as f:
  5560. f.write("*.log\n")
  5561. # Create ignored and non-ignored files
  5562. with open(os.path.join(mixed_dir, "debug.log"), "w") as f:
  5563. f.write("debug info\n")
  5564. with open(os.path.join(mixed_dir, "readme.txt"), "w") as f:
  5565. f.write("important\n")
  5566. # Test with exclude_ignored=True and normal mode
  5567. untracked = set(
  5568. porcelain.get_untracked_paths(
  5569. self.repo.path,
  5570. self.repo.path,
  5571. self.repo.open_index(),
  5572. exclude_ignored=True,
  5573. untracked_files="normal",
  5574. )
  5575. )
  5576. # In normal mode, should show the directory (matching git behavior)
  5577. self.assertEqual({os.path.join("mixed", "")}, untracked)
  5578. # Test with untracked_files="all"
  5579. untracked_all = set(
  5580. porcelain.get_untracked_paths(
  5581. self.repo.path,
  5582. self.repo.path,
  5583. self.repo.open_index(),
  5584. exclude_ignored=True,
  5585. untracked_files="all",
  5586. )
  5587. )
  5588. # Should list the non-ignored files
  5589. expected = {
  5590. os.path.join("mixed", ".gitignore"),
  5591. os.path.join("mixed", "readme.txt"),
  5592. }
  5593. self.assertEqual(expected, untracked_all)
  5594. def test_get_untracked_paths_specific_ignore_pattern(self) -> None:
  5595. """Test directory with .gitignore that ignores specific files, not all."""
  5596. # Create a directory
  5597. test_dir = os.path.join(self.repo.path, "testdir")
  5598. os.mkdir(test_dir)
  5599. # Create .gitignore that ignores only files named "test"
  5600. with open(os.path.join(test_dir, ".gitignore"), "w") as f:
  5601. f.write("test\n")
  5602. # Create files
  5603. with open(os.path.join(test_dir, "test"), "w") as f:
  5604. f.write("ignored\n")
  5605. with open(os.path.join(test_dir, "other.txt"), "w") as f:
  5606. f.write("not ignored\n")
  5607. # Test with exclude_ignored=True and normal mode
  5608. untracked = set(
  5609. porcelain.get_untracked_paths(
  5610. self.repo.path,
  5611. self.repo.path,
  5612. self.repo.open_index(),
  5613. exclude_ignored=True,
  5614. untracked_files="normal",
  5615. )
  5616. )
  5617. # Directory should be shown because it has non-ignored files
  5618. self.assertEqual({os.path.join("testdir", "")}, untracked)
  5619. def test_get_untracked_paths_nested_subdirs_all_ignored(self) -> None:
  5620. """Test directory containing only subdirectories where all files are ignored."""
  5621. # Create parent directory with .gitignore that ignores everything
  5622. parent_dir = os.path.join(self.repo.path, "parent")
  5623. os.mkdir(parent_dir)
  5624. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5625. f.write("*\n")
  5626. # Create subdirectories with files (all should be ignored by parent's .gitignore)
  5627. sub1 = os.path.join(parent_dir, "sub1")
  5628. sub2 = os.path.join(parent_dir, "sub2")
  5629. os.mkdir(sub1)
  5630. os.mkdir(sub2)
  5631. # Create files in subdirectories
  5632. with open(os.path.join(sub1, "file1.txt"), "w") as f:
  5633. f.write("content1\n")
  5634. with open(os.path.join(sub2, "file2.txt"), "w") as f:
  5635. f.write("content2\n")
  5636. # Create another normal untracked file
  5637. with open(os.path.join(self.repo.path, "normal.txt"), "w") as f:
  5638. f.write("normal\n")
  5639. # Test with exclude_ignored=True
  5640. untracked = set(
  5641. porcelain.get_untracked_paths(
  5642. self.repo.path,
  5643. self.repo.path,
  5644. self.repo.open_index(),
  5645. exclude_ignored=True,
  5646. untracked_files="normal",
  5647. )
  5648. )
  5649. # Parent directory should NOT be shown since all nested files are ignored
  5650. self.assertEqual({"normal.txt"}, untracked)
  5651. def test_get_untracked_paths_nested_subdirs_mixed(self) -> None:
  5652. """Test directory containing only subdirectories where some files are ignored, some aren't."""
  5653. # Create parent directory with .gitignore that ignores .log files
  5654. parent_dir = os.path.join(self.repo.path, "parent")
  5655. os.mkdir(parent_dir)
  5656. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5657. f.write("*.log\n")
  5658. # Create subdirectories
  5659. sub1 = os.path.join(parent_dir, "sub1")
  5660. sub2 = os.path.join(parent_dir, "sub2")
  5661. os.mkdir(sub1)
  5662. os.mkdir(sub2)
  5663. # sub1: only ignored files
  5664. with open(os.path.join(sub1, "debug.log"), "w") as f:
  5665. f.write("log content\n")
  5666. with open(os.path.join(sub1, "error.log"), "w") as f:
  5667. f.write("error log\n")
  5668. # sub2: mix of ignored and non-ignored files
  5669. with open(os.path.join(sub2, "access.log"), "w") as f:
  5670. f.write("access log\n")
  5671. with open(os.path.join(sub2, "readme.txt"), "w") as f:
  5672. f.write("important info\n")
  5673. # Test with exclude_ignored=True
  5674. untracked = set(
  5675. porcelain.get_untracked_paths(
  5676. self.repo.path,
  5677. self.repo.path,
  5678. self.repo.open_index(),
  5679. exclude_ignored=True,
  5680. untracked_files="normal",
  5681. )
  5682. )
  5683. # Parent directory SHOULD be shown since sub2 has non-ignored files
  5684. self.assertEqual({os.path.join("parent", "")}, untracked)
  5685. def test_get_untracked_paths_deeply_nested_all_ignored(self) -> None:
  5686. """Test deeply nested directories where all files are eventually ignored."""
  5687. # Create nested structure: parent/sub/subsub/
  5688. parent_dir = os.path.join(self.repo.path, "parent")
  5689. sub_dir = os.path.join(parent_dir, "sub")
  5690. subsub_dir = os.path.join(sub_dir, "subsub")
  5691. os.makedirs(subsub_dir)
  5692. # Parent has .gitignore that ignores everything
  5693. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5694. f.write("*\n")
  5695. # Create files at different levels
  5696. with open(os.path.join(subsub_dir, "deep_file.txt"), "w") as f:
  5697. f.write("deep content\n")
  5698. with open(os.path.join(sub_dir, "mid_file.txt"), "w") as f:
  5699. f.write("mid content\n")
  5700. # Test with exclude_ignored=True
  5701. untracked = set(
  5702. porcelain.get_untracked_paths(
  5703. self.repo.path,
  5704. self.repo.path,
  5705. self.repo.open_index(),
  5706. exclude_ignored=True,
  5707. untracked_files="normal",
  5708. )
  5709. )
  5710. # Parent directory should NOT be shown since all nested files are ignored
  5711. self.assertEqual(set(), untracked)
  5712. def test_get_untracked_paths_subdir(self) -> None:
  5713. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5714. f.write("subdir/\nignored")
  5715. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5716. f.write("blah\n")
  5717. os.mkdir(os.path.join(self.repo.path, "subdir"))
  5718. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  5719. f.write("foo")
  5720. with open(os.path.join(self.repo.path, "subdir", "ignored"), "w") as f:
  5721. f.write("foo")
  5722. self.assertEqual(
  5723. {
  5724. ".gitignore",
  5725. "notignored",
  5726. "ignored",
  5727. os.path.join("subdir", ""),
  5728. },
  5729. set(
  5730. porcelain.get_untracked_paths(
  5731. self.repo.path,
  5732. self.repo.path,
  5733. self.repo.open_index(),
  5734. )
  5735. ),
  5736. )
  5737. self.assertEqual(
  5738. {".gitignore", "notignored"},
  5739. set(
  5740. porcelain.get_untracked_paths(
  5741. self.repo.path,
  5742. self.repo.path,
  5743. self.repo.open_index(),
  5744. exclude_ignored=True,
  5745. )
  5746. ),
  5747. )
  5748. def test_get_untracked_paths_invalid_untracked_files(self) -> None:
  5749. with self.assertRaises(ValueError):
  5750. list(
  5751. porcelain.get_untracked_paths(
  5752. self.repo.path,
  5753. self.repo.path,
  5754. self.repo.open_index(),
  5755. untracked_files="invalid_value",
  5756. )
  5757. )
  5758. def test_get_untracked_paths_normal(self) -> None:
  5759. # Create an untracked directory with files
  5760. untracked_dir = os.path.join(self.repo.path, "untracked_dir")
  5761. os.mkdir(untracked_dir)
  5762. with open(os.path.join(untracked_dir, "file1.txt"), "w") as f:
  5763. f.write("untracked content")
  5764. with open(os.path.join(untracked_dir, "file2.txt"), "w") as f:
  5765. f.write("more untracked content")
  5766. # Test that "normal" mode works and returns only the directory
  5767. _, _, untracked = porcelain.status(
  5768. repo=self.repo.path, untracked_files="normal"
  5769. )
  5770. self.assertEqual(untracked, ["untracked_dir/"])
  5771. def test_get_untracked_paths_top_level_issue_1247(self) -> None:
  5772. """Test for issue #1247: ensure top-level untracked files are detected."""
  5773. # Create a single top-level untracked file
  5774. with open(os.path.join(self.repo.path, "sample.txt"), "w") as f:
  5775. f.write("test content")
  5776. # Test get_untracked_paths directly
  5777. untracked = list(
  5778. porcelain.get_untracked_paths(
  5779. self.repo.path, self.repo.path, self.repo.open_index()
  5780. )
  5781. )
  5782. self.assertIn(
  5783. "sample.txt",
  5784. untracked,
  5785. "Top-level file 'sample.txt' should be in untracked list",
  5786. )
  5787. # Test via status
  5788. status = porcelain.status(self.repo)
  5789. self.assertIn(
  5790. "sample.txt",
  5791. status.untracked,
  5792. "Top-level file 'sample.txt' should be in status.untracked",
  5793. )
  5794. # TODO(jelmer): Add test for dulwich.porcelain.daemon
  5795. class ShortlogTests(PorcelainTestCase):
  5796. def test_shortlog(self) -> None:
  5797. """Test porcelain.shortlog function with multiple authors and commits."""
  5798. # Create first file and commit
  5799. file_a = os.path.join(self.repo.path, "a.txt")
  5800. with open(file_a, "w") as f:
  5801. f.write("hello")
  5802. porcelain.add(self.repo.path, paths=[file_a])
  5803. porcelain.commit(
  5804. repo=self.repo.path,
  5805. message=b"Initial commit",
  5806. author=b"John <john@example.com>",
  5807. )
  5808. # Create second file and commit
  5809. file_b = os.path.join(self.repo.path, "b.txt")
  5810. with open(file_b, "w") as f:
  5811. f.write("update")
  5812. porcelain.add(self.repo.path, paths=[file_b])
  5813. porcelain.commit(
  5814. repo=self.repo.path,
  5815. message=b"Update file",
  5816. author=b"Doe <doe@example.com>",
  5817. )
  5818. # Call shortlog
  5819. output = porcelain.shortlog(self.repo.path)
  5820. expected = [
  5821. {"author": "John <john@example.com>", "messages": "Initial commit"},
  5822. {"author": "Doe <doe@example.com>", "messages": "Update file"},
  5823. ]
  5824. self.assertCountEqual(output, expected)
  5825. # Test summary output (count of messages)
  5826. output_summary = [
  5827. {"author": entry["author"], "count": len(entry["messages"].splitlines())}
  5828. for entry in output
  5829. ]
  5830. expected_summary = [
  5831. {"author": "John <john@example.com>", "count": 1},
  5832. {"author": "Doe <doe@example.com>", "count": 1},
  5833. ]
  5834. self.assertCountEqual(output_summary, expected_summary)
  5835. class UploadPackTests(PorcelainTestCase):
  5836. """Tests for upload_pack."""
  5837. def test_upload_pack(self) -> None:
  5838. outf = BytesIO()
  5839. exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf)
  5840. outlines = outf.getvalue().splitlines()
  5841. self.assertEqual([b"0000"], outlines)
  5842. self.assertEqual(0, exitcode)
  5843. class ReceivePackTests(PorcelainTestCase):
  5844. """Tests for receive_pack."""
  5845. def test_receive_pack(self) -> None:
  5846. filename = "foo"
  5847. fullpath = os.path.join(self.repo.path, filename)
  5848. with open(fullpath, "w") as f:
  5849. f.write("stuff")
  5850. porcelain.add(repo=self.repo.path, paths=fullpath)
  5851. self.repo.get_worktree().commit(
  5852. message=b"test status",
  5853. committer=b"committer <email>",
  5854. author=b"author <email>",
  5855. commit_timestamp=1402354300,
  5856. commit_timezone=0,
  5857. author_timestamp=1402354300,
  5858. author_timezone=0,
  5859. )
  5860. outf = BytesIO()
  5861. exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf)
  5862. outlines = outf.getvalue().splitlines()
  5863. self.assertEqual(
  5864. [
  5865. b"0091319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status "
  5866. b"delete-refs quiet ofs-delta side-band-64k "
  5867. b"no-done symref=HEAD:refs/heads/master",
  5868. b"003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master",
  5869. b"0000",
  5870. ],
  5871. outlines,
  5872. )
  5873. self.assertEqual(0, exitcode)
  5874. class BranchListTests(PorcelainTestCase):
  5875. def test_standard(self) -> None:
  5876. self.assertEqual(set(), set(porcelain.branch_list(self.repo)))
  5877. def test_new_branch(self) -> None:
  5878. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5879. self.repo[b"HEAD"] = c1.id
  5880. porcelain.branch_create(self.repo, b"foo")
  5881. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  5882. def test_sort_by_refname(self) -> None:
  5883. """Test branch.sort=refname (default alphabetical)."""
  5884. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5885. self.repo[b"HEAD"] = c1.id
  5886. # Create branches in non-alphabetical order
  5887. porcelain.branch_create(self.repo, b"zebra")
  5888. porcelain.branch_create(self.repo, b"alpha")
  5889. porcelain.branch_create(self.repo, b"beta")
  5890. # Set branch.sort to refname (though it's the default)
  5891. config = self.repo.get_config()
  5892. config.set((b"branch",), b"sort", b"refname")
  5893. config.write_to_path()
  5894. # Should be sorted alphabetically
  5895. branches = porcelain.branch_list(self.repo)
  5896. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5897. def test_sort_by_refname_reverse(self) -> None:
  5898. """Test branch.sort=-refname (reverse alphabetical)."""
  5899. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5900. self.repo[b"HEAD"] = c1.id
  5901. # Create branches
  5902. porcelain.branch_create(self.repo, b"zebra")
  5903. porcelain.branch_create(self.repo, b"alpha")
  5904. porcelain.branch_create(self.repo, b"beta")
  5905. # Set branch.sort to -refname
  5906. config = self.repo.get_config()
  5907. config.set((b"branch",), b"sort", b"-refname")
  5908. config.write_to_path()
  5909. # Should be sorted reverse alphabetically
  5910. branches = porcelain.branch_list(self.repo)
  5911. self.assertEqual([b"zebra", b"master", b"beta", b"alpha"], branches)
  5912. def test_sort_by_committerdate(self) -> None:
  5913. """Test branch.sort=committerdate."""
  5914. # Use build_commit_graph to create proper commits with specific times
  5915. c1, c2, c3 = build_commit_graph(
  5916. self.repo.object_store,
  5917. [[1], [2], [3]],
  5918. attrs={
  5919. 1: {"commit_time": 1000}, # oldest
  5920. 2: {"commit_time": 2000}, # newest
  5921. 3: {"commit_time": 1500}, # middle
  5922. },
  5923. )
  5924. self.repo[b"HEAD"] = c1.id
  5925. # Create branches pointing to different commits
  5926. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  5927. self.repo.refs[b"refs/heads/oldest"] = c1.id
  5928. self.repo.refs[b"refs/heads/newest"] = c2.id
  5929. self.repo.refs[b"refs/heads/middle"] = c3.id
  5930. # Set branch.sort to committerdate
  5931. config = self.repo.get_config()
  5932. config.set((b"branch",), b"sort", b"committerdate")
  5933. config.write_to_path()
  5934. # Should be sorted by commit time (oldest first)
  5935. branches = porcelain.branch_list(self.repo)
  5936. self.assertEqual([b"master", b"oldest", b"middle", b"newest"], branches)
  5937. def test_sort_by_committerdate_reverse(self) -> None:
  5938. """Test branch.sort=-committerdate."""
  5939. # Use build_commit_graph to create proper commits with specific times
  5940. c1, c2, c3 = build_commit_graph(
  5941. self.repo.object_store,
  5942. [[1], [2], [3]],
  5943. attrs={
  5944. 1: {"commit_time": 1000}, # oldest
  5945. 2: {"commit_time": 2000}, # newest
  5946. 3: {"commit_time": 1500}, # middle
  5947. },
  5948. )
  5949. self.repo[b"HEAD"] = c1.id
  5950. # Create branches pointing to different commits
  5951. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  5952. self.repo.refs[b"refs/heads/oldest"] = c1.id
  5953. self.repo.refs[b"refs/heads/newest"] = c2.id
  5954. self.repo.refs[b"refs/heads/middle"] = c3.id
  5955. # Set branch.sort to -committerdate
  5956. config = self.repo.get_config()
  5957. config.set((b"branch",), b"sort", b"-committerdate")
  5958. config.write_to_path()
  5959. # Should be sorted by commit time (newest first)
  5960. branches = porcelain.branch_list(self.repo)
  5961. self.assertEqual([b"newest", b"middle", b"master", b"oldest"], branches)
  5962. def test_sort_default(self) -> None:
  5963. """Test default sorting (no config)."""
  5964. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5965. self.repo[b"HEAD"] = c1.id
  5966. # Create branches in non-alphabetical order
  5967. porcelain.branch_create(self.repo, b"zebra")
  5968. porcelain.branch_create(self.repo, b"alpha")
  5969. porcelain.branch_create(self.repo, b"beta")
  5970. # No config set - should default to alphabetical
  5971. branches = porcelain.branch_list(self.repo)
  5972. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5973. class BranchRemoteListTests(PorcelainTestCase):
  5974. def test_no_remote_branches(self) -> None:
  5975. """Test with no remote branches."""
  5976. result = porcelain.branch_remotes_list(self.repo)
  5977. self.assertEqual([], result)
  5978. def test_remote_branches_refname_sort(self) -> None:
  5979. """Test remote branches sorting with refname (alphabetical)."""
  5980. # Create some remote branches
  5981. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5982. # Create remote branches is non-alphabetical order
  5983. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  5984. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  5985. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  5986. self.repo.refs[b"refs/remotes/origin/feature-4"] = c1.id
  5987. # Set branch.sort to refname
  5988. config = self.repo.get_config()
  5989. config.set((b"branch",), b"sort", b"refname")
  5990. config.write_to_path()
  5991. # Should return only branch names, sorted alphabetically
  5992. branches = porcelain.branch_remotes_list(self.repo)
  5993. expected = [
  5994. b"origin/feature-1",
  5995. b"origin/feature-2",
  5996. b"origin/feature-3",
  5997. b"origin/feature-4",
  5998. ]
  5999. self.assertEqual(expected, branches)
  6000. def test_remote_branches_refname_reverse_sort(self) -> None:
  6001. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6002. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  6003. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  6004. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  6005. self.repo.refs[b"refs/remotes/origin/feature-4"] = c1.id
  6006. # Set branch.sort to -refname
  6007. config = self.repo.get_config()
  6008. config.set((b"branch",), b"sort", b"-refname")
  6009. config.write_to_path()
  6010. branches = porcelain.branch_remotes_list(self.repo)
  6011. expected = [
  6012. b"origin/feature-4",
  6013. b"origin/feature-3",
  6014. b"origin/feature-2",
  6015. b"origin/feature-1",
  6016. ]
  6017. self.assertEqual(expected, branches)
  6018. def test_remote_branches_committerdate_sort(self) -> None:
  6019. """Test remote branches sorting with committerdate"""
  6020. # Create commits with different timestamps
  6021. c1, c2, c3 = build_commit_graph(
  6022. self.repo.object_store,
  6023. [[1], [2], [3]],
  6024. attrs={
  6025. 1: {"commit_time": 1000},
  6026. 2: {"commit_time": 2000},
  6027. 3: {"commit_time": 3000},
  6028. },
  6029. )
  6030. self.repo.refs[b"refs/remotes/origin/oldest"] = c1.id
  6031. self.repo.refs[b"refs/remotes/origin/middle"] = c2.id
  6032. self.repo.refs[b"refs/remotes/origin/newest"] = c3.id
  6033. # Set branch.sort to committerdate
  6034. config = self.repo.get_config()
  6035. config.set((b"branch",), b"sort", b"committerdate")
  6036. config.write_to_path()
  6037. branches = porcelain.branch_remotes_list(self.repo)
  6038. # Should be sorted by commit time (oldest first), then alphabetically for same time
  6039. expected = [b"origin/oldest", b"origin/middle", b"origin/newest"]
  6040. self.assertEqual(expected, branches)
  6041. def test_remote_branches_committerdate_reverse_sort(self) -> None:
  6042. """Test remote branches sorting with -committerdate."""
  6043. c1, c2, c3 = build_commit_graph(
  6044. self.repo.object_store,
  6045. [[1], [2], [3]],
  6046. attrs={
  6047. 1: {"commit_time": 1000},
  6048. 2: {"commit_time": 2000},
  6049. 3: {"commit_time": 1500},
  6050. },
  6051. )
  6052. self.repo.refs[b"refs/remotes/origin/oldest"] = c1.id
  6053. self.repo.refs[b"refs/remotes/origin/newest"] = c2.id
  6054. self.repo.refs[b"refs/remotes/origin/middle"] = c3.id
  6055. # Set branch.sort to -committerdate
  6056. config = self.repo.get_config()
  6057. config.set((b"branch",), b"sort", b"-committerdate")
  6058. config.write_to_path()
  6059. branches = porcelain.branch_remotes_list(self.repo)
  6060. # Should be sorted by commit time (newest first), then alphabetically for same time
  6061. expected = [b"origin/newest", b"origin/middle", b"origin/oldest"]
  6062. self.assertEqual(expected, branches)
  6063. def test_remote_branches_authordate_sort(self) -> None:
  6064. """Test remote branches sorting with authordate."""
  6065. c1, c2, c3 = build_commit_graph(
  6066. self.repo.object_store,
  6067. [[1], [2], [3]],
  6068. attrs={
  6069. 1: {"author_time": 1500},
  6070. 2: {"author_time": 2000},
  6071. 3: {"author_time": 1000},
  6072. },
  6073. )
  6074. self.repo.refs[b"refs/remotes/origin/middle"] = c1.id
  6075. self.repo.refs[b"refs/remotes/origin/newest"] = c2.id
  6076. self.repo.refs[b"refs/remotes/origin/oldest"] = c3.id
  6077. # Set branch.sort to authordate
  6078. config = self.repo.get_config()
  6079. config.set((b"branch",), b"sort", b"authordate")
  6080. config.write_to_path()
  6081. branches = porcelain.branch_remotes_list(self.repo)
  6082. expected = [b"origin/oldest", b"origin/middle", b"origin/newest"]
  6083. self.assertEqual(expected, branches)
  6084. def test_unknown_sort_key(self) -> None:
  6085. """Test that unknown sort key raises ValueError."""
  6086. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6087. self.repo.refs[b"refs/remotes/origin/master"] = c1.id
  6088. # Set branch.sort to unknown key
  6089. config = self.repo.get_config()
  6090. config.set((b"branch",), b"sort", b"unknown")
  6091. config.write_to_path()
  6092. with self.assertRaises(ValueError) as cm:
  6093. porcelain.branch_remotes_list(self.repo)
  6094. self.assertIn("Unknown sort key: unknown", str(cm.exception))
  6095. def test_default_sort_no_config(self) -> None:
  6096. """Test default sorting when no config is set."""
  6097. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6098. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  6099. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  6100. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  6101. # No config set - should default to alphabetical
  6102. branches = porcelain.branch_remotes_list(self.repo)
  6103. expected = [b"origin/feature-1", b"origin/feature-2", b"origin/feature-3"]
  6104. self.assertEqual(expected, branches)
  6105. class BranchMergedTests(PorcelainTestCase):
  6106. def test_no_merged_branches(self) -> None:
  6107. """Test with no merged branches."""
  6108. # Create complete graph: c1 → c2 (master), c1 → c3 (feature)
  6109. [_c1, c2, c3] = build_commit_graph(
  6110. self.repo.object_store,
  6111. [
  6112. [1], # c1
  6113. [2, 1], # c2 → c1 (master line)
  6114. [3, 1], # c3 → c1 (diverged feature branch)
  6115. ],
  6116. )
  6117. self.repo.refs[b"HEAD"] = c2.id
  6118. self.repo.refs[b"refs/heads/master"] = c2.id
  6119. self.repo.refs[b"refs/heads/feature"] = c3.id
  6120. result = list(porcelain.merged_branches(self.repo))
  6121. self.assertEqual([b"master"], result)
  6122. def test_all_branches_merged(self) -> None:
  6123. """Test when all branches are merged into current."""
  6124. # Create linear history: c1 → c2 → c3 (HEAD)
  6125. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  6126. self.repo.refs[b"HEAD"] = c3.id
  6127. self.repo.refs[b"refs/heads/master"] = c3.id
  6128. self.repo.refs[b"refs/heads/feature-1"] = c2.id # Merged (ancestor)
  6129. self.repo.refs[b"refs/heads/feature-2"] = c1.id # Merged (ancestor)
  6130. branches = list(porcelain.merged_branches(self.repo))
  6131. expected = [b"feature-1", b"master", b"feature-2"]
  6132. expected.sort()
  6133. branches.sort()
  6134. self.assertEqual(expected, branches)
  6135. def test_some_branches_merged(self) -> None:
  6136. """Test when some branches are merged, some are not."""
  6137. # c1 → c2 → c3 (HEAD/master)
  6138. # c1 → c4 → c5 (feature-1 - diverged)
  6139. [_c1, c2, c3, _c4, c5] = build_commit_graph(
  6140. self.repo.object_store,
  6141. [
  6142. [1], # c1
  6143. [2, 1], # c2 → c1 (master line)
  6144. [3, 2], # c3 → c2 (HEAD)
  6145. [4, 1], # c4 → c1 (feature branch)
  6146. [5, 4], # c5 → c4 (feature branch)
  6147. ],
  6148. )
  6149. self.repo.refs[b"HEAD"] = c3.id
  6150. self.repo.refs[b"refs/heads/master"] = c3.id
  6151. self.repo.refs[b"refs/heads/feature-1"] = c5.id # Not merged (diverged)
  6152. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Merged (ancestor)
  6153. branches = list(porcelain.merged_branches(self.repo))
  6154. expected = [b"feature-2", b"master"]
  6155. expected.sort()
  6156. branches.sort()
  6157. self.assertEqual(expected, branches)
  6158. def test_only_current_branch_merged(self) -> None:
  6159. """Test when only current branch exists."""
  6160. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6161. self.repo.refs[b"HEAD"] = c1.id
  6162. self.repo.refs[b"refs/heads/master"] = c1.id
  6163. result = list(porcelain.merged_branches(self.repo))
  6164. self.assertEqual([b"master"], result)
  6165. class BranchNoMergedTests(PorcelainTestCase):
  6166. def test_all_branches_merged(self) -> None:
  6167. """Test when all branches are merged - should return empty list."""
  6168. # Create linear history: c1 → c2 → c3 (HEAD)
  6169. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  6170. self.repo.refs[b"HEAD"] = c3.id
  6171. self.repo.refs[b"refs/heads/master"] = c3.id
  6172. self.repo.refs[b"refs/heads/feature-1"] = c2.id # Merged (ancestor)
  6173. self.repo.refs[b"refs/heads/feature-2"] = c1.id # Merged (ancestor)
  6174. result = list(porcelain.no_merged_branches(self.repo))
  6175. self.assertEqual([], result)
  6176. def test_no_merged_branches(self) -> None:
  6177. """Test with some non-merged branches."""
  6178. # Create complete graph: c1 → c2 (master), c1 → c3 (feature)
  6179. [_c1, c2, c3] = build_commit_graph(
  6180. self.repo.object_store,
  6181. [
  6182. [1], # c1
  6183. [2, 1], # c2 → c1 (master line)
  6184. [3, 1], # c3 → c1 (diverged feature branch)
  6185. ],
  6186. )
  6187. self.repo.refs[b"HEAD"] = c2.id
  6188. self.repo.refs[b"refs/heads/master"] = c2.id
  6189. self.repo.refs[b"refs/heads/feature"] = c3.id
  6190. result = list(porcelain.no_merged_branches(self.repo))
  6191. self.assertEqual([b"feature"], result)
  6192. def test_some_branches_not_merged(self) -> None:
  6193. """Test when some branches are merged, some are not."""
  6194. # c1 → c2 → c3 (HEAD/master)
  6195. # c1 → c4 → c5 (feature-1 - diverged)
  6196. [_c1, c2, c3, _c4, c5] = build_commit_graph(
  6197. self.repo.object_store,
  6198. [
  6199. [1], # c1
  6200. [2, 1], # c2 → c1 (master line)
  6201. [3, 2], # c3 → c2 (HEAD)
  6202. [4, 1], # c4 → c1 (feature branch)
  6203. [5, 4], # c5 → c4 (feature branch)
  6204. ],
  6205. )
  6206. self.repo.refs[b"HEAD"] = c3.id
  6207. self.repo.refs[b"refs/heads/master"] = c3.id
  6208. self.repo.refs[b"refs/heads/feature-1"] = c5.id # Not merged (diverged)
  6209. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Merged (ancestor)
  6210. result = list(porcelain.no_merged_branches(self.repo))
  6211. self.assertEqual([b"feature-1"], result)
  6212. def test_multiple_branches_not_merged(self) -> None:
  6213. """Test with multiple non-merged branches."""
  6214. # c1 → c2 (HEAD/master)
  6215. # c1 → c3 (feature-1 - diverged)
  6216. # c1 → c4 (feature-2 - diverged)
  6217. [_c1, c2, c3, c4] = build_commit_graph(
  6218. self.repo.object_store,
  6219. [
  6220. [1], # c1
  6221. [2, 1], # c2 → c1 (master line)
  6222. [3, 1], # c3 → c1 (feature-1 branch)
  6223. [4, 1], # c4 → c1 (feature-2 branch)
  6224. ],
  6225. )
  6226. self.repo.refs[b"HEAD"] = c2.id
  6227. self.repo.refs[b"refs/heads/master"] = c2.id
  6228. self.repo.refs[b"refs/heads/feature-1"] = c3.id # Not merged (diverged)
  6229. self.repo.refs[b"refs/heads/feature-2"] = c4.id # Not merged (diverged)
  6230. branches = list(porcelain.no_merged_branches(self.repo))
  6231. expected = [b"feature-1", b"feature-2"]
  6232. expected.sort()
  6233. branches.sort()
  6234. self.assertEqual(expected, branches)
  6235. def test_only_current_branch_exists(self) -> None:
  6236. """Test when only current branch exists - should return empty list."""
  6237. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6238. self.repo.refs[b"HEAD"] = c1.id
  6239. self.repo.refs[b"refs/heads/master"] = c1.id
  6240. result = list(porcelain.no_merged_branches(self.repo))
  6241. self.assertEqual([], result)
  6242. class BranchContainsTests(PorcelainTestCase):
  6243. def test_commit_in_single_branch(self) -> None:
  6244. """Test commit contained in only one branch."""
  6245. # Create: c1 → c2 (master), c1 → c3 (feature)
  6246. [_c1, c2, c3] = build_commit_graph(
  6247. self.repo.object_store,
  6248. [
  6249. [1], # c1
  6250. [2, 1], # c2 → c1 (master line)
  6251. [3, 1], # c3 → c1 (feature branch)
  6252. ],
  6253. )
  6254. self.repo.refs[b"HEAD"] = c2.id
  6255. self.repo.refs[b"refs/heads/master"] = c2.id
  6256. self.repo.refs[b"refs/heads/feature"] = c3.id
  6257. # c2 is only in master branch
  6258. result = list(porcelain.branches_containing(self.repo, c2.id.decode()))
  6259. self.assertEqual([b"master"], result)
  6260. # c3 is only in feature branch
  6261. result = list(porcelain.branches_containing(self.repo, c3.id.decode()))
  6262. self.assertEqual([b"feature"], result)
  6263. def test_commit_in_multiple_branches(self) -> None:
  6264. """Test commit contained in multiple branches."""
  6265. # Create: c1 → c2 → c3 (master), c2 → c4 (feature)
  6266. [c1, c2, c3, c4] = build_commit_graph(
  6267. self.repo.object_store,
  6268. [
  6269. [1], # c1
  6270. [2, 1], # c2 → c1
  6271. [3, 2], # c3 → c2 (master)
  6272. [4, 2], # c4 → c2 (feature)
  6273. ],
  6274. )
  6275. self.repo.refs[b"HEAD"] = c3.id
  6276. self.repo.refs[b"refs/heads/master"] = c3.id
  6277. self.repo.refs[b"refs/heads/feature"] = c4.id
  6278. # c2 is in both branches (common ancestor)
  6279. branches = list(porcelain.branches_containing(self.repo, c2.id.decode()))
  6280. expected = [b"master", b"feature"]
  6281. expected.sort()
  6282. branches.sort()
  6283. self.assertEqual(expected, branches)
  6284. # c1 is in both branches (older common ancestor)
  6285. branches = list(porcelain.branches_containing(self.repo, c1.id.decode()))
  6286. expected = [b"master", b"feature"]
  6287. expected.sort()
  6288. branches.sort()
  6289. self.assertEqual(expected, branches)
  6290. def test_commit_in_all_branches(self) -> None:
  6291. """Test commit contained in all branches."""
  6292. # Create linear history: c1 → c2 → c3 (HEAD/master)
  6293. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  6294. self.repo.refs[b"HEAD"] = c3.id
  6295. self.repo.refs[b"refs/heads/master"] = c3.id
  6296. self.repo.refs[b"refs/heads/feature-1"] = c3.id # Same as master
  6297. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Ancestor
  6298. # c1 is in all branches
  6299. branches = list(porcelain.branches_containing(self.repo, c1.id.decode()))
  6300. expected = [b"master", b"feature-1", b"feature-2"]
  6301. expected.sort()
  6302. branches.sort()
  6303. self.assertEqual(expected, branches)
  6304. def test_commit_in_no_branches(self) -> None:
  6305. """Test commit not contained in any branch."""
  6306. # Create: c1 → c2 (master), c1 → c3 (feature), orphan c4
  6307. [_c1, c2, c3, c4] = build_commit_graph(
  6308. self.repo.object_store,
  6309. [
  6310. [1], # c1
  6311. [2, 1], # c2 → c1 (master)
  6312. [3, 1], # c3 → c1 (feature)
  6313. [4], # c4 (orphan commit)
  6314. ],
  6315. )
  6316. self.repo.refs[b"HEAD"] = c2.id
  6317. self.repo.refs[b"refs/heads/master"] = c2.id
  6318. self.repo.refs[b"refs/heads/feature"] = c3.id
  6319. # c4 is not in any branch
  6320. result = list(porcelain.branches_containing(self.repo, c4.id.decode()))
  6321. self.assertEqual([], result)
  6322. def test_commit_ref_by_branch_name(self) -> None:
  6323. """Test using branch name as commit reference."""
  6324. # Create: c1 → c2 (master), c1 → c3 (feature)
  6325. [_c1, c2, c3] = build_commit_graph(
  6326. self.repo.object_store,
  6327. [
  6328. [1], # c1
  6329. [2, 1], # c2 → c1 (master)
  6330. [3, 1], # c3 → c1 (feature)
  6331. ],
  6332. )
  6333. self.repo.refs[b"HEAD"] = c2.id
  6334. self.repo.refs[b"refs/heads/master"] = c2.id
  6335. self.repo.refs[b"refs/heads/feature"] = c3.id
  6336. # Use "master" as commit reference - should find master branch
  6337. result = list(porcelain.branches_containing(self.repo, "master"))
  6338. self.assertEqual([b"master"], result)
  6339. # Use "feature" as commit reference - should find feature branch
  6340. result = list(porcelain.branches_containing(self.repo, "feature"))
  6341. self.assertEqual([b"feature"], result)
  6342. def test_commit_ref_by_head(self) -> None:
  6343. """Test using HEAD as commit reference."""
  6344. # Create: c1 → c2 → c3 (HEAD/master)
  6345. [_c1, c2, c3] = build_commit_graph(
  6346. self.repo.object_store, [[1], [2, 1], [3, 2]]
  6347. )
  6348. self.repo.refs[b"HEAD"] = c3.id
  6349. self.repo.refs[b"refs/heads/master"] = c3.id
  6350. self.repo.refs[b"refs/heads/feature"] = c2.id # Ancestor
  6351. # Use "HEAD" as commit reference
  6352. result = list(porcelain.branches_containing(self.repo, "HEAD"))
  6353. self.assertEqual([b"master"], result)
  6354. def test_invalid_commit_ref(self) -> None:
  6355. """Test with invalid commit reference."""
  6356. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6357. self.repo.refs[b"HEAD"] = c1.id
  6358. self.repo.refs[b"refs/heads/master"] = c1.id
  6359. # Test with non-existent commit
  6360. with self.assertRaises(KeyError) as cm:
  6361. list(porcelain.branches_containing(self.repo, "nonexistent"))
  6362. self.assertEqual(b"nonexistent", cm.exception.args[0])
  6363. # Test with invalid SHA
  6364. with self.assertRaises(KeyError) as cm:
  6365. list(porcelain.branches_containing(self.repo, "invalid-sha"))
  6366. self.assertEqual(b"invalid-sha", cm.exception.args[0])
  6367. def test_short_sha_reference(self) -> None:
  6368. """Test using short SHA as commit reference."""
  6369. # Create: c1 → c2 (master)
  6370. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2, 1]])
  6371. self.repo.refs[b"HEAD"] = c2.id
  6372. self.repo.refs[b"refs/heads/master"] = c2.id
  6373. # Use short SHA (first 7 characters)
  6374. short_sha = c1.id.decode()[:7]
  6375. result = list(porcelain.branches_containing(self.repo, short_sha))
  6376. self.assertEqual([b"master"], result)
  6377. class FilterBranchesByPatternTests(PorcelainTestCase):
  6378. """Tests for filter_branches_by_pattern function."""
  6379. def test_empty_branches(self) -> None:
  6380. """Test with empty branches list."""
  6381. result = porcelain.filter_branches_by_pattern([], "feature-*")
  6382. self.assertEqual([], result)
  6383. def test_star_pattern(self) -> None:
  6384. """Test wildcard pattern matching."""
  6385. branches = [b"main", b"feature-1", b"feature-2", b"develop", b"hotfix-bug"]
  6386. result = porcelain.filter_branches_by_pattern(branches, "feature-*")
  6387. expected = [b"feature-1", b"feature-2"]
  6388. self.assertEqual(expected, result)
  6389. def test_question_mark_pattern(self) -> None:
  6390. """Test single character wildcard pattern."""
  6391. branches = [b"main", b"feature-1", b"feature-2", b"feature-a", b"develop"]
  6392. result = porcelain.filter_branches_by_pattern(branches, "feature-?")
  6393. expected = [b"feature-1", b"feature-2", b"feature-a"]
  6394. self.assertEqual(expected, result)
  6395. def test_specific_pattern(self) -> None:
  6396. """Test exact match pattern."""
  6397. branches = [b"main", b"feature-1", b"feature-2", b"develop"]
  6398. result = porcelain.filter_branches_by_pattern(branches, "feature-1")
  6399. expected = [b"feature-1"]
  6400. self.assertEqual(expected, result)
  6401. def test_no_matches(self) -> None:
  6402. """Test pattern that matches no branches."""
  6403. branches = [b"main", b"feature-1", b"develop"]
  6404. result = porcelain.filter_branches_by_pattern(branches, "release-*")
  6405. self.assertEqual([], result)
  6406. def test_case_sensitive_pattern(self) -> None:
  6407. """Test case-sensitive pattern matching."""
  6408. branches = [b"Main", b"main", b"MAIN", b"develop"]
  6409. result = porcelain.filter_branches_by_pattern(branches, "main")
  6410. expected = [b"main"]
  6411. self.assertEqual(expected, result)
  6412. def test_multiple_patterns_behavior(self) -> None:
  6413. """Test that pattern works with multiple wildcards."""
  6414. branches = [
  6415. b"feature-login",
  6416. b"feature-signup",
  6417. b"bugfix-login",
  6418. b"hotfix-signup",
  6419. ]
  6420. result = porcelain.filter_branches_by_pattern(branches, "feature-*")
  6421. expected = [b"feature-login", b"feature-signup"]
  6422. self.assertEqual(expected, result)
  6423. def test_mixed_encoding_branches(self) -> None:
  6424. """Test with branches that have special characters."""
  6425. branches = [b"feature-1", b"feature/test", b"feature@prod", b"develop"]
  6426. result = porcelain.filter_branches_by_pattern(branches, "feature/*")
  6427. expected = [b"feature/test"]
  6428. self.assertEqual(expected, result)
  6429. def test_pattern_with_square_brackets(self) -> None:
  6430. """Test pattern with character classes."""
  6431. branches = [b"feature-1", b"feature-2", b"feature-a", b"feature-b", b"develop"]
  6432. result = porcelain.filter_branches_by_pattern(branches, "feature-[12]")
  6433. expected = [b"feature-1", b"feature-2"]
  6434. self.assertEqual(expected, result)
  6435. class BranchCreateTests(PorcelainTestCase):
  6436. def test_branch_exists(self) -> None:
  6437. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6438. self.repo[b"HEAD"] = c1.id
  6439. porcelain.branch_create(self.repo, b"foo")
  6440. self.assertRaises(porcelain.Error, porcelain.branch_create, self.repo, b"foo")
  6441. porcelain.branch_create(self.repo, b"foo", force=True)
  6442. def test_new_branch(self) -> None:
  6443. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6444. self.repo[b"HEAD"] = c1.id
  6445. porcelain.branch_create(self.repo, b"foo")
  6446. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  6447. def test_auto_setup_merge_true_from_remote_tracking(self) -> None:
  6448. """Test branch.autoSetupMerge=true sets up tracking from remote-tracking branch."""
  6449. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6450. self.repo[b"HEAD"] = c1.id
  6451. # Create a remote-tracking branch
  6452. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6453. # Set branch.autoSetupMerge to true (default)
  6454. config = self.repo.get_config()
  6455. config.set((b"branch",), b"autoSetupMerge", b"true")
  6456. config.write_to_path()
  6457. # Create branch from remote-tracking branch
  6458. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6459. # Verify tracking was set up
  6460. config = self.repo.get_config()
  6461. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6462. self.assertEqual(
  6463. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6464. )
  6465. def test_auto_setup_merge_false(self) -> None:
  6466. """Test branch.autoSetupMerge=false disables tracking setup."""
  6467. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6468. self.repo[b"HEAD"] = c1.id
  6469. # Create a remote-tracking branch
  6470. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6471. # Set branch.autoSetupMerge to false
  6472. config = self.repo.get_config()
  6473. config.set((b"branch",), b"autoSetupMerge", b"false")
  6474. config.write_to_path()
  6475. # Create branch from remote-tracking branch
  6476. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6477. # Verify tracking was NOT set up
  6478. config = self.repo.get_config()
  6479. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"remote")
  6480. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"merge")
  6481. def test_auto_setup_merge_always(self) -> None:
  6482. """Test branch.autoSetupMerge=always sets up tracking even from local branches."""
  6483. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6484. self.repo[b"HEAD"] = c1.id
  6485. self.repo.refs[b"refs/heads/main"] = c1.id
  6486. # Set branch.autoSetupMerge to always
  6487. config = self.repo.get_config()
  6488. config.set((b"branch",), b"autoSetupMerge", b"always")
  6489. config.write_to_path()
  6490. # Create branch from local branch - normally wouldn't set up tracking
  6491. porcelain.branch_create(self.repo, "feature", "main")
  6492. # With always, tracking should NOT be set up from local branches
  6493. # (Git only sets up tracking from remote-tracking branches even with always)
  6494. config = self.repo.get_config()
  6495. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"remote")
  6496. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"merge")
  6497. def test_auto_setup_merge_always_from_remote(self) -> None:
  6498. """Test branch.autoSetupMerge=always still sets up tracking from remote branches."""
  6499. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6500. self.repo[b"HEAD"] = c1.id
  6501. # Create a remote-tracking branch
  6502. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6503. # Set branch.autoSetupMerge to always
  6504. config = self.repo.get_config()
  6505. config.set((b"branch",), b"autoSetupMerge", b"always")
  6506. config.write_to_path()
  6507. # Create branch from remote-tracking branch
  6508. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6509. # Verify tracking was set up
  6510. config = self.repo.get_config()
  6511. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6512. self.assertEqual(
  6513. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6514. )
  6515. def test_auto_setup_merge_default(self) -> None:
  6516. """Test default behavior (no config) is same as true."""
  6517. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6518. self.repo[b"HEAD"] = c1.id
  6519. # Create a remote-tracking branch
  6520. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6521. # Don't set any config - should default to true
  6522. # Create branch from remote-tracking branch
  6523. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6524. # Verify tracking was set up
  6525. config = self.repo.get_config()
  6526. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6527. self.assertEqual(
  6528. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6529. )
  6530. class BranchDeleteTests(PorcelainTestCase):
  6531. def test_simple(self) -> None:
  6532. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6533. self.repo[b"HEAD"] = c1.id
  6534. porcelain.branch_create(self.repo, b"foo")
  6535. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  6536. porcelain.branch_delete(self.repo, b"foo")
  6537. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  6538. def test_simple_unicode(self) -> None:
  6539. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6540. self.repo[b"HEAD"] = c1.id
  6541. porcelain.branch_create(self.repo, "foo")
  6542. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  6543. porcelain.branch_delete(self.repo, "foo")
  6544. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  6545. class FetchTests(PorcelainTestCase):
  6546. def test_simple(self) -> None:
  6547. outstream = BytesIO()
  6548. errstream = BytesIO()
  6549. # create a file for initial commit
  6550. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6551. os.close(handle)
  6552. porcelain.add(repo=self.repo.path, paths=fullpath)
  6553. porcelain.commit(
  6554. repo=self.repo.path,
  6555. message=b"test",
  6556. author=b"test <email>",
  6557. committer=b"test <email>",
  6558. )
  6559. # Setup target repo
  6560. target_path = tempfile.mkdtemp()
  6561. self.addCleanup(shutil.rmtree, target_path)
  6562. target_repo = porcelain.clone(
  6563. self.repo.path, target=target_path, errstream=errstream
  6564. )
  6565. # create a second file to be pushed
  6566. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6567. os.close(handle)
  6568. porcelain.add(repo=self.repo.path, paths=fullpath)
  6569. porcelain.commit(
  6570. repo=self.repo.path,
  6571. message=b"test2",
  6572. author=b"test2 <email>",
  6573. committer=b"test2 <email>",
  6574. )
  6575. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  6576. target_repo.close()
  6577. # Fetch changes into the cloned repo
  6578. porcelain.fetch(target_path, "origin", outstream=outstream, errstream=errstream)
  6579. # Assert that fetch updated the local image of the remote
  6580. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  6581. # Check the target repo for pushed changes
  6582. with Repo(target_path) as r:
  6583. self.assertIn(self.repo[b"HEAD"].id, r)
  6584. def test_with_remote_name(self) -> None:
  6585. remote_name = "origin"
  6586. outstream = BytesIO()
  6587. errstream = BytesIO()
  6588. # create a file for initial commit
  6589. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6590. os.close(handle)
  6591. porcelain.add(repo=self.repo.path, paths=fullpath)
  6592. porcelain.commit(
  6593. repo=self.repo.path,
  6594. message=b"test",
  6595. author=b"test <email>",
  6596. committer=b"test <email>",
  6597. )
  6598. # Setup target repo
  6599. target_path = tempfile.mkdtemp()
  6600. self.addCleanup(shutil.rmtree, target_path)
  6601. target_repo = porcelain.clone(
  6602. self.repo.path, target=target_path, errstream=errstream
  6603. )
  6604. # Capture current refs
  6605. target_refs = target_repo.get_refs()
  6606. # create a second file to be pushed
  6607. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6608. os.close(handle)
  6609. porcelain.add(repo=self.repo.path, paths=fullpath)
  6610. porcelain.commit(
  6611. repo=self.repo.path,
  6612. message=b"test2",
  6613. author=b"test2 <email>",
  6614. committer=b"test2 <email>",
  6615. )
  6616. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  6617. target_config = target_repo.get_config()
  6618. target_config.set(
  6619. (b"remote", remote_name.encode()), b"url", self.repo.path.encode()
  6620. )
  6621. target_repo.close()
  6622. # Fetch changes into the cloned repo
  6623. porcelain.fetch(
  6624. target_path, remote_name, outstream=outstream, errstream=errstream
  6625. )
  6626. # Assert that fetch updated the local image of the remote
  6627. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  6628. # Check the target repo for pushed changes, as well as updates
  6629. # for the refs
  6630. with Repo(target_path) as r:
  6631. self.assertIn(self.repo[b"HEAD"].id, r)
  6632. self.assertNotEqual(self.repo.get_refs(), target_refs)
  6633. def assert_correct_remote_refs(
  6634. self, local_refs, remote_refs, remote_name=b"origin"
  6635. ) -> None:
  6636. """Assert that known remote refs corresponds to actual remote refs."""
  6637. local_ref_prefix = b"refs/heads"
  6638. remote_ref_prefix = b"refs/remotes/" + remote_name
  6639. locally_known_remote_refs = {
  6640. k[len(remote_ref_prefix) + 1 :]: v
  6641. for k, v in local_refs.items()
  6642. if k.startswith(remote_ref_prefix)
  6643. }
  6644. normalized_remote_refs = {
  6645. k[len(local_ref_prefix) + 1 :]: v
  6646. for k, v in remote_refs.items()
  6647. if k.startswith(local_ref_prefix)
  6648. }
  6649. if b"HEAD" in locally_known_remote_refs and b"HEAD" in remote_refs:
  6650. normalized_remote_refs[b"HEAD"] = remote_refs[b"HEAD"]
  6651. self.assertEqual(locally_known_remote_refs, normalized_remote_refs)
  6652. class RepackTests(PorcelainTestCase):
  6653. def test_empty(self) -> None:
  6654. porcelain.repack(self.repo)
  6655. def test_simple(self) -> None:
  6656. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6657. os.close(handle)
  6658. porcelain.add(repo=self.repo.path, paths=fullpath)
  6659. porcelain.repack(self.repo)
  6660. def test_write_bitmaps(self) -> None:
  6661. """Test that write_bitmaps generates bitmap files."""
  6662. # Create some content
  6663. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6664. os.close(handle)
  6665. with open(fullpath, "w") as f:
  6666. f.write("test content")
  6667. porcelain.add(repo=self.repo.path, paths=fullpath)
  6668. porcelain.commit(
  6669. repo=self.repo.path,
  6670. message=b"test commit",
  6671. author=b"Test Author <test@example.com>",
  6672. committer=b"Test Committer <test@example.com>",
  6673. )
  6674. # Repack with bitmaps
  6675. porcelain.repack(self.repo, write_bitmaps=True)
  6676. # Check that bitmap files were created
  6677. pack_dir = os.path.join(self.repo.path, ".git", "objects", "pack")
  6678. bitmap_files = [f for f in os.listdir(pack_dir) if f.endswith(".bitmap")]
  6679. self.assertGreater(len(bitmap_files), 0)
  6680. class LsTreeTests(PorcelainTestCase):
  6681. def test_empty(self) -> None:
  6682. porcelain.commit(
  6683. repo=self.repo.path,
  6684. message=b"test status",
  6685. author=b"author <email>",
  6686. committer=b"committer <email>",
  6687. )
  6688. f = StringIO()
  6689. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  6690. self.assertEqual(f.getvalue(), "")
  6691. def test_simple(self) -> None:
  6692. # Commit a dummy file then modify it
  6693. fullpath = os.path.join(self.repo.path, "foo")
  6694. with open(fullpath, "w") as f:
  6695. f.write("origstuff")
  6696. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6697. porcelain.commit(
  6698. repo=self.repo.path,
  6699. message=b"test status",
  6700. author=b"author <email>",
  6701. committer=b"committer <email>",
  6702. )
  6703. output = StringIO()
  6704. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  6705. self.assertEqual(
  6706. output.getvalue(),
  6707. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n",
  6708. )
  6709. def test_recursive(self) -> None:
  6710. # Create a directory then write a dummy file in it
  6711. dirpath = os.path.join(self.repo.path, "adir")
  6712. filepath = os.path.join(dirpath, "afile")
  6713. os.mkdir(dirpath)
  6714. with open(filepath, "w") as f:
  6715. f.write("origstuff")
  6716. porcelain.add(repo=self.repo.path, paths=[filepath])
  6717. porcelain.commit(
  6718. repo=self.repo.path,
  6719. message=b"test status",
  6720. author=b"author <email>",
  6721. committer=b"committer <email>",
  6722. )
  6723. output = StringIO()
  6724. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  6725. self.assertEqual(
  6726. output.getvalue(),
  6727. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n",
  6728. )
  6729. output2 = StringIO()
  6730. porcelain.ls_tree(self.repo, b"HEAD", outstream=output2, recursive=True)
  6731. self.assertEqual(
  6732. output2.getvalue(),
  6733. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n"
  6734. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir"
  6735. "/afile\n",
  6736. )
  6737. class LsRemoteTests(PorcelainTestCase):
  6738. def test_empty(self) -> None:
  6739. result = porcelain.ls_remote(self.repo.path)
  6740. self.assertEqual({}, result.refs)
  6741. self.assertEqual({}, result.symrefs)
  6742. def test_some(self) -> None:
  6743. cid = porcelain.commit(
  6744. repo=self.repo.path,
  6745. message=b"test status",
  6746. author=b"author <email>",
  6747. committer=b"committer <email>",
  6748. )
  6749. result = porcelain.ls_remote(self.repo.path)
  6750. self.assertEqual(
  6751. {b"refs/heads/master": cid, b"HEAD": cid},
  6752. result.refs,
  6753. )
  6754. # HEAD should be a symref to refs/heads/master
  6755. self.assertEqual({b"HEAD": b"refs/heads/master"}, result.symrefs)
  6756. class LsFilesTests(PorcelainTestCase):
  6757. def test_empty(self) -> None:
  6758. self.assertEqual([], list(porcelain.ls_files(self.repo)))
  6759. def test_simple(self) -> None:
  6760. # Commit a dummy file then modify it
  6761. fullpath = os.path.join(self.repo.path, "foo")
  6762. with open(fullpath, "w") as f:
  6763. f.write("origstuff")
  6764. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6765. self.assertEqual([b"foo"], list(porcelain.ls_files(self.repo)))
  6766. class RemoteAddTests(PorcelainTestCase):
  6767. def test_new(self) -> None:
  6768. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6769. c = self.repo.get_config()
  6770. self.assertEqual(
  6771. c.get((b"remote", b"jelmer"), b"url"),
  6772. b"git://jelmer.uk/code/dulwich",
  6773. )
  6774. def test_exists(self) -> None:
  6775. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6776. self.assertRaises(
  6777. porcelain.RemoteExists,
  6778. porcelain.remote_add,
  6779. self.repo,
  6780. "jelmer",
  6781. "git://jelmer.uk/code/dulwich",
  6782. )
  6783. class RemoteRemoveTests(PorcelainTestCase):
  6784. def test_remove(self) -> None:
  6785. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6786. c = self.repo.get_config()
  6787. self.assertEqual(
  6788. c.get((b"remote", b"jelmer"), b"url"),
  6789. b"git://jelmer.uk/code/dulwich",
  6790. )
  6791. porcelain.remote_remove(self.repo, "jelmer")
  6792. self.assertRaises(KeyError, porcelain.remote_remove, self.repo, "jelmer")
  6793. c = self.repo.get_config()
  6794. self.assertRaises(KeyError, c.get, (b"remote", b"jelmer"), b"url")
  6795. class CheckIgnoreTests(PorcelainTestCase):
  6796. def test_check_ignored(self) -> None:
  6797. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6798. f.write("foo")
  6799. foo_path = os.path.join(self.repo.path, "foo")
  6800. with open(foo_path, "w") as f:
  6801. f.write("BAR")
  6802. bar_path = os.path.join(self.repo.path, "bar")
  6803. with open(bar_path, "w") as f:
  6804. f.write("BAR")
  6805. self.assertEqual(["foo"], list(porcelain.check_ignore(self.repo, [foo_path])))
  6806. self.assertEqual([], list(porcelain.check_ignore(self.repo, [bar_path])))
  6807. def test_check_added_abs(self) -> None:
  6808. path = os.path.join(self.repo.path, "foo")
  6809. with open(path, "w") as f:
  6810. f.write("BAR")
  6811. self.repo.get_worktree().stage(["foo"])
  6812. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6813. f.write("foo\n")
  6814. self.assertEqual([], list(porcelain.check_ignore(self.repo, [path])))
  6815. self.assertEqual(
  6816. ["foo"],
  6817. list(porcelain.check_ignore(self.repo, [path], no_index=True)),
  6818. )
  6819. def test_check_added_rel(self) -> None:
  6820. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  6821. f.write("BAR")
  6822. self.repo.get_worktree().stage(["foo"])
  6823. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6824. f.write("foo\n")
  6825. cwd = os.getcwd()
  6826. self.addCleanup(os.chdir, cwd)
  6827. os.mkdir(os.path.join(self.repo.path, "bar"))
  6828. os.chdir(os.path.join(self.repo.path, "bar"))
  6829. self.assertEqual(list(porcelain.check_ignore(self.repo, ["../foo"])), [])
  6830. self.assertEqual(
  6831. ["../foo"],
  6832. list(porcelain.check_ignore(self.repo, ["../foo"], no_index=True)),
  6833. )
  6834. class UpdateHeadTests(PorcelainTestCase):
  6835. def test_set_to_branch(self) -> None:
  6836. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6837. self.repo.refs[b"refs/heads/blah"] = c1.id
  6838. porcelain.update_head(self.repo, "blah")
  6839. self.assertEqual(c1.id, self.repo.head())
  6840. self.assertEqual(b"ref: refs/heads/blah", self.repo.refs.read_ref(b"HEAD"))
  6841. def test_set_to_branch_detached(self) -> None:
  6842. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6843. self.repo.refs[b"refs/heads/blah"] = c1.id
  6844. porcelain.update_head(self.repo, "blah", detached=True)
  6845. self.assertEqual(c1.id, self.repo.head())
  6846. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  6847. def test_set_to_commit_detached(self) -> None:
  6848. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6849. self.repo.refs[b"refs/heads/blah"] = c1.id
  6850. porcelain.update_head(self.repo, c1.id, detached=True)
  6851. self.assertEqual(c1.id, self.repo.head())
  6852. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  6853. def test_set_new_branch(self) -> None:
  6854. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6855. self.repo.refs[b"refs/heads/blah"] = c1.id
  6856. porcelain.update_head(self.repo, "blah", new_branch="bar")
  6857. self.assertEqual(c1.id, self.repo.head())
  6858. self.assertEqual(b"ref: refs/heads/bar", self.repo.refs.read_ref(b"HEAD"))
  6859. class MailmapTests(PorcelainTestCase):
  6860. def test_no_mailmap(self) -> None:
  6861. self.assertEqual(
  6862. b"Jelmer Vernooij <jelmer@samba.org>",
  6863. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  6864. )
  6865. def test_mailmap_lookup(self) -> None:
  6866. with open(os.path.join(self.repo.path, ".mailmap"), "wb") as f:
  6867. f.write(
  6868. b"""\
  6869. Jelmer Vernooij <jelmer@debian.org>
  6870. """
  6871. )
  6872. self.assertEqual(
  6873. b"Jelmer Vernooij <jelmer@debian.org>",
  6874. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  6875. )
  6876. class FsckTests(PorcelainTestCase):
  6877. def test_none(self) -> None:
  6878. self.assertEqual([], list(porcelain.fsck(self.repo)))
  6879. def test_git_dir(self) -> None:
  6880. obj = Tree()
  6881. a = Blob()
  6882. a.data = b"foo"
  6883. obj.add(b".git", 0o100644, a.id)
  6884. self.repo.object_store.add_objects([(a, None), (obj, None)])
  6885. self.assertEqual(
  6886. [(obj.id, "invalid name .git")],
  6887. [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)],
  6888. )
  6889. class DescribeTests(PorcelainTestCase):
  6890. def test_no_commits(self) -> None:
  6891. self.assertRaises(KeyError, porcelain.describe, self.repo.path)
  6892. def test_single_commit(self) -> None:
  6893. fullpath = os.path.join(self.repo.path, "foo")
  6894. with open(fullpath, "w") as f:
  6895. f.write("BAR")
  6896. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6897. sha = porcelain.commit(
  6898. self.repo.path,
  6899. message=b"Some message",
  6900. author=b"Joe <joe@example.com>",
  6901. committer=b"Bob <bob@example.com>",
  6902. )
  6903. self.assertEqual(
  6904. "g{}".format(sha[:7].decode("ascii")),
  6905. porcelain.describe(self.repo.path),
  6906. )
  6907. def test_tag(self) -> None:
  6908. fullpath = os.path.join(self.repo.path, "foo")
  6909. with open(fullpath, "w") as f:
  6910. f.write("BAR")
  6911. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6912. porcelain.commit(
  6913. self.repo.path,
  6914. message=b"Some message",
  6915. author=b"Joe <joe@example.com>",
  6916. committer=b"Bob <bob@example.com>",
  6917. )
  6918. porcelain.tag_create(
  6919. self.repo.path,
  6920. b"tryme",
  6921. b"foo <foo@bar.com>",
  6922. b"bar",
  6923. annotated=True,
  6924. )
  6925. self.assertEqual("tryme", porcelain.describe(self.repo.path))
  6926. def test_tag_and_commit(self) -> None:
  6927. fullpath = os.path.join(self.repo.path, "foo")
  6928. with open(fullpath, "w") as f:
  6929. f.write("BAR")
  6930. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6931. porcelain.commit(
  6932. self.repo.path,
  6933. message=b"Some message",
  6934. author=b"Joe <joe@example.com>",
  6935. committer=b"Bob <bob@example.com>",
  6936. )
  6937. porcelain.tag_create(
  6938. self.repo.path,
  6939. b"tryme",
  6940. b"foo <foo@bar.com>",
  6941. b"bar",
  6942. annotated=True,
  6943. )
  6944. with open(fullpath, "w") as f:
  6945. f.write("BAR2")
  6946. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6947. sha = porcelain.commit(
  6948. self.repo.path,
  6949. message=b"Some message",
  6950. author=b"Joe <joe@example.com>",
  6951. committer=b"Bob <bob@example.com>",
  6952. )
  6953. self.assertEqual(
  6954. "tryme-1-g{}".format(sha[:7].decode("ascii")),
  6955. porcelain.describe(self.repo.path),
  6956. )
  6957. def test_tag_and_commit_full(self) -> None:
  6958. fullpath = os.path.join(self.repo.path, "foo")
  6959. with open(fullpath, "w") as f:
  6960. f.write("BAR")
  6961. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6962. porcelain.commit(
  6963. self.repo.path,
  6964. message=b"Some message",
  6965. author=b"Joe <joe@example.com>",
  6966. committer=b"Bob <bob@example.com>",
  6967. )
  6968. porcelain.tag_create(
  6969. self.repo.path,
  6970. b"tryme",
  6971. b"foo <foo@bar.com>",
  6972. b"bar",
  6973. annotated=True,
  6974. )
  6975. with open(fullpath, "w") as f:
  6976. f.write("BAR2")
  6977. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6978. sha = porcelain.commit(
  6979. self.repo.path,
  6980. message=b"Some message",
  6981. author=b"Joe <joe@example.com>",
  6982. committer=b"Bob <bob@example.com>",
  6983. )
  6984. self.assertEqual(
  6985. "tryme-1-g{}".format(sha.decode("ascii")),
  6986. porcelain.describe(self.repo.path, abbrev=40),
  6987. )
  6988. def test_untagged_commit_abbreviation(self) -> None:
  6989. _, _, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]])
  6990. self.repo.refs[b"HEAD"] = c3.id
  6991. brief_description, complete_description = (
  6992. porcelain.describe(self.repo),
  6993. porcelain.describe(self.repo, abbrev=40),
  6994. )
  6995. self.assertTrue(complete_description.startswith(brief_description))
  6996. self.assertEqual(
  6997. "g{}".format(c3.id.decode("ascii")),
  6998. complete_description,
  6999. )
  7000. def test_hash_length_dynamic(self) -> None:
  7001. """Test that hash length adjusts based on uniqueness."""
  7002. fullpath = os.path.join(self.repo.path, "foo")
  7003. with open(fullpath, "w") as f:
  7004. f.write("content")
  7005. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7006. sha = porcelain.commit(
  7007. self.repo.path,
  7008. message=b"commit",
  7009. author=b"Joe <joe@example.com>",
  7010. committer=b"Bob <bob@example.com>",
  7011. )
  7012. # When abbrev is None, it should use find_unique_abbrev
  7013. result = porcelain.describe(self.repo.path)
  7014. # Should start with 'g' and have at least 7 characters
  7015. self.assertTrue(result.startswith("g"))
  7016. self.assertGreaterEqual(len(result[1:]), 7)
  7017. # Should be a prefix of the full SHA
  7018. self.assertTrue(sha.decode("ascii").startswith(result[1:]))
  7019. class PathToTreeTests(PorcelainTestCase):
  7020. def setUp(self) -> None:
  7021. super().setUp()
  7022. self.fp = os.path.join(self.test_dir, "bar")
  7023. with open(self.fp, "w") as f:
  7024. f.write("something")
  7025. oldcwd = os.getcwd()
  7026. self.addCleanup(os.chdir, oldcwd)
  7027. os.chdir(self.test_dir)
  7028. def test_path_to_tree_path_base(self) -> None:
  7029. self.assertEqual(b"bar", porcelain.path_to_tree_path(self.test_dir, self.fp))
  7030. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  7031. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "bar"))
  7032. cwd = os.getcwd()
  7033. self.assertEqual(
  7034. b"bar", porcelain.path_to_tree_path(".", os.path.join(cwd, "bar"))
  7035. )
  7036. self.assertEqual(b"bar", porcelain.path_to_tree_path(cwd, "bar"))
  7037. def test_path_to_tree_path_syntax(self) -> None:
  7038. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  7039. def test_path_to_tree_path_error(self) -> None:
  7040. with self.assertRaises(ValueError):
  7041. with tempfile.TemporaryDirectory() as od:
  7042. porcelain.path_to_tree_path(od, self.fp)
  7043. def test_path_to_tree_path_rel(self) -> None:
  7044. cwd = os.getcwd()
  7045. self.addCleanup(os.chdir, cwd)
  7046. os.mkdir(os.path.join(self.repo.path, "foo"))
  7047. os.mkdir(os.path.join(self.repo.path, "foo/bar"))
  7048. os.chdir(os.path.join(self.repo.path, "foo/bar"))
  7049. with open("baz", "w") as f:
  7050. f.write("contents")
  7051. self.assertEqual(b"bar/baz", porcelain.path_to_tree_path("..", "baz"))
  7052. self.assertEqual(
  7053. b"bar/baz",
  7054. porcelain.path_to_tree_path(
  7055. os.path.join(os.getcwd(), ".."),
  7056. os.path.join(os.getcwd(), "baz"),
  7057. ),
  7058. )
  7059. self.assertEqual(
  7060. b"bar/baz",
  7061. porcelain.path_to_tree_path("..", os.path.join(os.getcwd(), "baz")),
  7062. )
  7063. self.assertEqual(
  7064. b"bar/baz",
  7065. porcelain.path_to_tree_path(os.path.join(os.getcwd(), ".."), "baz"),
  7066. )
  7067. class GetObjectByPathTests(PorcelainTestCase):
  7068. def test_simple(self) -> None:
  7069. fullpath = os.path.join(self.repo.path, "foo")
  7070. with open(fullpath, "w") as f:
  7071. f.write("BAR")
  7072. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7073. porcelain.commit(
  7074. self.repo.path,
  7075. message=b"Some message",
  7076. author=b"Joe <joe@example.com>",
  7077. committer=b"Bob <bob@example.com>",
  7078. )
  7079. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  7080. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  7081. def test_encoding(self) -> None:
  7082. fullpath = os.path.join(self.repo.path, "foo")
  7083. with open(fullpath, "w") as f:
  7084. f.write("BAR")
  7085. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7086. porcelain.commit(
  7087. self.repo.path,
  7088. message=b"Some message",
  7089. author=b"Joe <joe@example.com>",
  7090. committer=b"Bob <bob@example.com>",
  7091. encoding=b"utf-8",
  7092. )
  7093. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  7094. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  7095. def test_missing(self) -> None:
  7096. self.assertRaises(KeyError, porcelain.get_object_by_path, self.repo, "foo")
  7097. class WriteTreeTests(PorcelainTestCase):
  7098. def test_simple(self) -> None:
  7099. fullpath = os.path.join(self.repo.path, "foo")
  7100. with open(fullpath, "w") as f:
  7101. f.write("BAR")
  7102. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7103. self.assertEqual(
  7104. b"d2092c8a9f311f0311083bf8d177f2ca0ab5b241",
  7105. porcelain.write_tree(self.repo),
  7106. )
  7107. class ActiveBranchTests(PorcelainTestCase):
  7108. def test_simple(self) -> None:
  7109. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  7110. class BranchTrackingTests(PorcelainTestCase):
  7111. def test_get_branch_merge(self) -> None:
  7112. # Set up branch tracking configuration
  7113. config = self.repo.get_config()
  7114. config.set((b"branch", b"master"), b"remote", b"origin")
  7115. config.set((b"branch", b"master"), b"merge", b"refs/heads/main")
  7116. config.write_to_path()
  7117. # Test getting merge ref for current branch
  7118. merge_ref = porcelain.get_branch_merge(self.repo)
  7119. self.assertEqual(b"refs/heads/main", merge_ref)
  7120. # Test getting merge ref for specific branch
  7121. merge_ref = porcelain.get_branch_merge(self.repo, b"master")
  7122. self.assertEqual(b"refs/heads/main", merge_ref)
  7123. # Test branch without merge config
  7124. with self.assertRaises(KeyError):
  7125. porcelain.get_branch_merge(self.repo, b"nonexistent")
  7126. def test_set_branch_tracking(self) -> None:
  7127. # Create a new branch
  7128. _sha, _ = _commit_file_with_content(self.repo, "foo", "content\n")
  7129. porcelain.branch_create(self.repo, "feature")
  7130. # Set up tracking
  7131. porcelain.set_branch_tracking(
  7132. self.repo, b"feature", b"upstream", b"refs/heads/main"
  7133. )
  7134. # Verify configuration was written
  7135. config = self.repo.get_config()
  7136. self.assertEqual(b"upstream", config.get((b"branch", b"feature"), b"remote"))
  7137. self.assertEqual(
  7138. b"refs/heads/main", config.get((b"branch", b"feature"), b"merge")
  7139. )
  7140. class FindUniqueAbbrevTests(PorcelainTestCase):
  7141. def test_simple(self) -> None:
  7142. c1, _c2, c3 = build_commit_graph(
  7143. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  7144. )
  7145. self.repo.refs[b"HEAD"] = c3.id
  7146. self.assertEqual(
  7147. c1.id.decode("ascii")[:7],
  7148. porcelain.find_unique_abbrev(self.repo.object_store, c1.id),
  7149. )
  7150. class PackRefsTests(PorcelainTestCase):
  7151. def test_all(self) -> None:
  7152. c1, c2, c3 = build_commit_graph(
  7153. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  7154. )
  7155. self.repo.refs[b"HEAD"] = c3.id
  7156. self.repo.refs[b"refs/heads/master"] = c2.id
  7157. self.repo.refs[b"refs/tags/foo"] = c1.id
  7158. porcelain.pack_refs(self.repo, all=True)
  7159. self.assertEqual(
  7160. self.repo.refs.get_packed_refs(),
  7161. {
  7162. b"refs/heads/master": c2.id,
  7163. b"refs/tags/foo": c1.id,
  7164. },
  7165. )
  7166. def test_not_all(self) -> None:
  7167. c1, c2, c3 = build_commit_graph(
  7168. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  7169. )
  7170. self.repo.refs[b"HEAD"] = c3.id
  7171. self.repo.refs[b"refs/heads/master"] = c2.id
  7172. self.repo.refs[b"refs/tags/foo"] = c1.id
  7173. porcelain.pack_refs(self.repo)
  7174. self.assertEqual(
  7175. self.repo.refs.get_packed_refs(),
  7176. {
  7177. b"refs/tags/foo": c1.id,
  7178. },
  7179. )
  7180. class ServerTests(PorcelainTestCase):
  7181. @contextlib.contextmanager
  7182. def _serving(self):
  7183. with make_server("localhost", 0, self.app) as server:
  7184. thread = threading.Thread(target=server.serve_forever, daemon=True)
  7185. thread.start()
  7186. try:
  7187. yield f"http://localhost:{server.server_port}"
  7188. finally:
  7189. server.shutdown()
  7190. thread.join(10)
  7191. def setUp(self) -> None:
  7192. super().setUp()
  7193. self.served_repo_path = os.path.join(self.test_dir, "served_repo.git")
  7194. self.served_repo = Repo.init_bare(self.served_repo_path, mkdir=True)
  7195. self.addCleanup(self.served_repo.close)
  7196. backend = DictBackend({"/": self.served_repo})
  7197. self.app = make_wsgi_chain(backend)
  7198. def test_pull(self) -> None:
  7199. (c1,) = build_commit_graph(self.served_repo.object_store, [[1]])
  7200. self.served_repo.refs[b"refs/heads/master"] = c1.id
  7201. with self._serving() as url:
  7202. porcelain.pull(self.repo, url, "master")
  7203. def test_push(self) -> None:
  7204. (c1,) = build_commit_graph(self.repo.object_store, [[1]])
  7205. self.repo.refs[b"refs/heads/master"] = c1.id
  7206. with self._serving() as url:
  7207. porcelain.push(self.repo, url, "master")
  7208. class ForEachTests(PorcelainTestCase):
  7209. def setUp(self) -> None:
  7210. super().setUp()
  7211. c1, c2, c3, c4 = build_commit_graph(
  7212. self.repo.object_store, [[1], [2, 1], [3, 1, 2], [4]]
  7213. )
  7214. porcelain.tag_create(
  7215. self.repo.path,
  7216. b"v0.1",
  7217. objectish=c1.id,
  7218. annotated=True,
  7219. message=b"0.1",
  7220. )
  7221. porcelain.tag_create(
  7222. self.repo.path,
  7223. b"v1.0",
  7224. objectish=c2.id,
  7225. annotated=True,
  7226. message=b"1.0",
  7227. )
  7228. porcelain.tag_create(self.repo.path, b"simple-tag", objectish=c3.id)
  7229. porcelain.tag_create(
  7230. self.repo.path,
  7231. b"v1.1",
  7232. objectish=c4.id,
  7233. annotated=True,
  7234. message=b"1.1",
  7235. )
  7236. porcelain.branch_create(
  7237. self.repo.path, b"feat", objectish=c2.id.decode("ascii")
  7238. )
  7239. self.repo.refs[b"HEAD"] = c4.id
  7240. def test_for_each_ref(self) -> None:
  7241. refs = porcelain.for_each_ref(self.repo)
  7242. self.assertEqual(
  7243. [(object_type, tag) for _, object_type, tag in refs],
  7244. [
  7245. (b"commit", b"refs/heads/feat"),
  7246. (b"commit", b"refs/heads/master"),
  7247. (b"commit", b"refs/tags/simple-tag"),
  7248. (b"tag", b"refs/tags/v0.1"),
  7249. (b"tag", b"refs/tags/v1.0"),
  7250. (b"tag", b"refs/tags/v1.1"),
  7251. ],
  7252. )
  7253. def test_for_each_ref_pattern(self) -> None:
  7254. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v*")
  7255. self.assertEqual(
  7256. [(object_type, tag) for _, object_type, tag in versions],
  7257. [
  7258. (b"tag", b"refs/tags/v0.1"),
  7259. (b"tag", b"refs/tags/v1.0"),
  7260. (b"tag", b"refs/tags/v1.1"),
  7261. ],
  7262. )
  7263. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v1.?")
  7264. self.assertEqual(
  7265. [(object_type, tag) for _, object_type, tag in versions],
  7266. [
  7267. (b"tag", b"refs/tags/v1.0"),
  7268. (b"tag", b"refs/tags/v1.1"),
  7269. ],
  7270. )
  7271. class SparseCheckoutTests(PorcelainTestCase):
  7272. """Integration tests for Dulwich's sparse checkout feature."""
  7273. # NOTE: We do NOT override `setUp()` here because the parent class
  7274. # (PorcelainTestCase) already:
  7275. # 1) Creates self.test_dir = a unique temp dir
  7276. # 2) Creates a subdir named "repo"
  7277. # 3) Calls Repo.init() on that path
  7278. # Re-initializing again caused FileExistsError.
  7279. #
  7280. # Utility/Placeholder
  7281. #
  7282. def sparse_checkout(self, repo, patterns, force=False):
  7283. """Wrapper around the actual porcelain.sparse_checkout function
  7284. to handle any test-specific setup or logging.
  7285. """
  7286. return porcelain.sparse_checkout(repo, patterns, force=force)
  7287. def _write_file(self, rel_path, content):
  7288. """Helper to write a file in the repository working tree."""
  7289. abs_path = os.path.join(self.repo_path, rel_path)
  7290. os.makedirs(os.path.dirname(abs_path), exist_ok=True)
  7291. with open(abs_path, "w") as f:
  7292. f.write(content)
  7293. return abs_path
  7294. def _commit_file(self, rel_path, content):
  7295. """Helper to write, add, and commit a file."""
  7296. abs_path = self._write_file(rel_path, content)
  7297. add(self.repo_path, paths=[abs_path])
  7298. commit(self.repo_path, message=b"Added " + rel_path.encode("utf-8"))
  7299. def _list_wtree_files(self):
  7300. """Return a set of all files (not dirs) present
  7301. in the working tree, ignoring .git/.
  7302. """
  7303. found_files = set()
  7304. for root, dirs, files in os.walk(self.repo_path):
  7305. # Skip .git in the walk
  7306. if ".git" in dirs:
  7307. dirs.remove(".git")
  7308. for filename in files:
  7309. file_rel = os.path.relpath(os.path.join(root, filename), self.repo_path)
  7310. found_files.add(file_rel)
  7311. return found_files
  7312. def test_only_included_paths_appear_in_wtree(self):
  7313. """Only included paths remain in the working tree, excluded paths are removed.
  7314. Commits two files, "keep_me.txt" and "exclude_me.txt". Then applies a
  7315. sparse-checkout pattern containing only "keep_me.txt". Ensures that
  7316. the latter remains in the working tree, while "exclude_me.txt" is
  7317. removed. This verifies correct application of sparse-checkout patterns
  7318. to remove files not listed.
  7319. """
  7320. self._commit_file("keep_me.txt", "I'll stay\n")
  7321. self._commit_file("exclude_me.txt", "I'll be excluded\n")
  7322. patterns = ["keep_me.txt"]
  7323. self.sparse_checkout(self.repo, patterns)
  7324. actual_files = self._list_wtree_files()
  7325. expected_files = {"keep_me.txt"}
  7326. self.assertEqual(
  7327. expected_files,
  7328. actual_files,
  7329. f"Expected only {expected_files}, but found {actual_files}",
  7330. )
  7331. def test_previously_included_paths_become_excluded(self):
  7332. """Previously included files become excluded after pattern changes.
  7333. Verifies that files initially brought into the working tree (e.g.,
  7334. by including `data/`) can later be excluded by narrowing the
  7335. sparse-checkout pattern to just `data/included_1.txt`. Confirms that
  7336. the file `data/included_2.txt` remains in the index with
  7337. skip-worktree set (rather than being removed entirely), ensuring
  7338. data is not lost and Dulwich correctly updates the index flags.
  7339. """
  7340. self._commit_file("data/included_1.txt", "some content\n")
  7341. self._commit_file("data/included_2.txt", "other content\n")
  7342. initial_patterns = ["data/"]
  7343. self.sparse_checkout(self.repo, initial_patterns)
  7344. updated_patterns = ["data/included_1.txt"]
  7345. self.sparse_checkout(self.repo, updated_patterns)
  7346. actual_files = self._list_wtree_files()
  7347. expected_files = {os.path.join("data", "included_1.txt")}
  7348. self.assertEqual(expected_files, actual_files)
  7349. idx = self.repo.open_index()
  7350. self.assertIn(b"data/included_2.txt", idx)
  7351. entry = idx[b"data/included_2.txt"]
  7352. self.assertTrue(entry.skip_worktree)
  7353. def test_force_removes_local_changes_for_excluded_paths(self):
  7354. """Forced sparse checkout removes local modifications for newly excluded paths.
  7355. Verifies that specifying force=True allows destructive operations
  7356. which discard uncommitted changes. First, we commit "file1.txt" and
  7357. then modify it. Next, we apply a pattern that excludes the file,
  7358. using force=True. The local modifications (and the file) should
  7359. be removed, leaving the working tree empty.
  7360. """
  7361. self._commit_file("file1.txt", "original content\n")
  7362. file1_path = os.path.join(self.repo_path, "file1.txt")
  7363. with open(file1_path, "a") as f:
  7364. f.write("local changes!\n")
  7365. new_patterns = ["some_other_file.txt"]
  7366. self.sparse_checkout(self.repo, new_patterns, force=True)
  7367. actual_files = self._list_wtree_files()
  7368. self.assertEqual(
  7369. set(),
  7370. actual_files,
  7371. "Force-sparse-checkout did not remove file with local changes.",
  7372. )
  7373. def test_destructive_refuse_uncommitted_changes_without_force(self):
  7374. """Fail on uncommitted changes for newly excluded paths without force.
  7375. Ensures that a sparse checkout is blocked if it would remove local
  7376. modifications from the working tree. We commit 'config.yaml', then
  7377. modify it, and finally attempt to exclude it via new patterns without
  7378. using force=True. This should raise a CheckoutError rather than
  7379. discarding the local changes.
  7380. """
  7381. self._commit_file("config.yaml", "initial\n")
  7382. cfg_path = os.path.join(self.repo_path, "config.yaml")
  7383. with open(cfg_path, "a") as f:
  7384. f.write("local modifications\n")
  7385. exclude_patterns = ["docs/"]
  7386. with self.assertRaises(CheckoutError):
  7387. self.sparse_checkout(self.repo, exclude_patterns, force=False)
  7388. def test_fnmatch_gitignore_pattern_expansion(self):
  7389. """Reading/writing patterns align with gitignore/fnmatch expansions.
  7390. Ensures that `sparse_checkout` interprets wildcard patterns (like `*.py`)
  7391. in the same way Git's sparse-checkout would. Multiple files are committed
  7392. to `src/` (e.g. `foo.py`, `foo_test.py`, `foo_helper.py`) and to `docs/`.
  7393. Then the pattern `src/foo*.py` is applied, confirming that only the
  7394. matching Python files remain in the working tree while the Markdown file
  7395. under `docs/` is excluded.
  7396. Finally, verifies that the `.git/info/sparse-checkout` file contains the
  7397. specified wildcard pattern (`src/foo*.py`), ensuring correct round-trip
  7398. of user-supplied patterns.
  7399. """
  7400. self._commit_file("src/foo.py", "print('hello')\n")
  7401. self._commit_file("src/foo_test.py", "print('test')\n")
  7402. self._commit_file("docs/readme.md", "# docs\n")
  7403. self._commit_file("src/foo_helper.py", "print('helper')\n")
  7404. patterns = ["src/foo*.py"]
  7405. self.sparse_checkout(self.repo, patterns)
  7406. actual_files = self._list_wtree_files()
  7407. expected_files = {
  7408. os.path.join("src", "foo.py"),
  7409. os.path.join("src", "foo_test.py"),
  7410. os.path.join("src", "foo_helper.py"),
  7411. }
  7412. self.assertEqual(
  7413. expected_files,
  7414. actual_files,
  7415. "Wildcard pattern not matched as expected. Either too strict or too broad.",
  7416. )
  7417. sc_file = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7418. self.assertTrue(os.path.isfile(sc_file))
  7419. with open(sc_file) as f:
  7420. lines = f.read().strip().split()
  7421. self.assertIn("src/foo*.py", lines)
  7422. class ConeModeTests(PorcelainTestCase):
  7423. """Provide integration tests for Dulwich's cone mode sparse checkout.
  7424. This test suite verifies the expected behavior for:
  7425. * cone_mode_init
  7426. * cone_mode_set
  7427. * cone_mode_add
  7428. Although Dulwich does not yet implement cone mode, these tests are
  7429. prepared in advance to guide future development.
  7430. """
  7431. def setUp(self):
  7432. """Set up a fresh repository for each test.
  7433. This method creates a new empty repo_path and Repo object
  7434. as provided by the PorcelainTestCase base class.
  7435. """
  7436. super().setUp()
  7437. def _commit_file(self, rel_path, content=b"contents"):
  7438. """Add a file at the given relative path and commit it.
  7439. Creates necessary directories, writes the file content,
  7440. stages, and commits. The commit message and author/committer
  7441. are also provided.
  7442. """
  7443. full_path = os.path.join(self.repo_path, rel_path)
  7444. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  7445. with open(full_path, "wb") as f:
  7446. f.write(content)
  7447. porcelain.add(self.repo_path, paths=[full_path])
  7448. porcelain.commit(
  7449. self.repo_path,
  7450. message=b"Adding " + rel_path.encode("utf-8"),
  7451. author=b"Test Author <author@example.com>",
  7452. committer=b"Test Committer <committer@example.com>",
  7453. )
  7454. def _list_wtree_files(self):
  7455. """Return a set of all file paths relative to the repository root.
  7456. Walks the working tree, skipping the .git directory.
  7457. """
  7458. found_files = set()
  7459. for root, dirs, files in os.walk(self.repo_path):
  7460. if ".git" in dirs:
  7461. dirs.remove(".git")
  7462. for fn in files:
  7463. relp = os.path.relpath(os.path.join(root, fn), self.repo_path)
  7464. found_files.add(relp)
  7465. return found_files
  7466. def test_init_excludes_everything(self):
  7467. """Verify that cone_mode_init writes minimal patterns and empties the working tree.
  7468. Make some dummy files, commit them, then call cone_mode_init. Confirm
  7469. that the working tree is empty, the sparse-checkout file has the
  7470. minimal patterns (/*, !/*/), and the relevant config values are set.
  7471. """
  7472. self._commit_file("docs/readme.md", b"# doc\n")
  7473. self._commit_file("src/main.py", b"print('hello')\n")
  7474. porcelain.cone_mode_init(self.repo)
  7475. actual_files = self._list_wtree_files()
  7476. self.assertEqual(
  7477. set(),
  7478. actual_files,
  7479. "cone_mode_init did not exclude all files from the working tree.",
  7480. )
  7481. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7482. with open(sp_path) as f:
  7483. lines = [ln.strip() for ln in f if ln.strip()]
  7484. self.assertIn("/*", lines)
  7485. self.assertIn("!/*/", lines)
  7486. config = self.repo.get_config()
  7487. self.assertEqual(config.get((b"core",), b"sparseCheckout"), b"true")
  7488. self.assertEqual(config.get((b"core",), b"sparseCheckoutCone"), b"true")
  7489. def test_set_specific_dirs(self):
  7490. """Verify that cone_mode_set overwrites the included directories to only the specified ones.
  7491. Initializes cone mode, commits some files, then calls cone_mode_set with
  7492. a list of directories. Expects that only those directories remain in the
  7493. working tree.
  7494. """
  7495. porcelain.cone_mode_init(self.repo)
  7496. self._commit_file("docs/readme.md", b"# doc\n")
  7497. self._commit_file("src/main.py", b"print('hello')\n")
  7498. self._commit_file("tests/test_foo.py", b"# tests\n")
  7499. # Everything is still excluded initially by init.
  7500. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  7501. actual_files = self._list_wtree_files()
  7502. expected_files = {
  7503. os.path.join("docs", "readme.md"),
  7504. os.path.join("src", "main.py"),
  7505. }
  7506. self.assertEqual(
  7507. expected_files,
  7508. actual_files,
  7509. "Did not see only the 'docs/' and 'src/' dirs in the working tree.",
  7510. )
  7511. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7512. with open(sp_path) as f:
  7513. lines = [ln.strip() for ln in f if ln.strip()]
  7514. # For standard cone mode, we'd expect lines like:
  7515. # /* (include top-level files)
  7516. # !/*/ (exclude subdirectories)
  7517. # !/docs/ (re-include docs)
  7518. # !/src/ (re-include src)
  7519. # Instead of the wildcard-based lines the old test used.
  7520. self.assertIn("/*", lines)
  7521. self.assertIn("!/*/", lines)
  7522. self.assertIn("/docs/", lines)
  7523. self.assertIn("/src/", lines)
  7524. self.assertNotIn("/tests/", lines)
  7525. def test_set_overwrites_old_dirs(self):
  7526. """Ensure that calling cone_mode_set again overwrites old includes.
  7527. Initializes cone mode, includes two directories, then calls
  7528. cone_mode_set again with a different directory to confirm the
  7529. new set of includes replaces the old.
  7530. """
  7531. porcelain.cone_mode_init(self.repo)
  7532. self._commit_file("docs/readme.md")
  7533. self._commit_file("src/main.py")
  7534. self._commit_file("tests/test_bar.py")
  7535. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  7536. self.assertEqual(
  7537. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  7538. self._list_wtree_files(),
  7539. )
  7540. # Overwrite includes, now only 'tests'
  7541. porcelain.cone_mode_set(self.repo, dirs=["tests"], force=True)
  7542. actual_files = self._list_wtree_files()
  7543. expected_files = {os.path.join("tests", "test_bar.py")}
  7544. self.assertEqual(expected_files, actual_files)
  7545. def test_force_removal_of_local_mods(self):
  7546. """Confirm that force=True removes local changes in excluded paths.
  7547. cone_mode_init and cone_mode_set are called, a file is locally modified,
  7548. and then cone_mode_set is called again with force=True to exclude that path.
  7549. The excluded file should be removed with no CheckoutError.
  7550. """
  7551. porcelain.cone_mode_init(self.repo)
  7552. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  7553. self._commit_file("docs/readme.md", b"Docs stuff\n")
  7554. self._commit_file("src/main.py", b"print('hello')\n")
  7555. # Modify src/main.py
  7556. with open(os.path.join(self.repo_path, "src/main.py"), "ab") as f:
  7557. f.write(b"extra line\n")
  7558. # Exclude src/ with force=True
  7559. porcelain.cone_mode_set(self.repo, dirs=["docs"], force=True)
  7560. actual_files = self._list_wtree_files()
  7561. expected_files = {os.path.join("docs", "readme.md")}
  7562. self.assertEqual(expected_files, actual_files)
  7563. def test_add_and_merge_dirs(self):
  7564. """Verify that cone_mode_add merges new directories instead of overwriting them.
  7565. After initializing cone mode and including a single directory, call
  7566. cone_mode_add with a new directory. Confirm that both directories
  7567. remain included. Repeat for an additional directory to ensure it
  7568. is merged, not overwritten.
  7569. """
  7570. porcelain.cone_mode_init(self.repo)
  7571. self._commit_file("docs/readme.md", b"# doc\n")
  7572. self._commit_file("src/main.py", b"print('hello')\n")
  7573. self._commit_file("tests/test_bar.py", b"# tests\n")
  7574. # Include "docs" only
  7575. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  7576. self.assertEqual({os.path.join("docs", "readme.md")}, self._list_wtree_files())
  7577. # Add "src"
  7578. porcelain.cone_mode_add(self.repo, dirs=["src"])
  7579. actual_files = self._list_wtree_files()
  7580. self.assertEqual(
  7581. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  7582. actual_files,
  7583. )
  7584. # Add "tests" as well
  7585. porcelain.cone_mode_add(self.repo, dirs=["tests"])
  7586. actual_files = self._list_wtree_files()
  7587. expected_files = {
  7588. os.path.join("docs", "readme.md"),
  7589. os.path.join("src", "main.py"),
  7590. os.path.join("tests", "test_bar.py"),
  7591. }
  7592. self.assertEqual(expected_files, actual_files)
  7593. # Check .git/info/sparse-checkout
  7594. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7595. with open(sp_path) as f:
  7596. lines = [ln.strip() for ln in f if ln.strip()]
  7597. # Standard cone mode lines:
  7598. # "/*" -> include top-level
  7599. # "!/*/" -> exclude subdirectories
  7600. # "!/docs/", "!/src/", "!/tests/" -> re-include the directories we added
  7601. self.assertIn("/*", lines)
  7602. self.assertIn("!/*/", lines)
  7603. self.assertIn("/docs/", lines)
  7604. self.assertIn("/src/", lines)
  7605. self.assertIn("/tests/", lines)
  7606. class UnpackObjectsTest(PorcelainTestCase):
  7607. def test_unpack_objects(self):
  7608. """Test unpacking objects from a pack file."""
  7609. # Create a test repository with some objects
  7610. b1 = Blob()
  7611. b1.data = b"test content 1"
  7612. b2 = Blob()
  7613. b2.data = b"test content 2"
  7614. # Add objects to the repo
  7615. self.repo.object_store.add_object(b1)
  7616. self.repo.object_store.add_object(b2)
  7617. # Create a pack file with these objects
  7618. pack_path = os.path.join(self.test_dir, "test_pack")
  7619. with (
  7620. open(pack_path + ".pack", "wb") as pack_f,
  7621. open(pack_path + ".idx", "wb") as idx_f,
  7622. ):
  7623. porcelain.pack_objects(
  7624. self.repo,
  7625. [b1.id, b2.id],
  7626. pack_f,
  7627. idx_f,
  7628. )
  7629. # Create a new repository to unpack into
  7630. target_repo_path = os.path.join(self.test_dir, "target_repo")
  7631. target_repo = Repo.init(target_repo_path, mkdir=True)
  7632. self.addCleanup(target_repo.close)
  7633. # Unpack the objects
  7634. count = porcelain.unpack_objects(pack_path + ".pack", target_repo_path)
  7635. # Verify the objects were unpacked
  7636. self.assertEqual(2, count)
  7637. self.assertIn(b1.id, target_repo.object_store)
  7638. self.assertIn(b2.id, target_repo.object_store)
  7639. # Verify the content is correct
  7640. unpacked_b1 = target_repo.object_store[b1.id]
  7641. unpacked_b2 = target_repo.object_store[b2.id]
  7642. self.assertEqual(b1.data, unpacked_b1.data)
  7643. self.assertEqual(b2.data, unpacked_b2.data)
  7644. class CountObjectsTests(PorcelainTestCase):
  7645. def test_count_objects_empty_repo(self):
  7646. """Test counting objects in an empty repository."""
  7647. stats = porcelain.count_objects(self.repo)
  7648. self.assertEqual(0, stats.count)
  7649. self.assertEqual(0, stats.size)
  7650. def test_count_objects_verbose_empty_repo(self):
  7651. """Test verbose counting in an empty repository."""
  7652. stats = porcelain.count_objects(self.repo, verbose=True)
  7653. self.assertEqual(0, stats.count)
  7654. self.assertEqual(0, stats.size)
  7655. self.assertEqual(0, stats.in_pack)
  7656. self.assertEqual(0, stats.packs)
  7657. self.assertEqual(0, stats.size_pack)
  7658. def test_count_objects_with_loose_objects(self):
  7659. """Test counting loose objects."""
  7660. # Create some loose objects
  7661. blob1 = make_object(Blob, data=b"data1")
  7662. blob2 = make_object(Blob, data=b"data2")
  7663. self.repo.object_store.add_object(blob1)
  7664. self.repo.object_store.add_object(blob2)
  7665. stats = porcelain.count_objects(self.repo)
  7666. self.assertEqual(2, stats.count)
  7667. self.assertGreater(stats.size, 0)
  7668. def test_count_objects_verbose_with_objects(self):
  7669. """Test verbose counting with both loose and packed objects."""
  7670. # Add some loose objects
  7671. for i in range(3):
  7672. blob = make_object(Blob, data=f"data{i}".encode())
  7673. self.repo.object_store.add_object(blob)
  7674. # Create a simple commit to have some objects in a pack
  7675. tree = Tree()
  7676. c1 = make_commit(tree=tree.id, message=b"Test commit")
  7677. self.repo.object_store.add_objects([(tree, None), (c1, None)])
  7678. self.repo.refs[b"HEAD"] = c1.id
  7679. # Repack to create a pack file
  7680. porcelain.repack(self.repo)
  7681. stats = porcelain.count_objects(self.repo, verbose=True)
  7682. # After repacking, loose objects might be cleaned up
  7683. self.assertIsInstance(stats.count, int)
  7684. self.assertIsInstance(stats.size, int)
  7685. self.assertGreater(stats.in_pack, 0) # Should have packed objects
  7686. self.assertGreater(stats.packs, 0) # Should have at least one pack
  7687. self.assertGreater(stats.size_pack, 0) # Pack should have size
  7688. # Verify it's the correct dataclass type
  7689. self.assertIsInstance(stats, CountObjectsResult)
  7690. class PruneTests(PorcelainTestCase):
  7691. def test_prune_removes_old_tempfiles(self):
  7692. """Test that prune removes old temporary files."""
  7693. # Create an old temporary file in the objects directory
  7694. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7695. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_test")
  7696. with open(tmp_pack_path, "wb") as f:
  7697. f.write(b"old temporary data")
  7698. # Make it old
  7699. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  7700. os.utime(tmp_pack_path, (old_time, old_time))
  7701. # Run prune
  7702. porcelain.prune(self.repo.path)
  7703. # Verify the file was removed
  7704. self.assertFalse(os.path.exists(tmp_pack_path))
  7705. def test_prune_keeps_recent_tempfiles(self):
  7706. """Test that prune keeps recent temporary files."""
  7707. # Create a recent temporary file
  7708. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7709. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_recent")
  7710. with open(tmp_pack_path, "wb") as f:
  7711. f.write(b"recent temporary data")
  7712. self.addCleanup(os.remove, tmp_pack_path)
  7713. # Run prune
  7714. porcelain.prune(self.repo.path)
  7715. # Verify the file was NOT removed
  7716. self.assertTrue(os.path.exists(tmp_pack_path))
  7717. def test_prune_with_custom_grace_period(self):
  7718. """Test prune with custom grace period."""
  7719. # Create a 1-hour-old temporary file
  7720. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7721. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_1hour")
  7722. with open(tmp_pack_path, "wb") as f:
  7723. f.write(b"1 hour old data")
  7724. # Make it 1 hour old
  7725. old_time = time.time() - 3600
  7726. os.utime(tmp_pack_path, (old_time, old_time))
  7727. # Prune with 30-minute grace period should remove it
  7728. porcelain.prune(self.repo.path, grace_period=1800)
  7729. # Verify the file was removed
  7730. self.assertFalse(os.path.exists(tmp_pack_path))
  7731. def test_prune_dry_run(self):
  7732. """Test prune in dry-run mode."""
  7733. # Create an old temporary file
  7734. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7735. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_dryrun")
  7736. with open(tmp_pack_path, "wb") as f:
  7737. f.write(b"old temporary data")
  7738. self.addCleanup(os.remove, tmp_pack_path)
  7739. # Make it old
  7740. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  7741. os.utime(tmp_pack_path, (old_time, old_time))
  7742. # Run prune in dry-run mode
  7743. porcelain.prune(self.repo.path, dry_run=True)
  7744. # Verify the file was NOT removed (dry run)
  7745. self.assertTrue(os.path.exists(tmp_pack_path))
  7746. class FilterBranchTests(PorcelainTestCase):
  7747. def setUp(self):
  7748. super().setUp()
  7749. # Create initial commits with different authors
  7750. from dulwich.objects import Commit, Tree
  7751. # Create actual tree and blob objects
  7752. tree = Tree()
  7753. self.repo.object_store.add_object(tree)
  7754. c1 = Commit()
  7755. c1.tree = tree.id
  7756. c1.parents = []
  7757. c1.author = b"Old Author <old@example.com>"
  7758. c1.author_time = 1000
  7759. c1.author_timezone = 0
  7760. c1.committer = b"Old Committer <old@example.com>"
  7761. c1.commit_time = 1000
  7762. c1.commit_timezone = 0
  7763. c1.message = b"Initial commit"
  7764. self.repo.object_store.add_object(c1)
  7765. c2 = Commit()
  7766. c2.tree = tree.id
  7767. c2.parents = [c1.id]
  7768. c2.author = b"Another Author <another@example.com>"
  7769. c2.author_time = 2000
  7770. c2.author_timezone = 0
  7771. c2.committer = b"Another Committer <another@example.com>"
  7772. c2.commit_time = 2000
  7773. c2.commit_timezone = 0
  7774. c2.message = b"Second commit\n\nWith body"
  7775. self.repo.object_store.add_object(c2)
  7776. c3 = Commit()
  7777. c3.tree = tree.id
  7778. c3.parents = [c2.id]
  7779. c3.author = b"Third Author <third@example.com>"
  7780. c3.author_time = 3000
  7781. c3.author_timezone = 0
  7782. c3.committer = b"Third Committer <third@example.com>"
  7783. c3.commit_time = 3000
  7784. c3.commit_timezone = 0
  7785. c3.message = b"Third commit"
  7786. self.repo.object_store.add_object(c3)
  7787. self.repo.refs[b"refs/heads/master"] = c3.id
  7788. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  7789. # Store IDs for test assertions
  7790. self.c1_id = c1.id
  7791. self.c2_id = c2.id
  7792. self.c3_id = c3.id
  7793. def test_filter_branch_author(self):
  7794. """Test filtering branch with author changes."""
  7795. def filter_author(author):
  7796. # Change all authors to "New Author"
  7797. return b"New Author <new@example.com>"
  7798. result = porcelain.filter_branch(
  7799. self.repo_path, "master", filter_author=filter_author
  7800. )
  7801. # Check that we have mappings for all commits
  7802. self.assertEqual(len(result), 3)
  7803. # Verify the branch ref was updated
  7804. new_head = self.repo.refs[b"refs/heads/master"]
  7805. self.assertNotEqual(new_head, self.c3_id)
  7806. # Verify the original ref was saved
  7807. original_ref = self.repo.refs[b"refs/original/refs/heads/master"]
  7808. self.assertEqual(original_ref, self.c3_id)
  7809. # Check that authors were updated
  7810. new_commit = self.repo[new_head]
  7811. self.assertEqual(new_commit.author, b"New Author <new@example.com>")
  7812. # Check parent chain
  7813. parent = self.repo[new_commit.parents[0]]
  7814. self.assertEqual(parent.author, b"New Author <new@example.com>")
  7815. def test_filter_branch_message(self):
  7816. """Test filtering branch with message changes."""
  7817. def filter_message(message):
  7818. # Add prefix to all messages
  7819. return b"[FILTERED] " + message
  7820. porcelain.filter_branch(self.repo_path, "master", filter_message=filter_message)
  7821. # Verify messages were updated
  7822. new_head = self.repo.refs[b"refs/heads/master"]
  7823. new_commit = self.repo[new_head]
  7824. self.assertTrue(new_commit.message.startswith(b"[FILTERED] "))
  7825. def test_filter_branch_custom_filter(self):
  7826. """Test filtering branch with custom filter function."""
  7827. def custom_filter(commit):
  7828. # Change both author and message
  7829. return {
  7830. "author": b"Custom Author <custom@example.com>",
  7831. "message": b"Custom: " + commit.message,
  7832. }
  7833. porcelain.filter_branch(self.repo_path, "master", filter_fn=custom_filter)
  7834. # Verify custom filter was applied
  7835. new_head = self.repo.refs[b"refs/heads/master"]
  7836. new_commit = self.repo[new_head]
  7837. self.assertEqual(new_commit.author, b"Custom Author <custom@example.com>")
  7838. self.assertTrue(new_commit.message.startswith(b"Custom: "))
  7839. def test_filter_branch_no_changes(self):
  7840. """Test filtering branch with no changes."""
  7841. result = porcelain.filter_branch(self.repo_path, "master")
  7842. # All commits should map to themselves
  7843. for old_sha, new_sha in result.items():
  7844. self.assertEqual(old_sha, new_sha)
  7845. # HEAD should be unchanged
  7846. self.assertEqual(self.repo.refs[b"refs/heads/master"], self.c3_id)
  7847. def test_filter_branch_force(self):
  7848. """Test force filtering a previously filtered branch."""
  7849. # First filter
  7850. porcelain.filter_branch(
  7851. self.repo_path, "master", filter_message=lambda m: b"First: " + m
  7852. )
  7853. # Try again without force - should fail
  7854. with self.assertRaises(porcelain.Error):
  7855. porcelain.filter_branch(
  7856. self.repo_path, "master", filter_message=lambda m: b"Second: " + m
  7857. )
  7858. # Try again with force - should succeed
  7859. porcelain.filter_branch(
  7860. self.repo_path,
  7861. "master",
  7862. filter_message=lambda m: b"Second: " + m,
  7863. force=True,
  7864. )
  7865. # Verify second filter was applied
  7866. new_head = self.repo.refs[b"refs/heads/master"]
  7867. new_commit = self.repo[new_head]
  7868. self.assertTrue(new_commit.message.startswith(b"Second: First: "))
  7869. class StashTests(PorcelainTestCase):
  7870. def setUp(self) -> None:
  7871. super().setUp()
  7872. # Create initial commit
  7873. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  7874. f.write(b"initial content")
  7875. porcelain.add(repo=self.repo.path, paths=["initial.txt"])
  7876. porcelain.commit(
  7877. repo=self.repo.path,
  7878. message=b"Initial commit",
  7879. author=b"Test Author <test@example.com>",
  7880. committer=b"Test Committer <test@example.com>",
  7881. )
  7882. def test_stash_push_and_pop(self) -> None:
  7883. # Create a new file and stage it
  7884. new_file = os.path.join(self.repo.path, "new.txt")
  7885. with open(new_file, "wb") as f:
  7886. f.write(b"new file content")
  7887. porcelain.add(repo=self.repo.path, paths=["new.txt"])
  7888. # Modify existing file
  7889. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  7890. f.write(b"modified content")
  7891. # Push to stash
  7892. porcelain.stash_push(self.repo.path)
  7893. # Verify files are reset
  7894. self.assertFalse(os.path.exists(new_file))
  7895. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  7896. self.assertEqual(b"initial content", f.read())
  7897. # Pop the stash
  7898. porcelain.stash_pop(self.repo.path)
  7899. # Verify files are restored
  7900. self.assertTrue(os.path.exists(new_file))
  7901. with open(new_file, "rb") as f:
  7902. self.assertEqual(b"new file content", f.read())
  7903. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  7904. self.assertEqual(b"modified content", f.read())
  7905. # Verify new file is in the index
  7906. from dulwich.index import Index
  7907. index = Index(os.path.join(self.repo.path, ".git", "index"))
  7908. self.assertIn(b"new.txt", index)
  7909. def test_stash_list(self) -> None:
  7910. # Initially no stashes
  7911. stashes = list(porcelain.stash_list(self.repo.path))
  7912. self.assertEqual(0, len(stashes))
  7913. # Create a file and stash it
  7914. test_file = os.path.join(self.repo.path, "test.txt")
  7915. with open(test_file, "wb") as f:
  7916. f.write(b"test content")
  7917. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  7918. # Push first stash
  7919. porcelain.stash_push(self.repo.path)
  7920. # Create another file and stash it
  7921. test_file2 = os.path.join(self.repo.path, "test2.txt")
  7922. with open(test_file2, "wb") as f:
  7923. f.write(b"test content 2")
  7924. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  7925. # Push second stash
  7926. porcelain.stash_push(self.repo.path)
  7927. # Check stash list
  7928. stashes = list(porcelain.stash_list(self.repo.path))
  7929. self.assertEqual(2, len(stashes))
  7930. # Stashes are returned in order (most recent first)
  7931. self.assertEqual(0, stashes[0][0])
  7932. self.assertEqual(1, stashes[1][0])
  7933. def test_stash_drop(self) -> None:
  7934. # Create and stash some changes
  7935. test_file = os.path.join(self.repo.path, "test.txt")
  7936. with open(test_file, "wb") as f:
  7937. f.write(b"test content")
  7938. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  7939. porcelain.stash_push(self.repo.path)
  7940. # Create another stash
  7941. test_file2 = os.path.join(self.repo.path, "test2.txt")
  7942. with open(test_file2, "wb") as f:
  7943. f.write(b"test content 2")
  7944. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  7945. porcelain.stash_push(self.repo.path)
  7946. # Verify we have 2 stashes
  7947. stashes = list(porcelain.stash_list(self.repo.path))
  7948. self.assertEqual(2, len(stashes))
  7949. # Drop the first stash (index 0)
  7950. porcelain.stash_drop(self.repo.path, 0)
  7951. # Verify we have 1 stash left
  7952. stashes = list(porcelain.stash_list(self.repo.path))
  7953. self.assertEqual(1, len(stashes))
  7954. # The remaining stash should be the one we created first
  7955. # Pop it and verify it's the first file
  7956. porcelain.stash_pop(self.repo.path)
  7957. self.assertTrue(os.path.exists(test_file))
  7958. self.assertFalse(os.path.exists(test_file2))
  7959. def test_stash_pop_empty(self) -> None:
  7960. # Attempting to pop from empty stash should raise an error
  7961. with self.assertRaises(IndexError):
  7962. porcelain.stash_pop(self.repo.path)
  7963. def test_stash_with_untracked_files(self) -> None:
  7964. # Create an untracked file
  7965. untracked_file = os.path.join(self.repo.path, "untracked.txt")
  7966. with open(untracked_file, "wb") as f:
  7967. f.write(b"untracked content")
  7968. # Create a tracked change
  7969. tracked_file = os.path.join(self.repo.path, "tracked.txt")
  7970. with open(tracked_file, "wb") as f:
  7971. f.write(b"tracked content")
  7972. porcelain.add(repo=self.repo.path, paths=["tracked.txt"])
  7973. # Stash (by default, untracked files are not included)
  7974. porcelain.stash_push(self.repo.path)
  7975. # Untracked file should still exist
  7976. self.assertTrue(os.path.exists(untracked_file))
  7977. # Tracked file should be gone
  7978. self.assertFalse(os.path.exists(tracked_file))
  7979. # Pop the stash
  7980. porcelain.stash_pop(self.repo.path)
  7981. # Tracked file should be restored
  7982. self.assertTrue(os.path.exists(tracked_file))
  7983. class BisectTests(PorcelainTestCase):
  7984. """Tests for bisect porcelain functions."""
  7985. def test_bisect_start(self):
  7986. """Test starting a bisect session."""
  7987. # Create some commits
  7988. _c1, _c2, c3 = build_commit_graph(
  7989. self.repo.object_store,
  7990. [[1], [2, 1], [3, 2]],
  7991. attrs={
  7992. 1: {"message": b"initial"},
  7993. 2: {"message": b"second"},
  7994. 3: {"message": b"third"},
  7995. },
  7996. )
  7997. self.repo.refs[b"refs/heads/master"] = c3.id
  7998. self.repo.refs[b"HEAD"] = c3.id
  7999. # Start bisect
  8000. porcelain.bisect_start(self.repo_path)
  8001. # Check that bisect state files exist
  8002. self.assertTrue(
  8003. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  8004. )
  8005. self.assertTrue(
  8006. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_TERMS"))
  8007. )
  8008. self.assertTrue(
  8009. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_NAMES"))
  8010. )
  8011. self.assertTrue(
  8012. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_LOG"))
  8013. )
  8014. def test_bisect_workflow(self):
  8015. """Test a complete bisect workflow."""
  8016. # Create some commits
  8017. c1, c2, c3, c4 = build_commit_graph(
  8018. self.repo.object_store,
  8019. [[1], [2, 1], [3, 2], [4, 3]],
  8020. attrs={
  8021. 1: {"message": b"good commit 1"},
  8022. 2: {"message": b"good commit 2"},
  8023. 3: {"message": b"bad commit"},
  8024. 4: {"message": b"bad commit 2"},
  8025. },
  8026. )
  8027. self.repo.refs[b"refs/heads/master"] = c4.id
  8028. self.repo.refs[b"HEAD"] = c4.id
  8029. # Start bisect with bad and good
  8030. next_sha = porcelain.bisect_start(self.repo_path, bad=c4.id, good=c1.id)
  8031. # Should return the middle commit
  8032. self.assertIsNotNone(next_sha)
  8033. self.assertIn(next_sha, [c2.id, c3.id])
  8034. # Mark the middle commit as good or bad
  8035. if next_sha == c2.id:
  8036. # c2 is good, next should be c3
  8037. next_sha = porcelain.bisect_good(self.repo_path)
  8038. self.assertEqual(next_sha, c3.id)
  8039. # Mark c3 as bad - bisect complete
  8040. next_sha = porcelain.bisect_bad(self.repo_path)
  8041. self.assertIsNone(next_sha)
  8042. else:
  8043. # c3 is bad, next should be c2
  8044. next_sha = porcelain.bisect_bad(self.repo_path)
  8045. self.assertEqual(next_sha, c2.id)
  8046. # Mark c2 as good - bisect complete
  8047. next_sha = porcelain.bisect_good(self.repo_path)
  8048. self.assertIsNone(next_sha)
  8049. def test_bisect_log(self):
  8050. """Test getting bisect log."""
  8051. # Create some commits
  8052. c1, _c2, c3 = build_commit_graph(
  8053. self.repo.object_store,
  8054. [[1], [2, 1], [3, 2]],
  8055. attrs={
  8056. 1: {"message": b"initial"},
  8057. 2: {"message": b"second"},
  8058. 3: {"message": b"third"},
  8059. },
  8060. )
  8061. self.repo.refs[b"refs/heads/master"] = c3.id
  8062. self.repo.refs[b"HEAD"] = c3.id
  8063. # Start bisect and mark commits
  8064. porcelain.bisect_start(self.repo_path)
  8065. porcelain.bisect_bad(self.repo_path, c3.id)
  8066. porcelain.bisect_good(self.repo_path, c1.id)
  8067. # Get log
  8068. log = porcelain.bisect_log(self.repo_path)
  8069. self.assertIn("git bisect start", log)
  8070. self.assertIn("git bisect bad", log)
  8071. self.assertIn("git bisect good", log)
  8072. def test_bisect_reset(self):
  8073. """Test resetting bisect state."""
  8074. # Create some commits
  8075. c1, _c2, c3 = build_commit_graph(
  8076. self.repo.object_store,
  8077. [[1], [2, 1], [3, 2]],
  8078. attrs={
  8079. 1: {"message": b"initial"},
  8080. 2: {"message": b"second"},
  8081. 3: {"message": b"third"},
  8082. },
  8083. )
  8084. self.repo.refs[b"refs/heads/master"] = c3.id
  8085. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  8086. # Start bisect
  8087. porcelain.bisect_start(self.repo_path)
  8088. porcelain.bisect_bad(self.repo_path)
  8089. porcelain.bisect_good(self.repo_path, c1.id)
  8090. # Reset
  8091. porcelain.bisect_reset(self.repo_path)
  8092. # Check that bisect state files are removed
  8093. self.assertFalse(
  8094. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  8095. )
  8096. self.assertFalse(
  8097. os.path.exists(os.path.join(self.repo.controldir(), "refs", "bisect"))
  8098. )
  8099. # HEAD should be back to being a symbolic ref to master
  8100. head_target, _ = self.repo.refs.follow(b"HEAD")
  8101. self.assertEqual(head_target[-1], b"refs/heads/master")
  8102. def test_bisect_skip(self):
  8103. """Test skipping commits during bisect."""
  8104. # Create some commits
  8105. c1, c2, _c3, _c4, c5 = build_commit_graph(
  8106. self.repo.object_store,
  8107. [[1], [2, 1], [3, 2], [4, 3], [5, 4]],
  8108. attrs={
  8109. 1: {"message": b"good"},
  8110. 2: {"message": b"skip this"},
  8111. 3: {"message": b"bad"},
  8112. 4: {"message": b"bad"},
  8113. 5: {"message": b"bad"},
  8114. },
  8115. )
  8116. self.repo.refs[b"refs/heads/master"] = c5.id
  8117. self.repo.refs[b"HEAD"] = c5.id
  8118. # Start bisect
  8119. porcelain.bisect_start(self.repo_path, bad=c5.id, good=c1.id)
  8120. # Skip c2 if it's selected
  8121. next_sha = porcelain.bisect_skip(self.repo_path, [c2.id])
  8122. self.assertIsNotNone(next_sha)
  8123. class ReflogTest(PorcelainTestCase):
  8124. def test_reflog_head(self):
  8125. """Test reading HEAD reflog."""
  8126. # Create a commit
  8127. blob = Blob.from_string(b"test content")
  8128. self.repo.object_store.add_object(blob)
  8129. tree = Tree()
  8130. tree.add(b"test", 0o100644, blob.id)
  8131. self.repo.object_store.add_object(tree)
  8132. commit = Commit()
  8133. commit.tree = tree.id
  8134. commit.author = b"Test Author <test@example.com>"
  8135. commit.committer = b"Test Author <test@example.com>"
  8136. commit.commit_time = 1234567890
  8137. commit.commit_timezone = 0
  8138. commit.author_time = 1234567890
  8139. commit.author_timezone = 0
  8140. commit.message = b"Initial commit"
  8141. self.repo.object_store.add_object(commit)
  8142. # Write a reflog entry
  8143. self.repo._write_reflog(
  8144. b"HEAD",
  8145. ZERO_SHA,
  8146. commit.id,
  8147. b"Test Author <test@example.com>",
  8148. 1234567890,
  8149. 0,
  8150. b"commit (initial): Initial commit",
  8151. )
  8152. # Read reflog using porcelain
  8153. entries = list(porcelain.reflog(self.repo_path))
  8154. self.assertEqual(1, len(entries))
  8155. self.assertEqual(ZERO_SHA, entries[0].old_sha)
  8156. self.assertEqual(commit.id, entries[0].new_sha)
  8157. self.assertEqual(b"Test Author <test@example.com>", entries[0].committer)
  8158. self.assertEqual(1234567890, entries[0].timestamp)
  8159. self.assertEqual(0, entries[0].timezone)
  8160. self.assertEqual(b"commit (initial): Initial commit", entries[0].message)
  8161. def test_reflog_with_string_ref(self):
  8162. """Test reading reflog with string reference."""
  8163. # Create a commit
  8164. blob = Blob.from_string(b"test content")
  8165. self.repo.object_store.add_object(blob)
  8166. tree = Tree()
  8167. tree.add(b"test", 0o100644, blob.id)
  8168. self.repo.object_store.add_object(tree)
  8169. commit = Commit()
  8170. commit.tree = tree.id
  8171. commit.author = b"Test Author <test@example.com>"
  8172. commit.committer = b"Test Author <test@example.com>"
  8173. commit.commit_time = 1234567890
  8174. commit.commit_timezone = 0
  8175. commit.author_time = 1234567890
  8176. commit.author_timezone = 0
  8177. commit.message = b"Initial commit"
  8178. self.repo.object_store.add_object(commit)
  8179. # Write a reflog entry
  8180. self.repo._write_reflog(
  8181. b"refs/heads/master",
  8182. ZERO_SHA,
  8183. commit.id,
  8184. b"Test Author <test@example.com>",
  8185. 1234567890,
  8186. 0,
  8187. b"commit (initial): Initial commit",
  8188. )
  8189. # Read reflog using porcelain with string ref
  8190. entries = list(porcelain.reflog(self.repo_path, "refs/heads/master"))
  8191. self.assertEqual(1, len(entries))
  8192. self.assertEqual(commit.id, entries[0].new_sha)
  8193. def test_reflog_all(self):
  8194. """Test reading all reflogs."""
  8195. # Create a commit
  8196. blob = Blob.from_string(b"test content")
  8197. self.repo.object_store.add_object(blob)
  8198. tree = Tree()
  8199. tree.add(b"test", 0o100644, blob.id)
  8200. self.repo.object_store.add_object(tree)
  8201. commit = Commit()
  8202. commit.tree = tree.id
  8203. commit.author = b"Test Author <test@example.com>"
  8204. commit.committer = b"Test Author <test@example.com>"
  8205. commit.commit_time = 1234567890
  8206. commit.commit_timezone = 0
  8207. commit.author_time = 1234567890
  8208. commit.author_timezone = 0
  8209. commit.message = b"Initial commit"
  8210. self.repo.object_store.add_object(commit)
  8211. # Write reflog entries for HEAD and master
  8212. self.repo._write_reflog(
  8213. b"HEAD",
  8214. ZERO_SHA,
  8215. commit.id,
  8216. b"Test Author <test@example.com>",
  8217. 1234567890,
  8218. 0,
  8219. b"commit (initial): Initial commit",
  8220. )
  8221. self.repo._write_reflog(
  8222. b"refs/heads/master",
  8223. ZERO_SHA,
  8224. commit.id,
  8225. b"Test Author <test@example.com>",
  8226. 1234567891,
  8227. 0,
  8228. b"branch: Created from HEAD",
  8229. )
  8230. # Read all reflogs using porcelain
  8231. entries = list(porcelain.reflog(self.repo_path, all=True))
  8232. # Should have at least 2 entries (HEAD and refs/heads/master)
  8233. self.assertGreaterEqual(len(entries), 2)
  8234. # Check that we got entries from different refs
  8235. refs_seen = set()
  8236. for ref, entry in entries:
  8237. refs_seen.add(ref)
  8238. self.assertEqual(commit.id, entry.new_sha)
  8239. # Should have seen at least HEAD and refs/heads/master
  8240. self.assertIn(b"HEAD", refs_seen)
  8241. self.assertIn(b"refs/heads/master", refs_seen)
  8242. def test_reflog_expire_by_time(self):
  8243. """Test expiring reflog entries by timestamp."""
  8244. # Create commits
  8245. blob = Blob.from_string(b"test content")
  8246. self.repo.object_store.add_object(blob)
  8247. tree = Tree()
  8248. tree.add(b"test", 0o100644, blob.id)
  8249. self.repo.object_store.add_object(tree)
  8250. commit1 = Commit()
  8251. commit1.tree = tree.id
  8252. commit1.author = b"Test Author <test@example.com>"
  8253. commit1.committer = b"Test Author <test@example.com>"
  8254. commit1.commit_time = 1000000000
  8255. commit1.commit_timezone = 0
  8256. commit1.author_time = 1000000000
  8257. commit1.author_timezone = 0
  8258. commit1.message = b"Old commit"
  8259. self.repo.object_store.add_object(commit1)
  8260. commit2 = Commit()
  8261. commit2.tree = tree.id
  8262. commit2.author = b"Test Author <test@example.com>"
  8263. commit2.committer = b"Test Author <test@example.com>"
  8264. commit2.commit_time = 2000000000
  8265. commit2.commit_timezone = 0
  8266. commit2.author_time = 2000000000
  8267. commit2.author_timezone = 0
  8268. commit2.message = b"Recent commit"
  8269. self.repo.object_store.add_object(commit2)
  8270. # Write reflog entries with different timestamps
  8271. self.repo._write_reflog(
  8272. b"HEAD",
  8273. ZERO_SHA,
  8274. commit1.id,
  8275. b"Test Author <test@example.com>",
  8276. 1000000000,
  8277. 0,
  8278. b"commit: Old commit",
  8279. )
  8280. self.repo._write_reflog(
  8281. b"HEAD",
  8282. commit1.id,
  8283. commit2.id,
  8284. b"Test Author <test@example.com>",
  8285. 2000000000,
  8286. 0,
  8287. b"commit: Recent commit",
  8288. )
  8289. # Expire entries older than timestamp 1500000000
  8290. result = porcelain.reflog_expire(
  8291. self.repo_path, ref=b"HEAD", expire_time=1500000000
  8292. )
  8293. self.assertEqual(1, result[b"HEAD"])
  8294. # Check that only the recent entry remains
  8295. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8296. self.assertEqual(1, len(entries))
  8297. self.assertEqual(commit2.id, entries[0].new_sha)
  8298. def test_reflog_expire_all(self):
  8299. """Test expiring reflog entries for all refs."""
  8300. # Create a commit
  8301. blob = Blob.from_string(b"test content")
  8302. self.repo.object_store.add_object(blob)
  8303. tree = Tree()
  8304. tree.add(b"test", 0o100644, blob.id)
  8305. self.repo.object_store.add_object(tree)
  8306. commit = Commit()
  8307. commit.tree = tree.id
  8308. commit.author = b"Test Author <test@example.com>"
  8309. commit.committer = b"Test Author <test@example.com>"
  8310. commit.commit_time = 1000000000
  8311. commit.commit_timezone = 0
  8312. commit.author_time = 1000000000
  8313. commit.author_timezone = 0
  8314. commit.message = b"Test commit"
  8315. self.repo.object_store.add_object(commit)
  8316. # Write old reflog entries for multiple refs
  8317. self.repo._write_reflog(
  8318. b"HEAD",
  8319. ZERO_SHA,
  8320. commit.id,
  8321. b"Test Author <test@example.com>",
  8322. 1000000000,
  8323. 0,
  8324. b"commit: Test commit",
  8325. )
  8326. self.repo._write_reflog(
  8327. b"refs/heads/master",
  8328. ZERO_SHA,
  8329. commit.id,
  8330. b"Test Author <test@example.com>",
  8331. 1000000000,
  8332. 0,
  8333. b"commit: Test commit",
  8334. )
  8335. # Expire all old entries
  8336. result = porcelain.reflog_expire(
  8337. self.repo_path, all=True, expire_time=2000000000
  8338. )
  8339. # Should have expired entries from both refs
  8340. self.assertIn(b"HEAD", result)
  8341. self.assertIn(b"refs/heads/master", result)
  8342. self.assertEqual(1, result[b"HEAD"])
  8343. self.assertEqual(1, result[b"refs/heads/master"])
  8344. def test_reflog_expire_dry_run(self):
  8345. """Test dry-run mode for reflog expire."""
  8346. # Create a commit
  8347. blob = Blob.from_string(b"test content")
  8348. self.repo.object_store.add_object(blob)
  8349. tree = Tree()
  8350. tree.add(b"test", 0o100644, blob.id)
  8351. self.repo.object_store.add_object(tree)
  8352. commit = Commit()
  8353. commit.tree = tree.id
  8354. commit.author = b"Test Author <test@example.com>"
  8355. commit.committer = b"Test Author <test@example.com>"
  8356. commit.commit_time = 1000000000
  8357. commit.commit_timezone = 0
  8358. commit.author_time = 1000000000
  8359. commit.author_timezone = 0
  8360. commit.message = b"Test commit"
  8361. self.repo.object_store.add_object(commit)
  8362. # Write old reflog entry
  8363. self.repo._write_reflog(
  8364. b"HEAD",
  8365. ZERO_SHA,
  8366. commit.id,
  8367. b"Test Author <test@example.com>",
  8368. 1000000000,
  8369. 0,
  8370. b"commit: Test commit",
  8371. )
  8372. # Dry run expire
  8373. result = porcelain.reflog_expire(
  8374. self.repo_path, ref=b"HEAD", expire_time=2000000000, dry_run=True
  8375. )
  8376. self.assertEqual(1, result[b"HEAD"])
  8377. # Entry should still exist
  8378. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8379. self.assertEqual(1, len(entries))
  8380. def test_reflog_delete(self):
  8381. """Test deleting specific reflog entry."""
  8382. # Create commits
  8383. blob = Blob.from_string(b"test content")
  8384. self.repo.object_store.add_object(blob)
  8385. tree = Tree()
  8386. tree.add(b"test", 0o100644, blob.id)
  8387. self.repo.object_store.add_object(tree)
  8388. commit1 = Commit()
  8389. commit1.tree = tree.id
  8390. commit1.author = b"Test Author <test@example.com>"
  8391. commit1.committer = b"Test Author <test@example.com>"
  8392. commit1.commit_time = 1000000000
  8393. commit1.commit_timezone = 0
  8394. commit1.author_time = 1000000000
  8395. commit1.author_timezone = 0
  8396. commit1.message = b"First commit"
  8397. self.repo.object_store.add_object(commit1)
  8398. commit2 = Commit()
  8399. commit2.tree = tree.id
  8400. commit2.author = b"Test Author <test@example.com>"
  8401. commit2.committer = b"Test Author <test@example.com>"
  8402. commit2.commit_time = 2000000000
  8403. commit2.commit_timezone = 0
  8404. commit2.author_time = 2000000000
  8405. commit2.author_timezone = 0
  8406. commit2.message = b"Second commit"
  8407. self.repo.object_store.add_object(commit2)
  8408. # Write two reflog entries
  8409. self.repo._write_reflog(
  8410. b"HEAD",
  8411. ZERO_SHA,
  8412. commit1.id,
  8413. b"Test Author <test@example.com>",
  8414. 1000000000,
  8415. 0,
  8416. b"commit: First commit",
  8417. )
  8418. self.repo._write_reflog(
  8419. b"HEAD",
  8420. commit1.id,
  8421. commit2.id,
  8422. b"Test Author <test@example.com>",
  8423. 2000000000,
  8424. 0,
  8425. b"commit: Second commit",
  8426. )
  8427. # Delete the most recent entry (index 0)
  8428. porcelain.reflog_delete(self.repo_path, ref=b"HEAD", index=0)
  8429. # Should only have one entry left
  8430. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8431. self.assertEqual(1, len(entries))
  8432. self.assertEqual(commit1.id, entries[0].new_sha)
  8433. def test_reflog_expire_unreachable(self):
  8434. """Test expiring unreachable reflog entries."""
  8435. # Create commits
  8436. blob = Blob.from_string(b"test content")
  8437. self.repo.object_store.add_object(blob)
  8438. tree = Tree()
  8439. tree.add(b"test", 0o100644, blob.id)
  8440. self.repo.object_store.add_object(tree)
  8441. # Create commit 1 - will be reachable (pointed to by HEAD)
  8442. commit1 = Commit()
  8443. commit1.tree = tree.id
  8444. commit1.author = b"Test Author <test@example.com>"
  8445. commit1.committer = b"Test Author <test@example.com>"
  8446. commit1.commit_time = 1000000000
  8447. commit1.commit_timezone = 0
  8448. commit1.author_time = 1000000000
  8449. commit1.author_timezone = 0
  8450. commit1.message = b"Reachable commit"
  8451. self.repo.object_store.add_object(commit1)
  8452. # Create commit 2 - will be unreachable
  8453. commit2 = Commit()
  8454. commit2.tree = tree.id
  8455. commit2.author = b"Test Author <test@example.com>"
  8456. commit2.committer = b"Test Author <test@example.com>"
  8457. commit2.commit_time = 1500000000
  8458. commit2.commit_timezone = 0
  8459. commit2.author_time = 1500000000
  8460. commit2.author_timezone = 0
  8461. commit2.message = b"Unreachable commit"
  8462. self.repo.object_store.add_object(commit2)
  8463. # Create commit 3 - will also be reachable (pointed to by master)
  8464. commit3 = Commit()
  8465. commit3.tree = tree.id
  8466. commit3.author = b"Test Author <test@example.com>"
  8467. commit3.committer = b"Test Author <test@example.com>"
  8468. commit3.commit_time = 2000000000
  8469. commit3.commit_timezone = 0
  8470. commit3.author_time = 2000000000
  8471. commit3.author_timezone = 0
  8472. commit3.message = b"Another reachable commit"
  8473. self.repo.object_store.add_object(commit3)
  8474. # Set up refs to make commit1 and commit3 reachable
  8475. # HEAD is a symbolic ref to refs/heads/master by default, so we set master first
  8476. self.repo.refs[b"refs/heads/master"] = commit1.id
  8477. # Create another branch pointing to commit3
  8478. self.repo.refs[b"refs/heads/feature"] = commit3.id
  8479. # Write reflog entries for all three commits
  8480. self.repo._write_reflog(
  8481. b"HEAD",
  8482. ZERO_SHA,
  8483. commit1.id,
  8484. b"Test Author <test@example.com>",
  8485. 1000000000,
  8486. 0,
  8487. b"commit: Reachable commit",
  8488. )
  8489. self.repo._write_reflog(
  8490. b"HEAD",
  8491. commit1.id,
  8492. commit2.id,
  8493. b"Test Author <test@example.com>",
  8494. 1500000000,
  8495. 0,
  8496. b"commit: Unreachable commit",
  8497. )
  8498. self.repo._write_reflog(
  8499. b"HEAD",
  8500. commit2.id,
  8501. commit3.id,
  8502. b"Test Author <test@example.com>",
  8503. 2000000000,
  8504. 0,
  8505. b"commit: Another reachable commit",
  8506. )
  8507. # Expire unreachable entries older than a time that includes commit2
  8508. # but not the reachable commits
  8509. result = porcelain.reflog_expire(
  8510. self.repo_path,
  8511. ref=b"HEAD",
  8512. expire_unreachable_time=1600000000, # After commit2, before commit3
  8513. )
  8514. # Should have expired only commit2
  8515. self.assertEqual(1, result[b"HEAD"])
  8516. # Verify the remaining entries
  8517. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8518. self.assertEqual(2, len(entries))
  8519. # commit1 and commit3 should remain (both reachable)
  8520. self.assertEqual(commit1.id, entries[0].new_sha)
  8521. self.assertEqual(commit3.id, entries[1].new_sha)
  8522. class WriteCommitGraphTests(PorcelainTestCase):
  8523. """Tests for the write_commit_graph porcelain function."""
  8524. def test_write_commit_graph_empty_repo(self):
  8525. """Test writing commit graph on empty repository."""
  8526. # Should not fail on empty repo
  8527. porcelain.write_commit_graph(self.repo_path)
  8528. # No commit graph should be created for empty repo
  8529. graph_path = os.path.join(
  8530. self.repo_path, ".git", "objects", "info", "commit-graph"
  8531. )
  8532. self.assertFalse(os.path.exists(graph_path))
  8533. def test_write_commit_graph_with_commits(self):
  8534. """Test writing commit graph with commits."""
  8535. # Create some commits
  8536. c1, c2, c3 = build_commit_graph(
  8537. self.repo.object_store,
  8538. [[1], [2, 1], [3, 1, 2]],
  8539. attrs={
  8540. 1: {"message": b"First commit"},
  8541. 2: {"message": b"Second commit"},
  8542. 3: {"message": b"Merge commit"},
  8543. },
  8544. )
  8545. self.repo.refs[b"refs/heads/master"] = c3.id
  8546. self.repo.refs[b"refs/heads/branch"] = c2.id
  8547. # Write commit graph
  8548. porcelain.write_commit_graph(self.repo_path)
  8549. # Verify commit graph was created
  8550. graph_path = os.path.join(
  8551. self.repo_path, ".git", "objects", "info", "commit-graph"
  8552. )
  8553. self.assertTrue(os.path.exists(graph_path))
  8554. # Load and verify the commit graph
  8555. from dulwich.commit_graph import read_commit_graph
  8556. commit_graph = read_commit_graph(graph_path)
  8557. self.assertIsNotNone(commit_graph)
  8558. self.assertEqual(3, len(commit_graph))
  8559. # Verify all commits are in the graph
  8560. for commit_obj in [c1, c2, c3]:
  8561. entry = commit_graph.get_entry_by_oid(commit_obj.id)
  8562. self.assertIsNotNone(entry)
  8563. def test_write_commit_graph_config_disabled(self):
  8564. """Test that commit graph is not written when disabled by config."""
  8565. # Create a commit
  8566. (c1,) = build_commit_graph(
  8567. self.repo.object_store, [[1]], attrs={1: {"message": b"First commit"}}
  8568. )
  8569. self.repo.refs[b"refs/heads/master"] = c1.id
  8570. # Disable commit graph in config
  8571. config = self.repo.get_config()
  8572. config.set((b"core",), b"commitGraph", b"false")
  8573. config.write_to_path()
  8574. # Write commit graph (should respect config)
  8575. porcelain.write_commit_graph(self.repo_path)
  8576. # Verify commit graph still gets written
  8577. # (porcelain.write_commit_graph explicitly writes regardless of config)
  8578. graph_path = os.path.join(
  8579. self.repo_path, ".git", "objects", "info", "commit-graph"
  8580. )
  8581. self.assertTrue(os.path.exists(graph_path))
  8582. def test_write_commit_graph_reachable_false(self):
  8583. """Test writing commit graph with reachable=False."""
  8584. # Create commits
  8585. _c1, _c2, c3 = build_commit_graph(
  8586. self.repo.object_store,
  8587. [[1], [2, 1], [3, 2]],
  8588. attrs={
  8589. 1: {"message": b"First commit"},
  8590. 2: {"message": b"Second commit"},
  8591. 3: {"message": b"Third commit"},
  8592. },
  8593. )
  8594. # Only reference the third commit
  8595. self.repo.refs[b"refs/heads/master"] = c3.id
  8596. # Write commit graph with reachable=False
  8597. porcelain.write_commit_graph(self.repo_path, reachable=False)
  8598. # Verify commit graph was created
  8599. graph_path = os.path.join(
  8600. self.repo_path, ".git", "objects", "info", "commit-graph"
  8601. )
  8602. self.assertTrue(os.path.exists(graph_path))
  8603. # Load and verify the commit graph
  8604. from dulwich.commit_graph import read_commit_graph
  8605. commit_graph = read_commit_graph(graph_path)
  8606. self.assertIsNotNone(commit_graph)
  8607. # With reachable=False, only directly referenced commits should be included
  8608. # In this case, only c3 (from refs/heads/master)
  8609. self.assertEqual(1, len(commit_graph))
  8610. entry = commit_graph.get_entry_by_oid(c3.id)
  8611. self.assertIsNotNone(entry)
  8612. class WorktreePorcelainTests(PorcelainTestCase):
  8613. """Tests for porcelain worktree functions."""
  8614. def test_worktree_list_single(self):
  8615. """Test listing worktrees when only main worktree exists."""
  8616. # Create initial commit
  8617. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8618. f.write("test content")
  8619. porcelain.add(self.repo_path, ["test.txt"])
  8620. porcelain.commit(self.repo_path, message=b"Initial commit")
  8621. # List worktrees
  8622. worktrees = porcelain.worktree_list(self.repo_path)
  8623. self.assertEqual(len(worktrees), 1)
  8624. self.assertEqual(worktrees[0].path, self.repo_path)
  8625. self.assertFalse(worktrees[0].bare)
  8626. self.assertIsNotNone(worktrees[0].head)
  8627. self.assertIsNotNone(worktrees[0].branch)
  8628. def test_worktree_add_branch(self):
  8629. """Test adding a worktree with a new branch."""
  8630. # Create initial commit
  8631. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8632. f.write("test content")
  8633. porcelain.add(self.repo_path, ["test.txt"])
  8634. porcelain.commit(self.repo_path, message=b"Initial commit")
  8635. # Add worktree
  8636. wt_path = os.path.join(self.test_dir, "worktree1")
  8637. result_path = porcelain.worktree_add(self.repo_path, wt_path, branch=b"feature")
  8638. self.assertEqual(result_path, wt_path)
  8639. self.assertTrue(os.path.exists(wt_path))
  8640. self.assertTrue(os.path.exists(os.path.join(wt_path, ".git")))
  8641. # Check it appears in the list
  8642. worktrees = porcelain.worktree_list(self.repo_path)
  8643. self.assertEqual(len(worktrees), 2)
  8644. # Find the new worktree
  8645. new_wt = None
  8646. for wt in worktrees:
  8647. if wt.path == wt_path:
  8648. new_wt = wt
  8649. break
  8650. self.assertIsNotNone(new_wt)
  8651. self.assertEqual(new_wt.branch, b"refs/heads/feature")
  8652. self.assertFalse(new_wt.detached)
  8653. def test_worktree_add_detached(self):
  8654. """Test adding a detached worktree."""
  8655. # Create initial commit
  8656. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8657. f.write("test content")
  8658. porcelain.add(self.repo_path, ["test.txt"])
  8659. sha = porcelain.commit(self.repo_path, message=b"Initial commit")
  8660. # Add detached worktree
  8661. wt_path = os.path.join(self.test_dir, "detached")
  8662. porcelain.worktree_add(self.repo_path, wt_path, commit=sha, detach=True)
  8663. # Check it's detached
  8664. worktrees = porcelain.worktree_list(self.repo_path)
  8665. for wt in worktrees:
  8666. if wt.path == wt_path:
  8667. self.assertTrue(wt.detached)
  8668. self.assertIsNone(wt.branch)
  8669. self.assertEqual(wt.head, sha)
  8670. def test_worktree_remove(self):
  8671. """Test removing a worktree."""
  8672. # Create initial commit
  8673. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8674. f.write("test content")
  8675. porcelain.add(self.repo_path, ["test.txt"])
  8676. porcelain.commit(self.repo_path, message=b"Initial commit")
  8677. # Add and remove worktree
  8678. wt_path = os.path.join(self.test_dir, "to-remove")
  8679. porcelain.worktree_add(self.repo_path, wt_path)
  8680. # Verify it exists
  8681. self.assertTrue(os.path.exists(wt_path))
  8682. self.assertEqual(len(porcelain.worktree_list(self.repo_path)), 2)
  8683. # Remove it
  8684. porcelain.worktree_remove(self.repo_path, wt_path)
  8685. # Verify it's gone
  8686. self.assertFalse(os.path.exists(wt_path))
  8687. self.assertEqual(len(porcelain.worktree_list(self.repo_path)), 1)
  8688. def test_worktree_prune(self):
  8689. """Test pruning worktrees."""
  8690. # Create initial commit
  8691. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8692. f.write("test content")
  8693. porcelain.add(self.repo_path, ["test.txt"])
  8694. porcelain.commit(self.repo_path, message=b"Initial commit")
  8695. # Add worktree
  8696. wt_path = os.path.join(self.test_dir, "to-prune")
  8697. porcelain.worktree_add(self.repo_path, wt_path)
  8698. # Manually remove directory
  8699. shutil.rmtree(wt_path)
  8700. # Prune should remove the administrative files
  8701. pruned = porcelain.worktree_prune(self.repo_path)
  8702. self.assertEqual(len(pruned), 1)
  8703. # Verify it's gone from the list
  8704. worktrees = porcelain.worktree_list(self.repo_path)
  8705. self.assertEqual(len(worktrees), 1)
  8706. def test_worktree_lock_unlock(self):
  8707. """Test locking and unlocking worktrees."""
  8708. # Create initial commit
  8709. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8710. f.write("test content")
  8711. porcelain.add(self.repo_path, ["test.txt"])
  8712. porcelain.commit(self.repo_path, message=b"Initial commit")
  8713. # Add worktree
  8714. wt_path = os.path.join(self.test_dir, "lockable")
  8715. porcelain.worktree_add(self.repo_path, wt_path)
  8716. # Lock it
  8717. porcelain.worktree_lock(self.repo_path, wt_path, reason="Testing")
  8718. # Verify it's locked
  8719. worktrees = porcelain.worktree_list(self.repo_path)
  8720. for wt in worktrees:
  8721. if wt.path == wt_path:
  8722. self.assertTrue(wt.locked)
  8723. # Unlock it
  8724. porcelain.worktree_unlock(self.repo_path, wt_path)
  8725. # Verify it's unlocked
  8726. worktrees = porcelain.worktree_list(self.repo_path)
  8727. for wt in worktrees:
  8728. if wt.path == wt_path:
  8729. self.assertFalse(wt.locked)
  8730. def test_worktree_move(self):
  8731. """Test moving a worktree."""
  8732. # Create initial commit
  8733. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8734. f.write("test content")
  8735. porcelain.add(self.repo_path, ["test.txt"])
  8736. porcelain.commit(self.repo_path, message=b"Initial commit")
  8737. # Add worktree
  8738. old_path = os.path.join(self.test_dir, "old-location")
  8739. porcelain.worktree_add(self.repo_path, old_path)
  8740. # Create a file in the worktree
  8741. test_file = os.path.join(old_path, "workspace.txt")
  8742. with open(test_file, "w") as f:
  8743. f.write("workspace content")
  8744. # Move it
  8745. new_path = os.path.join(self.test_dir, "new-location")
  8746. porcelain.worktree_move(self.repo_path, old_path, new_path)
  8747. # Verify old path doesn't exist, new path does
  8748. self.assertFalse(os.path.exists(old_path))
  8749. self.assertTrue(os.path.exists(new_path))
  8750. self.assertTrue(os.path.exists(os.path.join(new_path, "workspace.txt")))
  8751. # Verify it's in the list at new location
  8752. worktrees = porcelain.worktree_list(self.repo_path)
  8753. paths = [wt.path for wt in worktrees]
  8754. self.assertIn(new_path, paths)
  8755. self.assertNotIn(old_path, paths)
  8756. class VarTests(PorcelainTestCase):
  8757. """Tests for the var command."""
  8758. def test_var_author_ident(self):
  8759. """Test getting GIT_AUTHOR_IDENT."""
  8760. # Set up user config
  8761. config = self.repo.get_config()
  8762. config.set((b"user",), b"name", b"Test Author")
  8763. config.set((b"user",), b"email", b"author@example.com")
  8764. config.write_to_path()
  8765. result = porcelain.var(self.repo_path, variable="GIT_AUTHOR_IDENT")
  8766. self.assertIn("Test Author <author@example.com>", result)
  8767. # Check that timestamp and timezone are included
  8768. # Format: Name <email> timestamp timezone
  8769. # "Test Author" is 2 words, so we have: Test, Author, <email>, timestamp, timezone
  8770. parts = result.split()
  8771. self.assertGreaterEqual(
  8772. len(parts), 4
  8773. ) # At least name, <email>, timestamp, timezone
  8774. # Check last two parts are timestamp and timezone
  8775. self.assertTrue(parts[-2].isdigit()) # timestamp
  8776. self.assertRegex(parts[-1], r"[+-]\d{4}") # timezone
  8777. def test_var_committer_ident(self):
  8778. """Test getting GIT_COMMITTER_IDENT."""
  8779. # Set up user config
  8780. config = self.repo.get_config()
  8781. config.set((b"user",), b"name", b"Test Committer")
  8782. config.set((b"user",), b"email", b"committer@example.com")
  8783. config.write_to_path()
  8784. result = porcelain.var(self.repo_path, variable="GIT_COMMITTER_IDENT")
  8785. self.assertIn("Test Committer <committer@example.com>", result)
  8786. # Check that timestamp and timezone are included
  8787. parts = result.split()
  8788. self.assertGreaterEqual(
  8789. len(parts), 4
  8790. ) # At least name, <email>, timestamp, timezone
  8791. # Check last two parts are timestamp and timezone
  8792. self.assertTrue(parts[-2].isdigit()) # timestamp
  8793. self.assertRegex(parts[-1], r"[+-]\d{4}") # timezone
  8794. def test_var_editor(self):
  8795. """Test getting GIT_EDITOR."""
  8796. # Test with environment variable
  8797. self.overrideEnv("GIT_EDITOR", "vim")
  8798. result = porcelain.var(self.repo_path, variable="GIT_EDITOR")
  8799. self.assertEqual(result, "vim")
  8800. def test_var_editor_from_config(self):
  8801. """Test getting GIT_EDITOR from config."""
  8802. # Set up editor in config
  8803. config = self.repo.get_config()
  8804. config.set((b"core",), b"editor", b"emacs")
  8805. config.write_to_path()
  8806. # Make sure env var is not set
  8807. self.overrideEnv("GIT_EDITOR", None)
  8808. result = porcelain.var(self.repo_path, variable="GIT_EDITOR")
  8809. self.assertEqual(result, "emacs")
  8810. def test_var_pager(self):
  8811. """Test getting GIT_PAGER."""
  8812. # Test with environment variable
  8813. self.overrideEnv("GIT_PAGER", "less")
  8814. result = porcelain.var(self.repo_path, variable="GIT_PAGER")
  8815. self.assertEqual(result, "less")
  8816. def test_var_pager_from_config(self):
  8817. """Test getting GIT_PAGER from config."""
  8818. # Set up pager in config
  8819. config = self.repo.get_config()
  8820. config.set((b"core",), b"pager", b"more")
  8821. config.write_to_path()
  8822. # Make sure env var is not set
  8823. self.overrideEnv("GIT_PAGER", None)
  8824. result = porcelain.var(self.repo_path, variable="GIT_PAGER")
  8825. self.assertEqual(result, "more")
  8826. def test_var_default_branch(self):
  8827. """Test getting GIT_DEFAULT_BRANCH."""
  8828. # Set up default branch in config
  8829. config = self.repo.get_config()
  8830. config.set((b"init",), b"defaultBranch", b"main")
  8831. config.write_to_path()
  8832. result = porcelain.var(self.repo_path, variable="GIT_DEFAULT_BRANCH")
  8833. self.assertEqual(result, "main")
  8834. def test_var_default_branch_default(self):
  8835. """Test getting GIT_DEFAULT_BRANCH with default value."""
  8836. result = porcelain.var(self.repo_path, variable="GIT_DEFAULT_BRANCH")
  8837. self.assertEqual(result, "master")
  8838. def test_var_list_all(self):
  8839. """Test listing all logical variables."""
  8840. # Set up some config
  8841. config = self.repo.get_config()
  8842. config.set((b"user",), b"name", b"Test User")
  8843. config.set((b"user",), b"email", b"test@example.com")
  8844. config.write_to_path()
  8845. result = porcelain.var_list(self.repo_path)
  8846. self.assertIsInstance(result, dict)
  8847. # Check that logical variables are present
  8848. self.assertIn("GIT_AUTHOR_IDENT", result)
  8849. self.assertIn("GIT_COMMITTER_IDENT", result)
  8850. self.assertIn("GIT_DEFAULT_BRANCH", result)
  8851. # Config variables should NOT be included (deprecated feature)
  8852. self.assertNotIn("user.name", result)
  8853. self.assertNotIn("user.email", result)
  8854. # Verify only logical variables are present
  8855. for key in result.keys():
  8856. self.assertTrue(key.startswith("GIT_"))
  8857. def test_var_unknown_variable(self):
  8858. """Test requesting an unknown variable."""
  8859. with self.assertRaises(KeyError):
  8860. porcelain.var(self.repo_path, variable="UNKNOWN_VARIABLE")
  8861. class MergeBaseTests(PorcelainTestCase):
  8862. """Tests for merge-base, is_ancestor, and independent_commits."""
  8863. def test_merge_base_linear_history(self):
  8864. """Test merge-base with linear history."""
  8865. # Create linear history: c1 <- c2 <- c3
  8866. _c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8867. self.repo.refs[b"refs/heads/branch1"] = c2.id
  8868. self.repo.refs[b"refs/heads/branch2"] = c3.id
  8869. result = porcelain.merge_base(
  8870. self.repo.path, committishes=["refs/heads/branch1", "refs/heads/branch2"]
  8871. )
  8872. self.assertEqual([c2.id], result)
  8873. def test_merge_base_diverged(self):
  8874. """Test merge-base with diverged branches."""
  8875. # Create diverged history: c1 <- c2a, c1 <- c2b
  8876. c1, c2a, c2b = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1]])
  8877. self.repo.refs[b"refs/heads/branch-a"] = c2a.id
  8878. self.repo.refs[b"refs/heads/branch-b"] = c2b.id
  8879. result = porcelain.merge_base(
  8880. self.repo.path, committishes=["refs/heads/branch-a", "refs/heads/branch-b"]
  8881. )
  8882. self.assertEqual([c1.id], result)
  8883. def test_merge_base_all(self):
  8884. """Test merge-base with --all flag."""
  8885. # Create history with multiple common ancestors
  8886. commits = build_commit_graph(
  8887. self.repo.object_store,
  8888. [[1], [2, 1], [3, 1], [4, 2, 3], [5, 2, 3]],
  8889. )
  8890. _c1, c2, c3, c4, c5 = commits
  8891. self.repo.refs[b"refs/heads/branch1"] = c4.id
  8892. self.repo.refs[b"refs/heads/branch2"] = c5.id
  8893. # Without --all, should return only first result
  8894. result = porcelain.merge_base(
  8895. self.repo.path,
  8896. committishes=["refs/heads/branch1", "refs/heads/branch2"],
  8897. all=False,
  8898. )
  8899. self.assertEqual(1, len(result))
  8900. # With --all, should return all merge bases
  8901. result_all = porcelain.merge_base(
  8902. self.repo.path,
  8903. committishes=["refs/heads/branch1", "refs/heads/branch2"],
  8904. all=True,
  8905. )
  8906. self.assertEqual(2, len(result_all))
  8907. self.assertIn(c2.id, result_all)
  8908. self.assertIn(c3.id, result_all)
  8909. def test_merge_base_octopus(self):
  8910. """Test merge-base with --octopus flag."""
  8911. # Create three-way diverged history
  8912. commits = build_commit_graph(
  8913. self.repo.object_store, [[1], [2, 1], [3, 1], [4, 1]]
  8914. )
  8915. c1, c2, c3, c4 = commits
  8916. self.repo.refs[b"refs/heads/a"] = c2.id
  8917. self.repo.refs[b"refs/heads/b"] = c3.id
  8918. self.repo.refs[b"refs/heads/c"] = c4.id
  8919. result = porcelain.merge_base(
  8920. self.repo.path,
  8921. committishes=["refs/heads/a", "refs/heads/b", "refs/heads/c"],
  8922. octopus=True,
  8923. )
  8924. self.assertEqual([c1.id], result)
  8925. def test_merge_base_requires_two_commits(self):
  8926. """Test merge-base requires at least two commits."""
  8927. with self.assertRaises(ValueError):
  8928. porcelain.merge_base(self.repo.path, committishes=["HEAD"])
  8929. def test_is_ancestor_true(self):
  8930. """Test is_ancestor returns True when commit is an ancestor."""
  8931. # Create linear history: c1 <- c2 <- c3
  8932. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8933. self.repo.refs[b"refs/heads/main"] = c3.id
  8934. # c1 is ancestor of c3
  8935. result = porcelain.is_ancestor(
  8936. self.repo.path, ancestor=c1.id.decode(), descendant=c3.id.decode()
  8937. )
  8938. self.assertTrue(result)
  8939. # c2 is ancestor of c3
  8940. result = porcelain.is_ancestor(
  8941. self.repo.path, ancestor=c2.id.decode(), descendant=c3.id.decode()
  8942. )
  8943. self.assertTrue(result)
  8944. def test_is_ancestor_false(self):
  8945. """Test is_ancestor returns False when commit is not an ancestor."""
  8946. # Create diverged history: c1 <- c2a, c1 <- c2b
  8947. _c1, c2a, c2b = build_commit_graph(
  8948. self.repo.object_store, [[1], [2, 1], [3, 1]]
  8949. )
  8950. # c2a is not ancestor of c2b
  8951. result = porcelain.is_ancestor(
  8952. self.repo.path, ancestor=c2a.id.decode(), descendant=c2b.id.decode()
  8953. )
  8954. self.assertFalse(result)
  8955. # c2b is not ancestor of c2a
  8956. result = porcelain.is_ancestor(
  8957. self.repo.path, ancestor=c2b.id.decode(), descendant=c2a.id.decode()
  8958. )
  8959. self.assertFalse(result)
  8960. def test_is_ancestor_requires_both(self):
  8961. """Test is_ancestor requires both ancestor and descendant."""
  8962. with self.assertRaises(ValueError):
  8963. porcelain.is_ancestor(self.repo.path, ancestor="HEAD", descendant=None)
  8964. with self.assertRaises(ValueError):
  8965. porcelain.is_ancestor(self.repo.path, ancestor=None, descendant="HEAD")
  8966. def test_independent_commits_linear(self):
  8967. """Test independent_commits with linear history."""
  8968. # Create linear history: c1 <- c2 <- c3
  8969. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8970. # Only c3 is independent (c1 and c2 are ancestors)
  8971. result = porcelain.independent_commits(
  8972. self.repo.path,
  8973. committishes=[c1.id.decode(), c2.id.decode(), c3.id.decode()],
  8974. )
  8975. self.assertEqual([c3.id], result)
  8976. def test_independent_commits_diverged(self):
  8977. """Test independent_commits with diverged branches."""
  8978. # Create diverged history: c1 <- c2a, c1 <- c2b
  8979. _c1, c2a, c2b = build_commit_graph(
  8980. self.repo.object_store, [[1], [2, 1], [3, 1]]
  8981. )
  8982. # c2a and c2b are both independent (neither is ancestor of the other)
  8983. result = porcelain.independent_commits(
  8984. self.repo.path, committishes=[c2a.id.decode(), c2b.id.decode()]
  8985. )
  8986. self.assertEqual(2, len(result))
  8987. self.assertIn(c2a.id, result)
  8988. self.assertIn(c2b.id, result)
  8989. def test_independent_commits_mixed(self):
  8990. """Test independent_commits with mixed history."""
  8991. # Create mixed history
  8992. commits = build_commit_graph(
  8993. self.repo.object_store, [[1], [2, 1], [3, 1], [4, 2]]
  8994. )
  8995. _c1, c2, c3, c4 = commits
  8996. # c4 and c3 are independent; c2 is ancestor of c4
  8997. result = porcelain.independent_commits(
  8998. self.repo.path,
  8999. committishes=[c2.id.decode(), c3.id.decode(), c4.id.decode()],
  9000. )
  9001. self.assertEqual(2, len(result))
  9002. self.assertIn(c3.id, result)
  9003. self.assertIn(c4.id, result)
  9004. self.assertNotIn(c2.id, result)
  9005. def test_independent_commits_empty(self):
  9006. """Test independent_commits with empty list."""
  9007. result = porcelain.independent_commits(self.repo.path, committishes=[])
  9008. self.assertEqual([], result)
  9009. class CherryTests(PorcelainTestCase):
  9010. """Tests for cherry command."""
  9011. def test_cherry_no_changes(self):
  9012. """Test cherry when head and upstream are the same."""
  9013. # Create a simple commit
  9014. commit_sha = self.repo.get_worktree().commit(
  9015. b"Initial commit", committer=b"Test <test@example.com>"
  9016. )
  9017. # Cherry should return empty when comparing a commit to itself
  9018. results = porcelain.cherry(
  9019. self.repo.path, upstream=commit_sha.decode(), head=commit_sha.decode()
  9020. )
  9021. self.assertEqual([], results)
  9022. def test_cherry_unique_commits(self):
  9023. """Test cherry with commits unique to head."""
  9024. # Create initial commit
  9025. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  9026. f.write("base content\n")
  9027. self.repo.get_worktree().stage(["file1.txt"])
  9028. base_commit = self.repo.get_worktree().commit(
  9029. b"Base commit", committer=b"Test <test@example.com>"
  9030. )
  9031. # Create a new commit on head
  9032. with open(os.path.join(self.repo_path, "file2.txt"), "w") as f:
  9033. f.write("new content\n")
  9034. self.repo.get_worktree().stage(["file2.txt"])
  9035. head_commit = self.repo.get_worktree().commit(
  9036. b"New commit", committer=b"Test <test@example.com>"
  9037. )
  9038. # Cherry should show the new commit as unique
  9039. results = porcelain.cherry(
  9040. self.repo.path, upstream=base_commit.decode(), head=head_commit.decode()
  9041. )
  9042. self.assertEqual(1, len(results))
  9043. status, commit_sha, message = results[0]
  9044. self.assertEqual("+", status)
  9045. self.assertEqual(head_commit, commit_sha)
  9046. self.assertIsNone(message)
  9047. def test_cherry_verbose(self):
  9048. """Test cherry with verbose flag."""
  9049. # Create initial commit
  9050. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  9051. f.write("base content\n")
  9052. self.repo.get_worktree().stage(["file1.txt"])
  9053. base_commit = self.repo.get_worktree().commit(
  9054. b"Base commit", committer=b"Test <test@example.com>"
  9055. )
  9056. # Create a new commit on head
  9057. with open(os.path.join(self.repo_path, "file2.txt"), "w") as f:
  9058. f.write("new content\n")
  9059. self.repo.get_worktree().stage(["file2.txt"])
  9060. head_commit = self.repo.get_worktree().commit(
  9061. b"New commit on head", committer=b"Test <test@example.com>"
  9062. )
  9063. # Cherry with verbose should include commit message
  9064. results = porcelain.cherry(
  9065. self.repo.path,
  9066. upstream=base_commit.decode(),
  9067. head=head_commit.decode(),
  9068. verbose=True,
  9069. )
  9070. self.assertEqual(1, len(results))
  9071. status, commit_sha, message = results[0]
  9072. self.assertEqual("+", status)
  9073. self.assertEqual(head_commit, commit_sha)
  9074. self.assertEqual(b"New commit on head", message)
  9075. def test_cherry_equivalent_patches(self):
  9076. """Test cherry with equivalent patches (cherry-picked commits)."""
  9077. # Create base commit
  9078. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  9079. f.write("line1\n")
  9080. self.repo.get_worktree().stage(["file.txt"])
  9081. base_commit = self.repo.get_worktree().commit(
  9082. b"Base commit", committer=b"Test <test@example.com>"
  9083. )
  9084. # Create upstream branch with a change
  9085. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  9086. f.write("line1\nline2\n")
  9087. self.repo.get_worktree().stage(["file.txt"])
  9088. upstream_commit = self.repo.get_worktree().commit(
  9089. b"Add line2", committer=b"Test <test@example.com>"
  9090. )
  9091. # Reset to base and create same change on head branch
  9092. self.repo.refs[b"HEAD"] = base_commit
  9093. self.repo.get_worktree().reset_index()
  9094. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  9095. f.write("line1\nline2\n")
  9096. self.repo.get_worktree().stage(["file.txt"])
  9097. head_commit = self.repo.get_worktree().commit(
  9098. b"Add line2 (different metadata)",
  9099. committer=b"Different <different@example.com>",
  9100. )
  9101. # Cherry should mark this as equivalent (-)
  9102. results = porcelain.cherry(
  9103. self.repo.path,
  9104. upstream=upstream_commit.decode(),
  9105. head=head_commit.decode(),
  9106. )
  9107. self.assertEqual(1, len(results))
  9108. status, commit_sha, _message = results[0]
  9109. self.assertEqual("-", status)
  9110. self.assertEqual(head_commit, commit_sha)
  9111. class GrepTests(PorcelainTestCase):
  9112. def test_basic_grep(self) -> None:
  9113. """Test basic pattern matching in files."""
  9114. # Create some test files
  9115. with open(os.path.join(self.repo_path, "foo.txt"), "w") as f:
  9116. f.write("hello world\ngoodbye world\n")
  9117. with open(os.path.join(self.repo_path, "bar.txt"), "w") as f:
  9118. f.write("foo bar\nbaz qux\n")
  9119. porcelain.add(self.repo, paths=["foo.txt", "bar.txt"])
  9120. porcelain.commit(self.repo, message=b"Add test files")
  9121. # Search for "world"
  9122. outstream = StringIO()
  9123. porcelain.grep(self.repo, "world", outstream=outstream)
  9124. output = outstream.getvalue().replace("\r\n", "\n")
  9125. self.assertEqual("foo.txt:hello world\nfoo.txt:goodbye world\n", output)
  9126. def test_grep_with_line_numbers(self) -> None:
  9127. """Test grep with line numbers."""
  9128. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  9129. f.write("line one\nline two\nline three\n")
  9130. porcelain.add(self.repo, paths=["test.txt"])
  9131. porcelain.commit(self.repo, message=b"Add test file")
  9132. outstream = StringIO()
  9133. porcelain.grep(self.repo, "line", outstream=outstream, line_number=True)
  9134. output = outstream.getvalue().replace("\r\n", "\n")
  9135. self.assertEqual(
  9136. "test.txt:1:line one\ntest.txt:2:line two\ntest.txt:3:line three\n",
  9137. output,
  9138. )
  9139. def test_grep_case_insensitive(self) -> None:
  9140. """Test case-insensitive grep."""
  9141. with open(os.path.join(self.repo_path, "case.txt"), "w") as f:
  9142. f.write("Hello WORLD\nGoodbye world\n")
  9143. porcelain.add(self.repo, paths=["case.txt"])
  9144. porcelain.commit(self.repo, message=b"Add case file")
  9145. outstream = StringIO()
  9146. porcelain.grep(self.repo, "HELLO", outstream=outstream, ignore_case=True)
  9147. output = outstream.getvalue().replace("\r\n", "\n")
  9148. self.assertEqual("case.txt:Hello WORLD\n", output)
  9149. def test_grep_with_pathspec(self) -> None:
  9150. """Test grep with pathspec filtering."""
  9151. os.makedirs(os.path.join(self.repo_path, "subdir"))
  9152. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  9153. f.write("pattern match\n")
  9154. with open(os.path.join(self.repo_path, "subdir", "file2.txt"), "w") as f:
  9155. f.write("pattern match\n")
  9156. porcelain.add(self.repo, paths=["file1.txt", "subdir/file2.txt"])
  9157. porcelain.commit(self.repo, message=b"Add files")
  9158. # Search only in subdir
  9159. outstream = StringIO()
  9160. porcelain.grep(self.repo, "pattern", outstream=outstream, pathspecs=["subdir/"])
  9161. output = outstream.getvalue().replace("\r\n", "\n")
  9162. self.assertEqual("subdir/file2.txt:pattern match\n", output)
  9163. def test_grep_no_matches(self) -> None:
  9164. """Test grep with no matches."""
  9165. with open(os.path.join(self.repo_path, "empty.txt"), "w") as f:
  9166. f.write("nothing to see here\n")
  9167. porcelain.add(self.repo, paths=["empty.txt"])
  9168. porcelain.commit(self.repo, message=b"Add empty file")
  9169. outstream = StringIO()
  9170. porcelain.grep(self.repo, "nonexistent", outstream=outstream)
  9171. output = outstream.getvalue()
  9172. self.assertEqual("", output)
  9173. def test_grep_regex_pattern(self) -> None:
  9174. """Test grep with regex patterns."""
  9175. with open(os.path.join(self.repo_path, "regex.txt"), "w") as f:
  9176. f.write("test123\ntest456\nnotest\n")
  9177. porcelain.add(self.repo, paths=["regex.txt"])
  9178. porcelain.commit(self.repo, message=b"Add regex file")
  9179. # Search for "test" followed by digits
  9180. outstream = StringIO()
  9181. porcelain.grep(self.repo, r"test\d+", outstream=outstream)
  9182. output = outstream.getvalue().replace("\r\n", "\n")
  9183. self.assertEqual("regex.txt:test123\nregex.txt:test456\n", output)
  9184. def test_grep_invalid_pattern(self) -> None:
  9185. """Test grep with invalid regex pattern."""
  9186. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  9187. f.write("test\n")
  9188. porcelain.add(self.repo, paths=["test.txt"])
  9189. porcelain.commit(self.repo, message=b"Add test file")
  9190. outstream = StringIO()
  9191. with self.assertRaises(ValueError):
  9192. porcelain.grep(self.repo, "[invalid", outstream=outstream)
  9193. def test_grep_no_head(self) -> None:
  9194. """Test grep fails when there's no HEAD commit."""
  9195. # Create a fresh repo with no commits
  9196. empty_repo_path = os.path.join(self.test_dir, "empty_repo")
  9197. empty_repo = Repo.init(empty_repo_path, mkdir=True)
  9198. self.addCleanup(empty_repo.close)
  9199. outstream = StringIO()
  9200. with self.assertRaises(ValueError):
  9201. porcelain.grep(empty_repo, "pattern", outstream=outstream)
  9202. class ReplaceListTests(PorcelainTestCase):
  9203. def test_empty(self) -> None:
  9204. """Test listing replacements when there are none."""
  9205. replacements = porcelain.replace_list(self.repo)
  9206. self.assertEqual([], replacements)
  9207. def test_list_replacements(self) -> None:
  9208. """Test listing replacement refs."""
  9209. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9210. self.repo[b"HEAD"] = c1.id
  9211. # Create a replacement
  9212. porcelain.replace_create(self.repo, c1.id, c2.id)
  9213. # List replacements
  9214. replacements = porcelain.replace_list(self.repo)
  9215. self.assertEqual(1, len(replacements))
  9216. self.assertEqual((c1.id, c2.id), replacements[0])
  9217. class ReplaceCreateTests(PorcelainTestCase):
  9218. def test_create_replacement(self) -> None:
  9219. """Test creating a replacement ref."""
  9220. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9221. self.repo[b"HEAD"] = c1.id
  9222. # Create a replacement
  9223. porcelain.replace_create(self.repo, c1.id, c2.id)
  9224. # Verify the replacement ref was created (c1.id is already 40-char hex bytes)
  9225. replace_ref = b"refs/replace/" + c1.id
  9226. self.assertIn(replace_ref, self.repo.refs)
  9227. self.assertEqual(c2.id, self.repo.refs[replace_ref])
  9228. def test_create_replacement_with_bytes(self) -> None:
  9229. """Test creating a replacement ref with bytes arguments."""
  9230. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9231. self.repo[b"HEAD"] = c1.id
  9232. # Create a replacement using bytes arguments
  9233. porcelain.replace_create(self.repo, c1.id, c2.id)
  9234. # Verify the replacement ref was created
  9235. replace_ref = b"refs/replace/" + c1.id
  9236. self.assertIn(replace_ref, self.repo.refs)
  9237. self.assertEqual(c2.id, self.repo.refs[replace_ref])
  9238. class ReplaceDeleteTests(PorcelainTestCase):
  9239. def test_delete_replacement(self) -> None:
  9240. """Test deleting a replacement ref."""
  9241. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9242. self.repo[b"HEAD"] = c1.id
  9243. # Create a replacement
  9244. porcelain.replace_create(self.repo, c1.id, c2.id)
  9245. # Verify it exists
  9246. replacements = porcelain.replace_list(self.repo)
  9247. self.assertEqual(1, len(replacements))
  9248. # Delete the replacement
  9249. porcelain.replace_delete(self.repo, c1.id)
  9250. # Verify it's gone
  9251. replacements = porcelain.replace_list(self.repo)
  9252. self.assertEqual(0, len(replacements))
  9253. def test_delete_replacement_with_bytes(self) -> None:
  9254. """Test deleting a replacement ref with bytes argument."""
  9255. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9256. self.repo[b"HEAD"] = c1.id
  9257. # Create a replacement
  9258. porcelain.replace_create(self.repo, c1.id, c2.id)
  9259. # Delete using bytes argument
  9260. porcelain.replace_delete(self.repo, c1.id)
  9261. # Verify it's gone
  9262. replacements = porcelain.replace_list(self.repo)
  9263. self.assertEqual(0, len(replacements))
  9264. def test_delete_nonexistent_replacement(self) -> None:
  9265. """Test deleting a replacement ref that doesn't exist raises KeyError."""
  9266. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9267. self.repo[b"HEAD"] = c1.id
  9268. # Try to delete a non-existent replacement
  9269. with self.assertRaises(KeyError):
  9270. porcelain.replace_delete(self.repo, c1.id)
  9271. class GitReflogActionTests(PorcelainTestCase):
  9272. """Tests for GIT_REFLOG_ACTION environment variable support."""
  9273. def test_reset_with_git_reflog_action(self) -> None:
  9274. """Test that reset respects GIT_REFLOG_ACTION environment variable."""
  9275. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9276. self.repo.refs[b"HEAD"] = c2.id
  9277. # Set GIT_REFLOG_ACTION environment variable
  9278. self.overrideEnv("GIT_REFLOG_ACTION", "custom reset action")
  9279. # Reset to c1
  9280. porcelain.reset(self.repo, "hard", c1.id.decode())
  9281. # Check reflog message - HEAD is a symref to refs/heads/master
  9282. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/master"))
  9283. self.assertEqual(1, len(entries))
  9284. self.assertEqual(b"custom reset action", entries[0].message)
  9285. def test_commit_amend_with_git_reflog_action(self) -> None:
  9286. """Test that commit --amend respects GIT_REFLOG_ACTION environment variable."""
  9287. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9288. self.repo.refs[b"HEAD"] = c1.id
  9289. # Set GIT_REFLOG_ACTION environment variable
  9290. self.overrideEnv("GIT_REFLOG_ACTION", "custom amend action")
  9291. # Amend the commit
  9292. porcelain.commit(self.repo, b"amended message", amend=True)
  9293. # Check reflog message - HEAD is a symref to refs/heads/master
  9294. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/master"))
  9295. self.assertEqual(1, len(entries))
  9296. self.assertEqual(b"custom amend action", entries[0].message)
  9297. def test_branch_create_with_git_reflog_action(self) -> None:
  9298. """Test that branch_create respects GIT_REFLOG_ACTION environment variable."""
  9299. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9300. self.repo.refs[b"HEAD"] = c1.id
  9301. # Set GIT_REFLOG_ACTION environment variable
  9302. self.overrideEnv("GIT_REFLOG_ACTION", "custom branch action")
  9303. # Create a new branch
  9304. porcelain.branch_create(self.repo, b"test-branch")
  9305. # Check reflog message
  9306. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/test-branch"))
  9307. self.assertEqual(1, len(entries))
  9308. self.assertEqual(b"custom branch action", entries[0].message)
  9309. def test_reset_without_git_reflog_action(self) -> None:
  9310. """Test that reset uses default message when GIT_REFLOG_ACTION is not set."""
  9311. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9312. self.repo.refs[b"HEAD"] = c2.id
  9313. # Reset to c1 without GIT_REFLOG_ACTION
  9314. porcelain.reset(self.repo, "hard", c1.id.decode())
  9315. # Check reflog message contains default format - HEAD is a symref to refs/heads/master
  9316. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/master"))
  9317. self.assertEqual(1, len(entries))
  9318. self.assertTrue(entries[0].message.startswith(b"reset: moving to"))
  9319. def test_branch_create_without_git_reflog_action(self) -> None:
  9320. """Test that branch_create uses default message when GIT_REFLOG_ACTION is not set."""
  9321. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9322. self.repo.refs[b"HEAD"] = c1.id
  9323. # Create a new branch without GIT_REFLOG_ACTION
  9324. porcelain.branch_create(self.repo, b"test-branch")
  9325. # Check reflog message contains default format
  9326. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/test-branch"))
  9327. self.assertEqual(1, len(entries))
  9328. self.assertTrue(entries[0].message.startswith(b"branch: Created from"))
  9329. class PorcelainMailinfoTests(TestCase):
  9330. """Tests for porcelain.mailinfo function."""
  9331. def test_mailinfo_basic(self) -> None:
  9332. """Test basic mailinfo functionality."""
  9333. from io import BytesIO
  9334. email_content = b"""From: Test User <test@example.com>
  9335. Subject: [PATCH] Add feature
  9336. Date: Mon, 1 Jan 2024 12:00:00 +0000
  9337. Commit message here.
  9338. ---
  9339. diff --git a/file.txt b/file.txt
  9340. """
  9341. result = porcelain.mailinfo(BytesIO(email_content))
  9342. self.assertEqual("Test User", result.author_name)
  9343. self.assertEqual("test@example.com", result.author_email)
  9344. self.assertEqual("Add feature", result.subject)
  9345. self.assertIn("Commit message here.", result.message)
  9346. self.assertIn("diff --git", result.patch)
  9347. def test_mailinfo_write_to_files(self) -> None:
  9348. """Test mailinfo writing message and patch to files."""
  9349. from io import BytesIO
  9350. email_content = b"""From: Test <test@example.com>
  9351. Subject: Test
  9352. Message content
  9353. ---
  9354. Patch content
  9355. """
  9356. with tempfile.TemporaryDirectory() as tmpdir:
  9357. msg_file = os.path.join(tmpdir, "msg")
  9358. patch_file = os.path.join(tmpdir, "patch")
  9359. result = porcelain.mailinfo(
  9360. BytesIO(email_content), msg_file=msg_file, patch_file=patch_file
  9361. )
  9362. # Check that files were written
  9363. self.assertTrue(os.path.exists(msg_file))
  9364. self.assertTrue(os.path.exists(patch_file))
  9365. # Check file contents
  9366. with open(msg_file) as f:
  9367. msg_content = f.read()
  9368. self.assertIn("Message content", msg_content)
  9369. with open(patch_file) as f:
  9370. patch_content = f.read()
  9371. self.assertIn("Patch content", patch_content)
  9372. # Check return value
  9373. self.assertEqual("Test", result.subject)
  9374. def test_mailinfo_with_options(self) -> None:
  9375. """Test mailinfo with various options."""
  9376. from io import BytesIO
  9377. email_content = b"""From: Test <test@example.com>
  9378. Subject: [RFC][PATCH] Feature
  9379. Message-ID: <id@example.com>
  9380. Text before scissors
  9381. -- >8 --
  9382. Text after scissors
  9383. """
  9384. # Test with keep_non_patch, scissors, and message_id
  9385. result = porcelain.mailinfo(
  9386. BytesIO(email_content),
  9387. keep_non_patch=True,
  9388. scissors=True,
  9389. message_id=True,
  9390. )
  9391. self.assertEqual("[RFC] Feature", result.subject)
  9392. self.assertIn("Text after scissors", result.message)
  9393. self.assertNotIn("Text before scissors", result.message)
  9394. self.assertIn("Message-ID:", result.message)
  9395. def test_mailinfo_from_file_path(self) -> None:
  9396. """Test mailinfo reading from file path."""
  9397. email_content = b"""From: Test <test@example.com>
  9398. Subject: Test
  9399. Body
  9400. """
  9401. with tempfile.TemporaryDirectory() as tmpdir:
  9402. email_path = os.path.join(tmpdir, "email.txt")
  9403. with open(email_path, "wb") as f:
  9404. f.write(email_content)
  9405. result = porcelain.mailinfo(input_path=email_path)
  9406. self.assertEqual("Test", result.subject)
  9407. self.assertEqual("test@example.com", result.author_email)