test_porcelain.py 225 KB

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