test_porcelain.py 376 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280
  1. # test_porcelain.py -- porcelain tests
  2. # Copyright (C) 2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Tests for dulwich.porcelain."""
  22. import contextlib
  23. import os
  24. import platform
  25. import re
  26. import shutil
  27. import stat
  28. import subprocess
  29. import sys
  30. import tarfile
  31. import tempfile
  32. import threading
  33. import time
  34. from io import BytesIO, StringIO
  35. from unittest import skipIf
  36. from dulwich import porcelain
  37. from dulwich.client import SendPackResult
  38. from dulwich.diff_tree import tree_changes
  39. from dulwich.errors import CommitError
  40. from dulwich.object_store import DEFAULT_TEMPFILE_GRACE_PERIOD
  41. from dulwich.objects import ZERO_SHA, Blob, Commit, Tag, Tree
  42. from dulwich.porcelain import (
  43. CheckoutError, # Hypothetical or real error class
  44. CountObjectsResult,
  45. add,
  46. commit,
  47. )
  48. from dulwich.repo import NoIndexPresent, Repo
  49. from dulwich.server import DictBackend
  50. from dulwich.tests.utils import build_commit_graph, make_commit, make_object
  51. from dulwich.web import make_server, make_wsgi_chain
  52. from . import TestCase
  53. try:
  54. import gpg
  55. except ImportError:
  56. gpg = None
  57. def flat_walk_dir(dir_to_walk):
  58. for dirpath, _, filenames in os.walk(dir_to_walk):
  59. rel_dirpath = os.path.relpath(dirpath, dir_to_walk)
  60. if not dirpath == dir_to_walk:
  61. yield rel_dirpath
  62. for filename in filenames:
  63. if dirpath == dir_to_walk:
  64. yield filename
  65. else:
  66. yield os.path.join(rel_dirpath, filename)
  67. class PorcelainTestCase(TestCase):
  68. def setUp(self) -> None:
  69. super().setUp()
  70. # Disable pagers for tests
  71. self.overrideEnv("PAGER", "false")
  72. self.overrideEnv("GIT_PAGER", "false")
  73. self.overrideEnv("DULWICH_PAGER", "false")
  74. self.test_dir = tempfile.mkdtemp()
  75. self.addCleanup(shutil.rmtree, self.test_dir)
  76. self.repo_path = os.path.join(self.test_dir, "repo")
  77. self.repo = Repo.init(self.repo_path, mkdir=True)
  78. self.addCleanup(self.repo.close)
  79. def assertRecentTimestamp(self, ts) -> None:
  80. # On some slow CIs it does actually take more than 5 seconds to go from
  81. # creating the tag to here.
  82. self.assertLess(time.time() - ts, 50)
  83. @skipIf(gpg is None, "gpg is not available")
  84. class PorcelainGpgTestCase(PorcelainTestCase):
  85. DEFAULT_KEY = """
  86. -----BEGIN PGP PRIVATE KEY BLOCK-----
  87. lQVYBGBjIyIBDADAwydvMPQqeEiK54FG1DHwT5sQejAaJOb+PsOhVa4fLcKsrO3F
  88. g5CxO+/9BHCXAr8xQAtp/gOhDN05fyK3MFyGlL9s+Cd8xf34S3R4rN/qbF0oZmaa
  89. FW0MuGnniq54HINs8KshadVn1Dhi/GYSJ588qNFRl/qxFTYAk+zaGsgX/QgFfy0f
  90. djWXJLypZXu9D6DlyJ0cPSzUlfBkI2Ytx6grzIquRjY0FbkjK3l+iGsQ+ebRMdcP
  91. Sqd5iTN9XuzIUVoBFAZBRjibKV3N2wxlnCbfLlzCyDp7rktzSThzjJ2pVDuLrMAx
  92. 6/L9hIhwmFwdtY4FBFGvMR0b0Ugh3kCsRWr8sgj9I7dUoLHid6ObYhJFhnD3GzRc
  93. U+xX1uy3iTCqJDsG334aQIhC5Giuxln4SUZna2MNbq65ksh38N1aM/t3+Dc/TKVB
  94. rb5KWicRPCQ4DIQkHMDCSPyj+dvRLCPzIaPvHD7IrCfHYHOWuvvPGCpwjo0As3iP
  95. IecoMeguPLVaqgcAEQEAAQAL/i5/pQaUd4G7LDydpbixPS6r9UrfPrU/y5zvBP/p
  96. DCynPDutJ1oq539pZvXQ2VwEJJy7x0UVKkjyMndJLNWly9wHC7o8jkHx/NalVP47
  97. LXR+GWbCdOOcYYbdAWcCNB3zOtzPnWhdAEagkc2G9xRQDIB0dLHLCIUpCbLP/CWM
  98. qlHnDsVMrVTWjgzcpsnyGgw8NeLYJtYGB8dsN+XgCCjo7a9LEvUBKNgdmWBbf14/
  99. iBw7PCugazFcH9QYfZwzhsi3nqRRagTXHbxFRG0LD9Ro9qCEutHYGP2PJ59Nj8+M
  100. zaVkJj/OxWxVOGvn2q16mQBCjKpbWfqXZVVl+G5DGOmiSTZqXy+3j6JCKdOMy6Qd
  101. JBHOHhFZXYmWYaaPzoc33T/C3QhMfY5sOtUDLJmV05Wi4dyBeNBEslYgUuTk/jXb
  102. 5ZAie25eDdrsoqkcnSs2ZguMF7AXhe6il2zVhUUMs/6UZgd6I7I4Is0HXT/pnxEp
  103. uiTRFu4v8E+u+5a8O3pffe5boQYA3TsIxceen20qY+kRaTOkURHMZLn/y6KLW8bZ
  104. rNJyXWS9hBAcbbSGhfOwYfzbDCM17yPQO3E2zo8lcGdRklUdIIaCxQwtu36N5dfx
  105. OLCCQc5LmYdl/EAm91iAhrr7dNntZ18MU09gdzUu+ONZwu4CP3cJT83+qYZULso8
  106. 4Fvd/X8IEfGZ7kM+ylrdqBwtlrn8yYXtom+ows2M2UuNR53B+BUOd73kVLTkTCjE
  107. JH63+nE8BqG7tDLCMws+23SAA3xxBgDfDrr0x7zCozQKVQEqBzQr9Uoo/c/ZjAfi
  108. syzNSrDz+g5gqJYtuL9XpPJVWf6V1GXVyJlSbxR9CjTkBxmlPxpvV25IsbVSsh0o
  109. aqkf2eWpbCL6Qb2E0jd1rvf8sGeTTohzYfiSVVsC2t9ngRO/CmetizwQBvRzLGMZ
  110. 4mtAPiy7ZEDc2dFrPp7zlKISYmJZUx/DJVuZWuOrVMpBP+bSgJXoMTlICxZUqUnE
  111. 2VKVStb/L+Tl8XCwIWdrZb9BaDnHqfcGAM2B4HNPxP88Yj1tEDly/vqeb3vVMhj+
  112. S1lunnLdgxp46YyuTMYAzj88eCGurRtzBsdxxlGAsioEnZGebEqAHQbieKq/DO6I
  113. MOMZHMSVBDqyyIx3assGlxSX8BSFW0lhKyT7i0XqnAgCJ9f/5oq0SbFGq+01VQb7
  114. jIx9PbcYJORxsE0JG/CXXPv27bRtQXsudkWGSYvC0NLOgk4z8+kQpQtyFh16lujq
  115. WRwMeriu0qNDjCa1/eHIKDovhAZ3GyO5/9m1tBlUZXN0IFVzZXIgPHRlc3RAdGVz
  116. dC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAFiEEjrR8
  117. MQ4fJK44PYMvfN2AClLmXiYFAmDcEZEACgkQfN2AClLmXibZzgv/ZfeTpTuqQE1W
  118. C1jT5KpQExnt0BizTX0U7BvSn8Fr6VXTyol6kYc3u71GLUuJyawCLtIzOXqOXJvz
  119. bjcZqymcMADuftKcfMy513FhbF6MhdVd6QoeBP6+7/xXOFJCi+QVYF7SQ2h7K1Qm
  120. +yXOiAMgSxhCZQGPBNJLlDUOd47nSIMANvlumFtmLY/1FD7RpG7WQWjeX1mnxNTw
  121. hUU+Yv7GuFc/JprXCIYqHbhWfvXyVtae2ZK4xuVi5eqwA2RfggOVM7drb+CgPhG0
  122. +9aEDDLOZqVi65wK7J73Puo3rFTbPQMljxw5s27rWqF+vB6hhVdJOPNomWy3naPi
  123. k5MW0mhsacASz1WYndpZz+XaQTq/wJF5HUyyeUWJ0vlOEdwx021PHcqSTyfNnkjD
  124. KncrE21t2sxWRsgGDETxIwkd2b2HNGAvveUD0ffFK/oJHGSXjAERFGc3wuiDj3mQ
  125. BvKm4wt4QF9ZMrCdhMAA6ax5kfEUqQR4ntmrJk/khp/mV7TILaI4nQVYBGBjIyIB
  126. DADghIo9wXnRxzfdDTvwnP8dHpLAIaPokgdpyLswqUCixJWiW2xcV6weUjEWwH6n
  127. eN/t1uZYVehbrotxVPla+MPvzhxp6/cmG+2lhzEBOp6zRwnL1wIB6HoKJfpREhyM
  128. c8rLR0zMso1L1bJTyydvnu07a7BWo3VWKjilb0rEZZUSD/2hidx5HxMOJSoidLWe
  129. d/PPuv6yht3NtA4UThlcfldm9G6PbqCdm1kMEKAkq0wVJvhPJ6gEFRNJimgygfUw
  130. MDFXEIhQtxjgdV5Uoz3O5452VLoRsDlgpi3E0WDGj7WXDaO5uSU0T5aJgVgHCP/f
  131. xZhHuQFk2YYIl5nCBpOZyWWI0IKmscTuEwzpkhICQDQFvcMZ5ibsl7wA2P7YTrQf
  132. FDMjjzuaK80GYPfxDFlyKUyLqFt8w/QzsZLDLX7+jxIEpbRAaMw/JsWqm5BMxxbS
  133. 3CIQiS5S3oSKDsNINelqWFfwvLhvlQra8gIxyNTlek25OdgG66BiiX+seH8A/ql+
  134. F+MAEQEAAQAL/1jrNSLjMt9pwo6qFKClVQZP2vf7+sH7v7LeHIDXr3EnYUnVYnOq
  135. B1FU5PspTp/+J9W25DB9CZLx7Gj8qeslFdiuLSOoIBB4RCToB3kAoeTH0DHqW/Gs
  136. hFTrmJkuDp9zpo/ek6SIXJx5rHAyR9KVw0fizQprH2f6PcgLbTWeM61dJuqowmg3
  137. 7eCOyIKv7VQvFqEhYokLD+JNmrvg+Htg0DXGvdjRjAwPf/NezEXpj67a6cHTp1/C
  138. hwp7pevG+3fTxaCJFesl5/TxxtnaBLE8m2uo/S6Hxgn9l0edonroe1QlTjEqGLy2
  139. 7qi2z5Rem+v6GWNDRgvAWur13v8FNdyduHlioG/NgRsU9mE2MYeFsfi3cfNpJQp/
  140. wC9PSCIXrb/45mkS8KyjZpCrIPB9RV/m0MREq01TPom7rstZc4A1pD0Ot7AtUYS3
  141. e95zLyEmeLziPJ9fV4fgPmEudDr1uItnmV0LOskKlpg5sc0hhdrwYoobfkKt2dx6
  142. DqfMlcM1ZkUbLQYA4jwfpFJG4HmYvjL2xCJxM0ycjvMbqFN+4UjgYWVlRfOrm1V4
  143. Op86FjbRbV6OOCNhznotAg7mul4xtzrrTkK8o3YLBeJseDgl4AWuzXtNa9hE0XpK
  144. 9gJoEHUuBOOsamVh2HpXESFyE5CclOV7JSh541TlZKfnqfZYCg4JSbp0UijkawCL
  145. 5bJJUiGGMD9rZUxIAKQO1DvUEzptS7Jl6S3y5sbIIhilp4KfYWbSk3PPu9CnZD5b
  146. LhEQp0elxnb/IL8PBgD+DpTeC8unkGKXUpbe9x0ISI6V1D6FmJq/FxNg7fMa3QCh
  147. fGiAyoTm80ZETynj+blRaDO3gY4lTLa3Opubof1EqK2QmwXmpyvXEZNYcQfQ2CCS
  148. GOWUCK8jEQamUPf1PWndZXJUmROI1WukhlL71V/ir6zQeVCv1wcwPwclJPnAe87u
  149. pEklnCYpvsEldwHUX9u0BWzoULIEsi+ddtHmT0KTeF/DHRy0W15jIHbjFqhqckj1
  150. /6fmr7l7kIi/kN4vWe0F/0Q8IXX+cVMgbl3aIuaGcvENLGcoAsAtPGx88SfRgmfu
  151. HK64Y7hx1m+Bo215rxJzZRjqHTBPp0BmCi+JKkaavIBrYRbsx20gveI4dzhLcUhB
  152. kiT4Q7oz0/VbGHS1CEf9KFeS/YOGj57s4yHauSVI0XdP9kBRTWmXvBkzsooB2cKH
  153. hwhUN7iiT1k717CiTNUT6Q/pcPFCyNuMoBBGQTU206JEgIjQvI3f8xMUMGmGVVQz
  154. 9/k716ycnhb2JZ/Q/AyQIeHJiQG2BBgBCAAgAhsMFiEEjrR8MQ4fJK44PYMvfN2A
  155. ClLmXiYFAmDcEa4ACgkQfN2AClLmXiZxxQv/XaMN0hPCygtrQMbCsTNb34JbvJzh
  156. hngPuUAfTbRHrR3YeATyQofNbL0DD3fvfzeFF8qESqvzCSZxS6dYsXPd4MCJTzlp
  157. zYBZ2X0sOrgDqZvqCZKN72RKgdk0KvthdzAxsIm2dfcQOxxowXMxhJEXZmsFpusx
  158. jKJxOcrfVRjXJnh9isY0NpCoqMQ+3k3wDJ3VGEHV7G+A+vFkWfbLJF5huQ96uaH9
  159. Uc+jUsREUH9G82ZBqpoioEN8Ith4VXpYnKdTMonK/+ZcyeraJZhXrvbjnEomKdzU
  160. 0pu4bt1HlLR3dcnpjN7b009MBf2xLgEfQk2nPZ4zzY+tDkxygtPllaB4dldFjBpT
  161. j7Q+t49sWMjmlJUbLlHfuJ7nUUK5+cGjBsWVObAEcyfemHWCTVFnEa2BJslGC08X
  162. rFcjRRcMEr9ct4551QFBHsv3O/Wp3/wqczYgE9itSnGT05w+4vLt4smG+dnEHjRJ
  163. brMb2upTHa+kjktjdO96/BgSnKYqmNmPB/qB
  164. =ivA/
  165. -----END PGP PRIVATE KEY BLOCK-----
  166. """
  167. DEFAULT_KEY_ID = "8EB47C310E1F24AE383D832F7CDD800A52E65E26"
  168. NON_DEFAULT_KEY = """
  169. -----BEGIN PGP PRIVATE KEY BLOCK-----
  170. lQVYBGBjI0ABDADGWBRp+t02emfzUlhrc1psqIhhecFm6Em0Kv33cfDpnfoMF1tK
  171. Yy/4eLYIR7FmpdbFPcDThFNHbXJzBi00L1mp0XQE2l50h/2bDAAgREdZ+NVo5a7/
  172. RSZjauNU1PxW6pnXMehEh1tyIQmV78jAukaakwaicrpIenMiFUN3fAKHnLuFffA6
  173. t0f3LqJvTDhUw/o2vPgw5e6UDQhA1C+KTv1KXVrhJNo88a3hZqCZ76z3drKR411Q
  174. zYgT4DUb8lfnbN+z2wfqT9oM5cegh2k86/mxAA3BYOeQrhmQo/7uhezcgbxtdGZr
  175. YlbuaNDTSBrn10ZoaxLPo2dJe2zWxgD6MpvsGU1w3tcRW508qo/+xoWp2/pDzmok
  176. +uhOh1NAj9zB05VWBz1r7oBgCOIKpkD/LD4VKq59etsZ/UnrYDwKdXWZp7uhshkU
  177. M7N35lUJcR76a852dlMdrgpmY18+BP7+o7M+5ElHTiqQbMuE1nHTg8RgVpdV+tUx
  178. dg6GWY/XHf5asm8AEQEAAQAL/A85epOp+GnymmEQfI3+5D178D//Lwu9n86vECB6
  179. xAHCqQtdjZnXpDp/1YUsL59P8nzgYRk7SoMskQDoQ/cB/XFuDOhEdMSgHaTVlnrj
  180. ktCCq6rqGnUosyolbb64vIfVaSqd/5SnCStpAsnaBoBYrAu4ZmV4xfjDQWwn0q5s
  181. u+r56mD0SkjPgbwk/b3qTVagVmf2OFzUgWwm1e/X+bA1oPag1NV8VS4hZPXswT4f
  182. qhiyqUFOgP6vUBcqehkjkIDIl/54xII7/P5tp3LIZawvIXqHKNTqYPCqaCqCj+SL
  183. vMYDIb6acjescfZoM71eAeHAANeFZzr/rwfBT+dEP6qKmPXNcvgE11X44ZCr04nT
  184. zOV/uDUifEvKT5qgtyJpSFEVr7EXubJPKoNNhoYqq9z1pYU7IedX5BloiVXKOKTY
  185. 0pk7JkLqf3g5fYtXh/wol1owemITJy5V5PgaqZvk491LkI6S+kWC7ANYUg+TDPIW
  186. afxW3E5N1CYV6XDAl0ZihbLcoQYAy0Ky/p/wayWKePyuPBLwx9O89GSONK2pQljZ
  187. yaAgxPQ5/i1vx6LIMg7k/722bXR9W3zOjWOin4eatPM3d2hkG96HFvnBqXSmXOPV
  188. 03Xqy1/B5Tj8E9naLKUHE/OBQEc363DgLLG9db5HfPlpAngeppYPdyWkhzXyzkgS
  189. PylaE5eW3zkdjEbYJ6RBTecTZEgBaMvJNPdWbn//frpP7kGvyiCg5Es+WjLInUZ6
  190. 0sdifcNTCewzLXK80v/y5mVOdJhPBgD5zs9cYdyiQJayqAuOr+He1eMHMVUbm9as
  191. qBmPrst398eBW9ZYF7eBfTSlUf6B+WnvyLKEGsUf/7IK0EWDlzoBuWzWiHjUAY1g
  192. m9eTV2MnvCCCefqCErWwfFo2nWOasAZA9sKD+ICIBY4tbtvSl4yfLBzTMwSvs9ZS
  193. K1ocPSYUnhm2miSWZ8RLZPH7roHQasNHpyq/AX7DahFf2S/bJ+46ZGZ8Pigr7hA+
  194. MjmpQ4qVdb5SaViPmZhAKO+PjuCHm+EF/2H0Y3Sl4eXgxZWoQVOUeXdWg9eMfYrj
  195. XDtUMIFppV/QxbeztZKvJdfk64vt/crvLsOp0hOky9cKwY89r4QaHfexU3qR+qDq
  196. UlMvR1rHk7dS5HZAtw0xKsFJNkuDxvBkMqv8Los8zp3nUl+U99dfZOArzNkW38wx
  197. FPa0ixkC9za2BkDrWEA8vTnxw0A2upIFegDUhwOByrSyfPPnG3tKGeqt3Izb/kDk
  198. Q9vmo+HgxBOguMIvlzbBfQZwtbd/gXzlvPqCtCJBbm90aGVyIFRlc3QgVXNlciA8
  199. dGVzdDJAdGVzdC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4B
  200. AheAFiEEapM5P1DF5qzT1vtFuTYhLttOFMAFAmDcEeEACgkQuTYhLttOFMDe0Qv/
  201. Qx/bzXztJ3BCc+CYAVDx7Kr37S68etwwLgcWzhG+CDeMB5F/QE+upKgxy2iaqQFR
  202. mxfOMgf/TIQkUfkbaASzK1LpnesYO85pk7XYjoN1bYEHiXTkeW+bgB6aJIxrRmO2
  203. SrWasdBC/DsI3Mrya8YMt/TiHC6VpRJVxCe5vv7/kZC4CXrgTBnZocXx/YXimbke
  204. poPMVdbvhYh6N0aGeS38jRKgyN10KXmhDTAQDwseVFavBWAjVfx3DEwjtK2Z2GbA
  205. aL8JvAwRtqiPFkDMIKPL4UwxtXFws8SpMt6juroUkNyf6+BxNWYqmwXHPy8zCJAb
  206. xkxIJMlEc+s7qQsP3fILOo8Xn+dVzJ5sa5AoARoXm1GMjsdqaKAzq99Dic/dHnaQ
  207. Civev1PQsdwlYW2C2wNXNeIrxMndbDMFfNuZ6BnGHWJ/wjcp/pFs4YkyyZN8JH7L
  208. hP2FO4Jgham3AuP13kC3Ivea7V6hR8QNcDZRwFPOMIX4tXwQv1T72+7DZGaA25O7
  209. nQVXBGBjI0ABDADJMBYIcG0Yil9YxFs7aYzNbd7alUAr89VbY8eIGPHP3INFPM1w
  210. lBQCu+4j6xdEbhMpppLBZ9A5TEylP4C6qLtPa+oLtPeuSw8gHDE10XE4lbgPs376
  211. rL60XdImSOHhiduACUefYjqpcmFH9Bim1CC+koArYrSQJQx1Jri+OpnTaL/8UID0
  212. KzD/kEgMVGlHIVj9oJmb4+j9pW8I/g0wDSnIaEKFMxqu6SIVJ1GWj+MUMvZigjLC
  213. sNCZd7PnbOC5VeU3SsXj6he74Jx0AmGMPWIHi9M0DjHO5d1cCbXTnud8xxM1bOh4
  214. 7aCTnMK5cVyIr+adihgJpVVhrndSM8aklBPRgtozrGNCgF2CkYU2P1blxfloNr/8
  215. UZpM83o+s1aObBszzRNLxnpNORqoLqjfPtLEPQnagxE+4EapCq0NZ/x6yO5VTwwp
  216. NljdFAEk40uGuKyn1QA3uNMHy5DlpLl+tU7t1KEovdZ+OVYsYKZhVzw0MTpKogk9
  217. JI7AN0q62ronPskAEQEAAQAL+O8BUSt1ZCVjPSIXIsrR+ZOSkszZwgJ1CWIoh0IH
  218. YD2vmcMHGIhFYgBdgerpvhptKhaw7GcXDScEnYkyh5s4GE2hxclik1tbj/x1gYCN
  219. 8BNoyeDdPFxQG73qN12D99QYEctpOsz9xPLIDwmL0j1ehAfhwqHIAPm9Ca+i8JYM
  220. x/F+35S/jnKDXRI+NVlwbiEyXKXxxIqNlpy9i8sDBGexO5H5Sg0zSN/B1duLekGD
  221. biDw6gLc6bCgnS+0JOUpU07Z2fccMOY9ncjKGD2uIb/ePPUaek92GCQyq0eorCIV
  222. brcQsRc5sSsNtnRKQTQtxioROeDg7kf2oWySeHTswlXW/219ihrSXgteHJd+rPm7
  223. DYLEeGLRny8bRKv8rQdAtApHaJE4dAATXeY4RYo4NlXHYaztGYtU6kiM/3zCfWAe
  224. 9Nn+Wh9jMTZrjefUCagS5r6ZqAh7veNo/vgIGaCLh0a1Ypa0Yk9KFrn3LYEM3zgk
  225. 3m3bn+7qgy5cUYXoJ3DGJJEhBgDPonpW0WElqLs5ZMem1ha85SC38F0IkAaSuzuz
  226. v3eORiKWuyJGF32Q2XHa1RHQs1JtUKd8rxFer3b8Oq71zLz6JtVc9dmRudvgcJYX
  227. 0PC11F6WGjZFSSp39dajFp0A5DKUs39F3w7J1yuDM56TDIN810ywufGAHARY1pZb
  228. UJAy/dTqjFnCbNjpAakor3hVzqxcmUG+7Y2X9c2AGncT1MqAQC3M8JZcuZvkK8A9
  229. cMk8B914ryYE7VsZMdMhyTwHmykGAPgNLLa3RDETeGeGCKWI+ZPOoU0ib5JtJZ1d
  230. P3tNwfZKuZBZXKW9gqYqyBa/qhMip84SP30pr/TvulcdAFC759HK8sQZyJ6Vw24P
  231. c+5ssRxrQUEw1rvJPWhmQCmCOZHBMQl5T6eaTOpR5u3aUKTMlxPKhK9eC1dCSTnI
  232. /nyL8An3VKnLy+K/LI42YGphBVLLJmBewuTVDIJviWRdntiG8dElyEJMOywUltk3
  233. 2CEmqgsD9tPO8rXZjnMrMn3gfsiaoQYA6/6/e2utkHr7gAoWBgrBBdqVHsvqh5Ro
  234. 2DjLAOpZItO/EdCJfDAmbTYOa04535sBDP2tcH/vipPOPpbr1Y9Y/mNsKCulNxed
  235. yqAmEkKOcerLUP5UHju0AB6VBjHJFdU2mqT+UjPyBk7WeKXgFomyoYMv3KpNOFWR
  236. xi0Xji4kKHbttA6Hy3UcGPr9acyUAlDYeKmxbSUYIPhw32bbGrX9+F5YriTufRsG
  237. 3jftQVo9zqdcQSD/5pUTMn3EYbEcohYB2YWJAbYEGAEIACACGwwWIQRqkzk/UMXm
  238. rNPW+0W5NiEu204UwAUCYNwR6wAKCRC5NiEu204UwOPnC/92PgB1c3h9FBXH1maz
  239. g29fndHIHH65VLgqMiQ7HAMojwRlT5Xnj5tdkCBmszRkv5vMvdJRa3ZY8Ed/Inqr
  240. hxBFNzpjqX4oj/RYIQLKXWWfkTKYVLJFZFPCSo00jesw2gieu3Ke/Yy4gwhtNodA
  241. v+s6QNMvffTW/K3XNrWDB0E7/LXbdidzhm+MBu8ov2tuC3tp9liLICiE1jv/2xT4
  242. CNSO6yphmk1/1zEYHS/mN9qJ2csBmte2cdmGyOcuVEHk3pyINNMDOamaURBJGRwF
  243. XB5V7gTKUFU4jCp3chywKrBHJHxGGDUmPBmZtDtfWAOgL32drK7/KUyzZL/WO7Fj
  244. akOI0hRDFOcqTYWL20H7+hAiX3oHMP7eou3L5C7wJ9+JMcACklN/WMjG9a536DFJ
  245. 4UgZ6HyKPP+wy837Hbe8b25kNMBwFgiaLR0lcgzxj7NyQWjVCMOEN+M55tRCjvL6
  246. ya6JVZCRbMXfdCy8lVPgtNQ6VlHaj8Wvnn2FLbWWO2n2r3s=
  247. =9zU5
  248. -----END PGP PRIVATE KEY BLOCK-----
  249. """
  250. NON_DEFAULT_KEY_ID = "6A93393F50C5E6ACD3D6FB45B936212EDB4E14C0"
  251. def setUp(self) -> None:
  252. super().setUp()
  253. self.gpg_dir = os.path.join(self.test_dir, "gpg")
  254. os.mkdir(self.gpg_dir, mode=0o700)
  255. # Ignore errors when deleting GNUPGHOME, because of race conditions
  256. # (e.g. the gpg-agent socket having been deleted). See
  257. # https://github.com/jelmer/dulwich/issues/1000
  258. self.addCleanup(shutil.rmtree, self.gpg_dir, ignore_errors=True)
  259. self.overrideEnv("GNUPGHOME", self.gpg_dir)
  260. def import_default_key(self) -> None:
  261. subprocess.run(
  262. ["gpg", "--import"],
  263. stdout=subprocess.DEVNULL,
  264. stderr=subprocess.DEVNULL,
  265. input=PorcelainGpgTestCase.DEFAULT_KEY,
  266. text=True,
  267. )
  268. def import_non_default_key(self) -> None:
  269. subprocess.run(
  270. ["gpg", "--import"],
  271. stdout=subprocess.DEVNULL,
  272. stderr=subprocess.DEVNULL,
  273. input=PorcelainGpgTestCase.NON_DEFAULT_KEY,
  274. text=True,
  275. )
  276. class ArchiveTests(PorcelainTestCase):
  277. """Tests for the archive command."""
  278. def test_simple(self) -> None:
  279. _c1, _c2, c3 = build_commit_graph(
  280. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  281. )
  282. self.repo.refs[b"refs/heads/master"] = c3.id
  283. out = BytesIO()
  284. err = BytesIO()
  285. porcelain.archive(
  286. self.repo.path, b"refs/heads/master", outstream=out, errstream=err
  287. )
  288. self.assertEqual(b"", err.getvalue())
  289. tf = tarfile.TarFile(fileobj=out)
  290. self.addCleanup(tf.close)
  291. self.assertEqual([], tf.getnames())
  292. class UpdateServerInfoTests(PorcelainTestCase):
  293. def test_simple(self) -> None:
  294. _c1, _c2, c3 = build_commit_graph(
  295. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  296. )
  297. self.repo.refs[b"refs/heads/foo"] = c3.id
  298. porcelain.update_server_info(self.repo.path)
  299. self.assertTrue(
  300. os.path.exists(os.path.join(self.repo.controldir(), "info", "refs"))
  301. )
  302. class CommitTests(PorcelainTestCase):
  303. def test_custom_author(self) -> None:
  304. _c1, _c2, c3 = build_commit_graph(
  305. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  306. )
  307. self.repo.refs[b"refs/heads/foo"] = c3.id
  308. sha = porcelain.commit(
  309. self.repo.path,
  310. message=b"Some message",
  311. author=b"Joe <joe@example.com>",
  312. committer=b"Bob <bob@example.com>",
  313. )
  314. self.assertIsInstance(sha, bytes)
  315. self.assertEqual(len(sha), 40)
  316. def test_unicode(self) -> None:
  317. _c1, _c2, c3 = build_commit_graph(
  318. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  319. )
  320. self.repo.refs[b"refs/heads/foo"] = c3.id
  321. sha = porcelain.commit(
  322. self.repo.path,
  323. message="Some message",
  324. author="Joe <joe@example.com>",
  325. committer="Bob <bob@example.com>",
  326. )
  327. self.assertIsInstance(sha, bytes)
  328. self.assertEqual(len(sha), 40)
  329. def test_no_verify(self) -> None:
  330. if os.name != "posix":
  331. self.skipTest("shell hook tests requires POSIX shell")
  332. self.assertTrue(os.path.exists("/bin/sh"))
  333. hooks_dir = os.path.join(self.repo.controldir(), "hooks")
  334. os.makedirs(hooks_dir, exist_ok=True)
  335. self.addCleanup(shutil.rmtree, hooks_dir)
  336. _c1, _c2, _c3 = build_commit_graph(
  337. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  338. )
  339. hook_fail = "#!/bin/sh\nexit 1"
  340. # hooks are executed in pre-commit, commit-msg order
  341. # test commit-msg failure first, then pre-commit failure, then
  342. # no_verify to skip both hooks
  343. commit_msg = os.path.join(hooks_dir, "commit-msg")
  344. with open(commit_msg, "w") as f:
  345. f.write(hook_fail)
  346. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  347. with self.assertRaises(CommitError):
  348. porcelain.commit(
  349. self.repo.path,
  350. message="Some message",
  351. author="Joe <joe@example.com>",
  352. committer="Bob <bob@example.com>",
  353. )
  354. pre_commit = os.path.join(hooks_dir, "pre-commit")
  355. with open(pre_commit, "w") as f:
  356. f.write(hook_fail)
  357. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  358. with self.assertRaises(CommitError):
  359. porcelain.commit(
  360. self.repo.path,
  361. message="Some message",
  362. author="Joe <joe@example.com>",
  363. committer="Bob <bob@example.com>",
  364. )
  365. sha = porcelain.commit(
  366. self.repo.path,
  367. message="Some message",
  368. author="Joe <joe@example.com>",
  369. committer="Bob <bob@example.com>",
  370. no_verify=True,
  371. )
  372. self.assertIsInstance(sha, bytes)
  373. self.assertEqual(len(sha), 40)
  374. def test_timezone(self) -> None:
  375. _c1, _c2, c3 = build_commit_graph(
  376. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  377. )
  378. self.repo.refs[b"refs/heads/foo"] = c3.id
  379. sha = porcelain.commit(
  380. self.repo.path,
  381. message="Some message",
  382. author="Joe <joe@example.com>",
  383. author_timezone=18000,
  384. committer="Bob <bob@example.com>",
  385. commit_timezone=18000,
  386. )
  387. self.assertIsInstance(sha, bytes)
  388. self.assertEqual(len(sha), 40)
  389. commit = self.repo.get_object(sha)
  390. assert isinstance(commit, Commit)
  391. self.assertEqual(commit._author_timezone, 18000)
  392. self.assertEqual(commit._commit_timezone, 18000)
  393. self.overrideEnv("GIT_AUTHOR_DATE", "1995-11-20T19:12:08-0501")
  394. self.overrideEnv("GIT_COMMITTER_DATE", "1995-11-20T19:12:08-0501")
  395. sha = porcelain.commit(
  396. self.repo.path,
  397. message="Some message",
  398. author="Joe <joe@example.com>",
  399. committer="Bob <bob@example.com>",
  400. )
  401. self.assertIsInstance(sha, bytes)
  402. self.assertEqual(len(sha), 40)
  403. commit = self.repo.get_object(sha)
  404. assert isinstance(commit, Commit)
  405. self.assertEqual(commit._author_timezone, -18060)
  406. self.assertEqual(commit._commit_timezone, -18060)
  407. self.overrideEnv("GIT_AUTHOR_DATE", None)
  408. self.overrideEnv("GIT_COMMITTER_DATE", None)
  409. local_timezone = time.localtime().tm_gmtoff
  410. sha = porcelain.commit(
  411. self.repo.path,
  412. message="Some message",
  413. author="Joe <joe@example.com>",
  414. committer="Bob <bob@example.com>",
  415. )
  416. self.assertIsInstance(sha, bytes)
  417. self.assertEqual(len(sha), 40)
  418. commit = self.repo.get_object(sha)
  419. assert isinstance(commit, Commit)
  420. self.assertEqual(commit._author_timezone, local_timezone)
  421. self.assertEqual(commit._commit_timezone, local_timezone)
  422. def test_commit_all(self) -> None:
  423. # Create initial commit
  424. filename = os.path.join(self.repo.path, "test.txt")
  425. with open(filename, "wb") as f:
  426. f.write(b"initial content")
  427. porcelain.add(self.repo.path, paths=["test.txt"])
  428. initial_sha = porcelain.commit(self.repo.path, message=b"Initial commit")
  429. # Modify the file without staging
  430. with open(filename, "wb") as f:
  431. f.write(b"modified content")
  432. # Create an untracked file
  433. untracked_file = os.path.join(self.repo.path, "untracked.txt")
  434. with open(untracked_file, "wb") as f:
  435. f.write(b"untracked content")
  436. # Commit with all=True should stage modified files but not untracked
  437. sha = porcelain.commit(self.repo.path, message=b"Modified commit", all=True)
  438. self.assertIsInstance(sha, bytes)
  439. self.assertEqual(len(sha), 40)
  440. self.assertNotEqual(sha, initial_sha)
  441. # Verify the commit contains the modification
  442. commit = self.repo.get_object(sha)
  443. assert isinstance(commit, Commit)
  444. tree = self.repo.get_object(commit.tree)
  445. # The modified file should be in the commit
  446. self.assertIn(b"test.txt", tree)
  447. # The untracked file should not be in the commit
  448. self.assertNotIn(b"untracked.txt", tree)
  449. def test_commit_all_no_changes(self) -> None:
  450. # Create initial commit
  451. filename = os.path.join(self.repo.path, "test.txt")
  452. with open(filename, "wb") as f:
  453. f.write(b"initial content")
  454. porcelain.add(self.repo.path, paths=["test.txt"])
  455. initial_sha = porcelain.commit(self.repo.path, message=b"Initial commit")
  456. # Try to commit with all=True when there are no unstaged changes
  457. sha = porcelain.commit(self.repo.path, message=b"No changes commit", all=True)
  458. self.assertIsInstance(sha, bytes)
  459. self.assertEqual(len(sha), 40)
  460. self.assertNotEqual(sha, initial_sha)
  461. def test_commit_all_multiple_files(self) -> None:
  462. # Create initial commit with multiple files
  463. file1 = os.path.join(self.repo.path, "file1.txt")
  464. file2 = os.path.join(self.repo.path, "file2.txt")
  465. with open(file1, "wb") as f:
  466. f.write(b"content1")
  467. with open(file2, "wb") as f:
  468. f.write(b"content2")
  469. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  470. initial_sha = porcelain.commit(self.repo.path, message=b"Initial commit")
  471. # Modify both files
  472. with open(file1, "wb") as f:
  473. f.write(b"modified content1")
  474. with open(file2, "wb") as f:
  475. f.write(b"modified content2")
  476. # Commit with all=True should stage both modified files
  477. sha = porcelain.commit(self.repo.path, message=b"Modified both files", all=True)
  478. self.assertIsInstance(sha, bytes)
  479. self.assertEqual(len(sha), 40)
  480. self.assertNotEqual(sha, initial_sha)
  481. # Verify both modifications are in the commit
  482. commit = self.repo.get_object(sha)
  483. assert isinstance(commit, Commit)
  484. tree = self.repo.get_object(commit.tree)
  485. self.assertIn(b"file1.txt", tree)
  486. self.assertIn(b"file2.txt", tree)
  487. def test_commit_amend_message(self) -> None:
  488. # Create initial commit
  489. filename = os.path.join(self.repo.path, "test.txt")
  490. with open(filename, "wb") as f:
  491. f.write(b"initial content")
  492. porcelain.add(self.repo.path, paths=["test.txt"])
  493. original_sha = porcelain.commit(self.repo.path, message=b"Original commit")
  494. # Amend with new message
  495. amended_sha = porcelain.commit(
  496. self.repo.path, message=b"Amended commit", amend=True
  497. )
  498. self.assertIsInstance(amended_sha, bytes)
  499. self.assertEqual(len(amended_sha), 40)
  500. self.assertNotEqual(amended_sha, original_sha)
  501. # Check that the amended commit has the new message
  502. amended_commit = self.repo.get_object(amended_sha)
  503. assert isinstance(amended_commit, Commit)
  504. self.assertEqual(amended_commit.message, b"Amended commit")
  505. # Check that the amended commit uses the original commit's parents
  506. original_commit = self.repo.get_object(original_sha)
  507. assert isinstance(original_commit, Commit)
  508. # Since this was the first commit, it should have no parents,
  509. # and the amended commit should also have no parents
  510. self.assertEqual(amended_commit.parents, original_commit.parents)
  511. def test_commit_amend_no_message(self) -> None:
  512. # Create initial commit
  513. filename = os.path.join(self.repo.path, "test.txt")
  514. with open(filename, "wb") as f:
  515. f.write(b"initial content")
  516. porcelain.add(self.repo.path, paths=["test.txt"])
  517. original_sha = porcelain.commit(self.repo.path, message=b"Original commit")
  518. # Modify file and stage it
  519. with open(filename, "wb") as f:
  520. f.write(b"modified content")
  521. porcelain.add(self.repo.path, paths=["test.txt"])
  522. # Amend without providing message (should reuse original message)
  523. amended_sha = porcelain.commit(self.repo.path, amend=True)
  524. self.assertIsInstance(amended_sha, bytes)
  525. self.assertEqual(len(amended_sha), 40)
  526. self.assertNotEqual(amended_sha, original_sha)
  527. # Check that the amended commit has the original message
  528. amended_commit = self.repo.get_object(amended_sha)
  529. assert isinstance(amended_commit, Commit)
  530. self.assertEqual(amended_commit.message, b"Original commit")
  531. def test_commit_amend_no_existing_commit(self) -> None:
  532. # Try to amend when there's no existing commit
  533. with self.assertRaises(ValueError) as cm:
  534. porcelain.commit(self.repo.path, message=b"Should fail", amend=True)
  535. self.assertIn("Cannot amend: no existing commit found", str(cm.exception))
  536. @skipIf(
  537. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  538. "gpgme not easily available or supported on Windows and PyPy",
  539. )
  540. class CommitSignTests(PorcelainGpgTestCase):
  541. def test_default_key(self) -> None:
  542. _c1, _c2, c3 = build_commit_graph(
  543. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  544. )
  545. self.repo.refs[b"HEAD"] = c3.id
  546. cfg = self.repo.get_config()
  547. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  548. self.import_default_key()
  549. sha = porcelain.commit(
  550. self.repo.path,
  551. message="Some message",
  552. author="Joe <joe@example.com>",
  553. committer="Bob <bob@example.com>",
  554. sign=True,
  555. )
  556. self.assertIsInstance(sha, bytes)
  557. self.assertEqual(len(sha), 40)
  558. commit = self.repo.get_object(sha)
  559. assert isinstance(commit, Commit)
  560. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  561. commit.verify()
  562. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  563. self.import_non_default_key()
  564. self.assertRaises(
  565. gpg.errors.MissingSignatures,
  566. commit.verify,
  567. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  568. )
  569. assert isinstance(commit, Commit)
  570. commit.committer = b"Alice <alice@example.com>"
  571. self.assertRaises(
  572. gpg.errors.BadSignatures,
  573. commit.verify,
  574. )
  575. def test_non_default_key(self) -> None:
  576. _c1, _c2, c3 = build_commit_graph(
  577. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  578. )
  579. self.repo.refs[b"HEAD"] = c3.id
  580. cfg = self.repo.get_config()
  581. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  582. self.import_non_default_key()
  583. sha = porcelain.commit(
  584. self.repo.path,
  585. message="Some message",
  586. author="Joe <joe@example.com>",
  587. committer="Bob <bob@example.com>",
  588. signoff=PorcelainGpgTestCase.NON_DEFAULT_KEY_ID,
  589. )
  590. self.assertIsInstance(sha, bytes)
  591. self.assertEqual(len(sha), 40)
  592. commit = self.repo.get_object(sha)
  593. assert isinstance(commit, Commit)
  594. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  595. commit.verify()
  596. def test_sign_uses_config_signingkey(self) -> None:
  597. """Test that sign=True uses user.signingKey from config."""
  598. _c1, _c2, c3 = build_commit_graph(
  599. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  600. )
  601. self.repo.refs[b"HEAD"] = c3.id
  602. # Set up user.signingKey in config
  603. cfg = self.repo.get_config()
  604. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  605. cfg.write_to_path()
  606. self.import_default_key()
  607. # Create commit with sign=True (should use signingKey from config)
  608. sha = porcelain.commit(
  609. self.repo.path,
  610. message="Signed with configured key",
  611. author="Joe <joe@example.com>",
  612. committer="Bob <bob@example.com>",
  613. sign=True, # This should read user.signingKey from config
  614. )
  615. self.assertIsInstance(sha, bytes)
  616. self.assertEqual(len(sha), 40)
  617. commit = self.repo.get_object(sha)
  618. assert isinstance(commit, Commit)
  619. # Verify the commit is signed with the configured key
  620. commit.verify()
  621. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  622. def test_commit_gpg_sign_config_enabled(self) -> None:
  623. """Test that commit.gpgSign=true automatically signs commits."""
  624. _c1, _c2, c3 = build_commit_graph(
  625. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  626. )
  627. self.repo.refs[b"HEAD"] = c3.id
  628. # Set up user.signingKey and commit.gpgSign in config
  629. cfg = self.repo.get_config()
  630. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  631. cfg.set(("commit",), "gpgSign", True)
  632. cfg.write_to_path()
  633. self.import_default_key()
  634. # Create commit without explicit signoff parameter (should auto-sign due to config)
  635. sha = porcelain.commit(
  636. self.repo.path,
  637. message="Auto-signed commit",
  638. author="Joe <joe@example.com>",
  639. committer="Bob <bob@example.com>",
  640. # No signoff parameter - should use commit.gpgSign config
  641. )
  642. self.assertIsInstance(sha, bytes)
  643. self.assertEqual(len(sha), 40)
  644. commit = self.repo.get_object(sha)
  645. assert isinstance(commit, Commit)
  646. # Verify the commit is signed due to config
  647. commit.verify()
  648. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  649. def test_commit_gpg_sign_config_disabled(self) -> None:
  650. """Test that commit.gpgSign=false does not sign commits."""
  651. _c1, _c2, c3 = build_commit_graph(
  652. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  653. )
  654. self.repo.refs[b"HEAD"] = c3.id
  655. # Set up user.signingKey and commit.gpgSign=false in config
  656. cfg = self.repo.get_config()
  657. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  658. cfg.set(("commit",), "gpgSign", False)
  659. cfg.write_to_path()
  660. self.import_default_key()
  661. # Create commit without explicit signoff parameter (should not sign)
  662. sha = porcelain.commit(
  663. self.repo.path,
  664. message="Unsigned commit",
  665. author="Joe <joe@example.com>",
  666. committer="Bob <bob@example.com>",
  667. # No signoff parameter - should use commit.gpgSign=false config
  668. )
  669. self.assertIsInstance(sha, bytes)
  670. self.assertEqual(len(sha), 40)
  671. commit = self.repo.get_object(sha)
  672. assert isinstance(commit, Commit)
  673. # Verify the commit is not signed
  674. self.assertIsNone(commit._gpgsig)
  675. def test_commit_gpg_sign_config_no_signing_key(self) -> None:
  676. """Test that commit.gpgSign=true works without user.signingKey (uses default)."""
  677. _c1, _c2, c3 = build_commit_graph(
  678. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  679. )
  680. self.repo.refs[b"HEAD"] = c3.id
  681. # Set up commit.gpgSign but no user.signingKey
  682. cfg = self.repo.get_config()
  683. cfg.set(("commit",), "gpgSign", True)
  684. cfg.write_to_path()
  685. self.import_default_key()
  686. # Create commit without explicit signoff parameter (should auto-sign with default key)
  687. sha = porcelain.commit(
  688. self.repo.path,
  689. message="Default signed commit",
  690. author="Joe <joe@example.com>",
  691. committer="Bob <bob@example.com>",
  692. # No signoff parameter - should use commit.gpgSign config with default key
  693. )
  694. self.assertIsInstance(sha, bytes)
  695. self.assertEqual(len(sha), 40)
  696. commit = self.repo.get_object(sha)
  697. assert isinstance(commit, Commit)
  698. # Verify the commit is signed with default key
  699. commit.verify()
  700. def test_explicit_signoff_overrides_config(self) -> None:
  701. """Test that explicit signoff parameter overrides commit.gpgSign config."""
  702. _c1, _c2, c3 = build_commit_graph(
  703. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  704. )
  705. self.repo.refs[b"HEAD"] = c3.id
  706. # Set up commit.gpgSign=false but explicitly pass sign=True
  707. cfg = self.repo.get_config()
  708. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  709. cfg.set(("commit",), "gpgSign", False)
  710. cfg.write_to_path()
  711. self.import_default_key()
  712. # Create commit with explicit sign=True (should override config)
  713. sha = porcelain.commit(
  714. self.repo.path,
  715. message="Explicitly signed commit",
  716. author="Joe <joe@example.com>",
  717. committer="Bob <bob@example.com>",
  718. sign=True, # This should override commit.gpgSign=false
  719. )
  720. self.assertIsInstance(sha, bytes)
  721. self.assertEqual(len(sha), 40)
  722. commit = self.repo.get_object(sha)
  723. assert isinstance(commit, Commit)
  724. # Verify the commit is signed despite config=false
  725. commit.verify()
  726. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  727. def test_explicit_false_disables_signing(self) -> None:
  728. """Test that explicit signoff=False disables signing even with config=true."""
  729. _c1, _c2, c3 = build_commit_graph(
  730. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  731. )
  732. self.repo.refs[b"HEAD"] = c3.id
  733. # Set up commit.gpgSign=true but explicitly pass sign=False
  734. cfg = self.repo.get_config()
  735. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  736. cfg.set(("commit",), "gpgSign", True)
  737. cfg.write_to_path()
  738. self.import_default_key()
  739. # Create commit with explicit sign=False (should disable signing)
  740. sha = porcelain.commit(
  741. self.repo.path,
  742. message="Explicitly unsigned commit",
  743. author="Joe <joe@example.com>",
  744. committer="Bob <bob@example.com>",
  745. sign=False, # This should override commit.gpgSign=true
  746. )
  747. self.assertIsInstance(sha, bytes)
  748. self.assertEqual(len(sha), 40)
  749. commit = self.repo.get_object(sha)
  750. assert isinstance(commit, Commit)
  751. # Verify the commit is NOT signed despite config=true
  752. self.assertIsNone(commit._gpgsig)
  753. @skipIf(
  754. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  755. "gpgme not easily available or supported on Windows and PyPy",
  756. )
  757. class VerifyCommitTests(PorcelainGpgTestCase):
  758. def test_verify_commit_valid_signature(self) -> None:
  759. """Test verifying a commit with a valid GPG signature."""
  760. _c1, _c2, c3 = build_commit_graph(
  761. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  762. )
  763. self.repo.refs[b"HEAD"] = c3.id
  764. cfg = self.repo.get_config()
  765. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  766. cfg.write_to_path()
  767. self.import_default_key()
  768. # Create a signed commit
  769. sha = porcelain.commit(
  770. self.repo.path,
  771. message="Signed commit",
  772. author="Joe <joe@example.com>",
  773. committer="Bob <bob@example.com>",
  774. sign=True,
  775. )
  776. # Verify should not raise
  777. porcelain.verify_commit(self.repo.path, sha)
  778. porcelain.verify_commit(
  779. self.repo.path, sha, keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID]
  780. )
  781. def test_verify_commit_with_wrong_key(self) -> None:
  782. """Test that verifying with wrong keyid raises MissingSignatures."""
  783. _c1, _c2, c3 = build_commit_graph(
  784. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  785. )
  786. self.repo.refs[b"HEAD"] = c3.id
  787. cfg = self.repo.get_config()
  788. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  789. cfg.write_to_path()
  790. self.import_default_key()
  791. sha = porcelain.commit(
  792. self.repo.path,
  793. message="Signed commit",
  794. author="Joe <joe@example.com>",
  795. committer="Bob <bob@example.com>",
  796. sign=True,
  797. )
  798. self.import_non_default_key()
  799. self.assertRaises(
  800. gpg.errors.MissingSignatures,
  801. porcelain.verify_commit,
  802. self.repo.path,
  803. sha,
  804. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  805. )
  806. def test_verify_commit_unsigned(self) -> None:
  807. """Test that verifying an unsigned commit succeeds (no signature to verify)."""
  808. _c1, _c2, c3 = build_commit_graph(
  809. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  810. )
  811. self.repo.refs[b"HEAD"] = c3.id
  812. sha = porcelain.commit(
  813. self.repo.path,
  814. message="Unsigned commit",
  815. author="Joe <joe@example.com>",
  816. committer="Bob <bob@example.com>",
  817. sign=False,
  818. )
  819. # Verify should not raise for unsigned commits
  820. porcelain.verify_commit(self.repo.path, sha)
  821. @skipIf(
  822. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  823. "gpgme not easily available or supported on Windows and PyPy",
  824. )
  825. class VerifyTagTests(PorcelainGpgTestCase):
  826. def test_verify_tag_valid_signature(self) -> None:
  827. """Test verifying a tag with a valid GPG signature."""
  828. _c1, _c2, c3 = build_commit_graph(
  829. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  830. )
  831. self.repo.refs[b"HEAD"] = c3.id
  832. cfg = self.repo.get_config()
  833. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  834. cfg.write_to_path()
  835. self.import_default_key()
  836. # Create a signed tag
  837. porcelain.tag_create(
  838. self.repo.path,
  839. b"signed-tag",
  840. b"Tagger <tagger@example.com>",
  841. b"Signed tag message",
  842. annotated=True,
  843. sign=True,
  844. )
  845. # Verify should not raise
  846. porcelain.verify_tag(self.repo.path, b"signed-tag")
  847. porcelain.verify_tag(
  848. self.repo.path, b"signed-tag", keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID]
  849. )
  850. def test_verify_tag_with_wrong_key(self) -> None:
  851. """Test that verifying with wrong keyid raises MissingSignatures."""
  852. _c1, _c2, c3 = build_commit_graph(
  853. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  854. )
  855. self.repo.refs[b"HEAD"] = c3.id
  856. cfg = self.repo.get_config()
  857. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  858. cfg.write_to_path()
  859. self.import_default_key()
  860. porcelain.tag_create(
  861. self.repo.path,
  862. b"signed-tag",
  863. b"Tagger <tagger@example.com>",
  864. b"Signed tag message",
  865. annotated=True,
  866. sign=True,
  867. )
  868. self.import_non_default_key()
  869. self.assertRaises(
  870. gpg.errors.MissingSignatures,
  871. porcelain.verify_tag,
  872. self.repo.path,
  873. b"signed-tag",
  874. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  875. )
  876. def test_verify_tag_unsigned(self) -> None:
  877. """Test that verifying an unsigned tag succeeds (no signature to verify)."""
  878. _c1, _c2, c3 = build_commit_graph(
  879. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  880. )
  881. self.repo.refs[b"HEAD"] = c3.id
  882. porcelain.tag_create(
  883. self.repo.path,
  884. b"unsigned-tag",
  885. b"Tagger <tagger@example.com>",
  886. b"Unsigned tag message",
  887. annotated=True,
  888. sign=False,
  889. )
  890. # Verify should not raise for unsigned tags
  891. porcelain.verify_tag(self.repo.path, b"unsigned-tag")
  892. class TimezoneTests(PorcelainTestCase):
  893. def put_envs(self, value) -> None:
  894. self.overrideEnv("GIT_AUTHOR_DATE", value)
  895. self.overrideEnv("GIT_COMMITTER_DATE", value)
  896. def fallback(self, value) -> None:
  897. self.put_envs(value)
  898. self.assertRaises(porcelain.TimezoneFormatError, porcelain.get_user_timezones)
  899. def test_internal_format(self) -> None:
  900. self.put_envs("0 +0500")
  901. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  902. def test_rfc_2822(self) -> None:
  903. self.put_envs("Mon, 20 Nov 1995 19:12:08 -0500")
  904. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  905. self.put_envs("Mon, 20 Nov 1995 19:12:08")
  906. self.assertTupleEqual((0, 0), porcelain.get_user_timezones())
  907. def test_iso8601(self) -> None:
  908. self.put_envs("1995-11-20T19:12:08-0501")
  909. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  910. self.put_envs("1995-11-20T19:12:08+0501")
  911. self.assertTupleEqual((18060, 18060), porcelain.get_user_timezones())
  912. self.put_envs("1995-11-20T19:12:08-05:01")
  913. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  914. self.put_envs("1995-11-20 19:12:08-05")
  915. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  916. # https://github.com/git/git/blob/96b2d4fa927c5055adc5b1d08f10a5d7352e2989/t/t6300-for-each-ref.sh#L128
  917. self.put_envs("2006-07-03 17:18:44 +0200")
  918. self.assertTupleEqual((7200, 7200), porcelain.get_user_timezones())
  919. def test_missing_or_malformed(self) -> None:
  920. # TODO: add more here
  921. self.fallback("0 + 0500")
  922. self.fallback("a +0500")
  923. self.fallback("1995-11-20T19:12:08")
  924. self.fallback("1995-11-20T19:12:08-05:")
  925. self.fallback("1995.11.20")
  926. self.fallback("11/20/1995")
  927. self.fallback("20.11.1995")
  928. def test_different_envs(self) -> None:
  929. self.overrideEnv("GIT_AUTHOR_DATE", "0 +0500")
  930. self.overrideEnv("GIT_COMMITTER_DATE", "0 +0501")
  931. self.assertTupleEqual((18000, 18060), porcelain.get_user_timezones())
  932. def test_no_envs(self) -> None:
  933. local_timezone = time.localtime().tm_gmtoff
  934. self.put_envs("0 +0500")
  935. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  936. self.overrideEnv("GIT_COMMITTER_DATE", None)
  937. self.assertTupleEqual((18000, local_timezone), porcelain.get_user_timezones())
  938. self.put_envs("0 +0500")
  939. self.overrideEnv("GIT_AUTHOR_DATE", None)
  940. self.assertTupleEqual((local_timezone, 18000), porcelain.get_user_timezones())
  941. self.put_envs("0 +0500")
  942. self.overrideEnv("GIT_AUTHOR_DATE", None)
  943. self.overrideEnv("GIT_COMMITTER_DATE", None)
  944. self.assertTupleEqual(
  945. (local_timezone, local_timezone), porcelain.get_user_timezones()
  946. )
  947. class CleanTests(PorcelainTestCase):
  948. def put_files(self, tracked, ignored, untracked, empty_dirs) -> None:
  949. """Put the described files in the wd."""
  950. all_files = tracked | ignored | untracked
  951. for file_path in all_files:
  952. abs_path = os.path.join(self.repo.path, file_path)
  953. # File may need to be written in a dir that doesn't exist yet, so
  954. # create the parent dir(s) as necessary
  955. parent_dir = os.path.dirname(abs_path)
  956. try:
  957. os.makedirs(parent_dir)
  958. except FileExistsError:
  959. pass
  960. with open(abs_path, "w") as f:
  961. f.write("")
  962. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  963. f.writelines(ignored)
  964. for dir_path in empty_dirs:
  965. os.mkdir(os.path.join(self.repo.path, "empty_dir"))
  966. files_to_add = [os.path.join(self.repo.path, t) for t in tracked]
  967. porcelain.add(repo=self.repo.path, paths=files_to_add)
  968. porcelain.commit(repo=self.repo.path, message="init commit")
  969. def assert_wd(self, expected_paths) -> None:
  970. """Assert paths of files and dirs in wd are same as expected_paths."""
  971. control_dir_rel = os.path.relpath(self.repo._controldir, self.repo.path)
  972. # normalize paths to simplify comparison across platforms
  973. found_paths = {
  974. os.path.normpath(p)
  975. for p in flat_walk_dir(self.repo.path)
  976. if not p.split(os.sep)[0] == control_dir_rel
  977. }
  978. norm_expected_paths = {os.path.normpath(p) for p in expected_paths}
  979. self.assertEqual(found_paths, norm_expected_paths)
  980. def test_from_root(self) -> None:
  981. self.put_files(
  982. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  983. ignored={"ignored_file"},
  984. untracked={
  985. "untracked_file",
  986. "tracked_dir/untracked_dir/untracked_file",
  987. "untracked_dir/untracked_dir/untracked_file",
  988. },
  989. empty_dirs={"empty_dir"},
  990. )
  991. porcelain.clean(repo=self.repo.path, target_dir=self.repo.path)
  992. self.assert_wd(
  993. {
  994. "tracked_file",
  995. "tracked_dir/tracked_file",
  996. ".gitignore",
  997. "ignored_file",
  998. "tracked_dir",
  999. }
  1000. )
  1001. def test_from_subdir(self) -> None:
  1002. self.put_files(
  1003. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  1004. ignored={"ignored_file"},
  1005. untracked={
  1006. "untracked_file",
  1007. "tracked_dir/untracked_dir/untracked_file",
  1008. "untracked_dir/untracked_dir/untracked_file",
  1009. },
  1010. empty_dirs={"empty_dir"},
  1011. )
  1012. porcelain.clean(
  1013. repo=self.repo,
  1014. target_dir=os.path.join(self.repo.path, "untracked_dir"),
  1015. )
  1016. self.assert_wd(
  1017. {
  1018. "tracked_file",
  1019. "tracked_dir/tracked_file",
  1020. ".gitignore",
  1021. "ignored_file",
  1022. "untracked_file",
  1023. "tracked_dir/untracked_dir/untracked_file",
  1024. "empty_dir",
  1025. "untracked_dir",
  1026. "tracked_dir",
  1027. "tracked_dir/untracked_dir",
  1028. }
  1029. )
  1030. class CloneTests(PorcelainTestCase):
  1031. def test_simple_local(self) -> None:
  1032. f1_1 = make_object(Blob, data=b"f1")
  1033. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1034. trees = {
  1035. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1036. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1037. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1038. }
  1039. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1040. self.repo.refs[b"refs/heads/master"] = c3.id
  1041. self.repo.refs[b"refs/tags/foo"] = c3.id
  1042. target_path = tempfile.mkdtemp()
  1043. errstream = BytesIO()
  1044. self.addCleanup(shutil.rmtree, target_path)
  1045. r = porcelain.clone(
  1046. self.repo.path, target_path, checkout=False, errstream=errstream
  1047. )
  1048. self.addCleanup(r.close)
  1049. self.assertEqual(r.path, target_path)
  1050. target_repo = Repo(target_path)
  1051. self.addCleanup(target_repo.close)
  1052. self.assertEqual(0, len(target_repo.open_index()))
  1053. self.assertEqual(c3.id, target_repo.refs[b"refs/tags/foo"])
  1054. self.assertNotIn(b"f1", os.listdir(target_path))
  1055. self.assertNotIn(b"f2", os.listdir(target_path))
  1056. c = r.get_config()
  1057. encoded_path = self.repo.path
  1058. if not isinstance(encoded_path, bytes):
  1059. encoded_path_bytes = encoded_path.encode("utf-8")
  1060. else:
  1061. encoded_path_bytes = encoded_path
  1062. self.assertEqual(encoded_path_bytes, c.get((b"remote", b"origin"), b"url"))
  1063. self.assertEqual(
  1064. b"+refs/heads/*:refs/remotes/origin/*",
  1065. c.get((b"remote", b"origin"), b"fetch"),
  1066. )
  1067. def test_simple_local_with_checkout(self) -> None:
  1068. f1_1 = make_object(Blob, data=b"f1")
  1069. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1070. trees = {
  1071. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1072. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1073. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1074. }
  1075. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1076. self.repo.refs[b"refs/heads/master"] = c3.id
  1077. target_path = tempfile.mkdtemp()
  1078. errstream = BytesIO()
  1079. self.addCleanup(shutil.rmtree, target_path)
  1080. with porcelain.clone(
  1081. self.repo.path, target_path, checkout=True, errstream=errstream
  1082. ) as r:
  1083. self.assertEqual(r.path, target_path)
  1084. with Repo(target_path) as r:
  1085. self.assertEqual(r.head(), c3.id)
  1086. self.assertIn("f1", os.listdir(target_path))
  1087. self.assertIn("f2", os.listdir(target_path))
  1088. def test_bare_local_with_checkout(self) -> None:
  1089. f1_1 = make_object(Blob, data=b"f1")
  1090. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1091. trees = {
  1092. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1093. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1094. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1095. }
  1096. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1097. self.repo.refs[b"refs/heads/master"] = c3.id
  1098. target_path = tempfile.mkdtemp()
  1099. errstream = BytesIO()
  1100. self.addCleanup(shutil.rmtree, target_path)
  1101. with porcelain.clone(
  1102. self.repo.path, target_path, bare=True, errstream=errstream
  1103. ) as r:
  1104. self.assertEqual(r.path, target_path)
  1105. with Repo(target_path) as r:
  1106. r.head()
  1107. self.assertRaises(NoIndexPresent, r.open_index)
  1108. self.assertNotIn(b"f1", os.listdir(target_path))
  1109. self.assertNotIn(b"f2", os.listdir(target_path))
  1110. def test_no_checkout_with_bare(self) -> None:
  1111. f1_1 = make_object(Blob, data=b"f1")
  1112. commit_spec = [[1]]
  1113. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1114. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1115. self.repo.refs[b"refs/heads/master"] = c1.id
  1116. self.repo.refs[b"HEAD"] = c1.id
  1117. target_path = tempfile.mkdtemp()
  1118. errstream = BytesIO()
  1119. self.addCleanup(shutil.rmtree, target_path)
  1120. self.assertRaises(
  1121. porcelain.Error,
  1122. porcelain.clone,
  1123. self.repo.path,
  1124. target_path,
  1125. checkout=True,
  1126. bare=True,
  1127. errstream=errstream,
  1128. )
  1129. def test_no_head_no_checkout(self) -> None:
  1130. f1_1 = make_object(Blob, data=b"f1")
  1131. commit_spec = [[1]]
  1132. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1133. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1134. self.repo.refs[b"refs/heads/master"] = c1.id
  1135. target_path = tempfile.mkdtemp()
  1136. self.addCleanup(shutil.rmtree, target_path)
  1137. errstream = BytesIO()
  1138. r = porcelain.clone(
  1139. self.repo.path, target_path, checkout=True, errstream=errstream
  1140. )
  1141. r.close()
  1142. def test_no_head_no_checkout_outstream_errstream_autofallback(self) -> None:
  1143. f1_1 = make_object(Blob, data=b"f1")
  1144. commit_spec = [[1]]
  1145. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1146. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1147. self.repo.refs[b"refs/heads/master"] = c1.id
  1148. target_path = tempfile.mkdtemp()
  1149. self.addCleanup(shutil.rmtree, target_path)
  1150. errstream = porcelain.NoneStream()
  1151. r = porcelain.clone(
  1152. self.repo.path, target_path, checkout=True, errstream=errstream
  1153. )
  1154. r.close()
  1155. def test_source_broken(self) -> None:
  1156. with tempfile.TemporaryDirectory() as parent:
  1157. target_path = os.path.join(parent, "target")
  1158. self.assertRaises(
  1159. Exception, porcelain.clone, "/nonexistent/repo", target_path
  1160. )
  1161. self.assertFalse(os.path.exists(target_path))
  1162. def test_fetch_symref(self) -> None:
  1163. f1_1 = make_object(Blob, data=b"f1")
  1164. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1165. [c1] = build_commit_graph(self.repo.object_store, [[1]], trees)
  1166. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/else")
  1167. self.repo.refs[b"refs/heads/else"] = c1.id
  1168. target_path = tempfile.mkdtemp()
  1169. errstream = BytesIO()
  1170. self.addCleanup(shutil.rmtree, target_path)
  1171. r = porcelain.clone(
  1172. self.repo.path, target_path, checkout=False, errstream=errstream
  1173. )
  1174. self.addCleanup(r.close)
  1175. self.assertEqual(r.path, target_path)
  1176. target_repo = Repo(target_path)
  1177. self.addCleanup(target_repo.close)
  1178. self.assertEqual(0, len(target_repo.open_index()))
  1179. self.assertEqual(c1.id, target_repo.refs[b"refs/heads/else"])
  1180. self.assertEqual(c1.id, target_repo.refs[b"HEAD"])
  1181. self.assertEqual(
  1182. {
  1183. b"HEAD": b"refs/heads/else",
  1184. b"refs/remotes/origin/HEAD": b"refs/remotes/origin/else",
  1185. },
  1186. target_repo.refs.get_symrefs(),
  1187. )
  1188. def test_detached_head(self) -> None:
  1189. f1_1 = make_object(Blob, data=b"f1")
  1190. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1191. trees = {
  1192. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1193. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1194. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1195. }
  1196. _c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1197. self.repo.refs[b"refs/heads/master"] = c2.id
  1198. self.repo.refs.remove_if_equals(b"HEAD", None)
  1199. self.repo.refs[b"HEAD"] = c3.id
  1200. target_path = tempfile.mkdtemp()
  1201. self.addCleanup(shutil.rmtree, target_path)
  1202. errstream = porcelain.NoneStream()
  1203. with porcelain.clone(
  1204. self.repo.path, target_path, checkout=True, errstream=errstream
  1205. ) as r:
  1206. self.assertEqual(c3.id, r.refs[b"HEAD"])
  1207. def test_clone_pathlib(self) -> None:
  1208. from pathlib import Path
  1209. f1_1 = make_object(Blob, data=b"f1")
  1210. commit_spec = [[1]]
  1211. trees = {1: [(b"f1", f1_1)]}
  1212. c1 = build_commit_graph(self.repo.object_store, commit_spec, trees)[0]
  1213. self.repo.refs[b"refs/heads/master"] = c1.id
  1214. target_dir = tempfile.mkdtemp()
  1215. self.addCleanup(shutil.rmtree, target_dir)
  1216. target_path = Path(target_dir) / "clone_repo"
  1217. errstream = BytesIO()
  1218. r = porcelain.clone(
  1219. self.repo.path, target_path, checkout=False, errstream=errstream
  1220. )
  1221. self.addCleanup(r.close)
  1222. self.assertEqual(r.path, str(target_path))
  1223. self.assertTrue(os.path.exists(str(target_path)))
  1224. def test_clone_with_recurse_submodules(self) -> None:
  1225. # Create a submodule repository
  1226. sub_repo_path = tempfile.mkdtemp()
  1227. self.addCleanup(shutil.rmtree, sub_repo_path)
  1228. sub_repo = Repo.init(sub_repo_path)
  1229. self.addCleanup(sub_repo.close)
  1230. # Add a file to the submodule repo
  1231. sub_file = os.path.join(sub_repo_path, "subfile.txt")
  1232. with open(sub_file, "w") as f:
  1233. f.write("submodule content")
  1234. porcelain.add(sub_repo, paths=[sub_file])
  1235. sub_commit = porcelain.commit(
  1236. sub_repo,
  1237. message=b"Initial submodule commit",
  1238. author=b"Test Author <test@example.com>",
  1239. committer=b"Test Committer <test@example.com>",
  1240. )
  1241. # Create main repository with submodule
  1242. main_file = os.path.join(self.repo.path, "main.txt")
  1243. with open(main_file, "w") as f:
  1244. f.write("main content")
  1245. porcelain.add(self.repo, paths=[main_file])
  1246. porcelain.submodule_add(self.repo, sub_repo_path, "sub")
  1247. # Manually add the submodule to the index since submodule_add doesn't do it
  1248. # when the repository is local (to maintain backward compatibility)
  1249. from dulwich.index import IndexEntry
  1250. from dulwich.objects import S_IFGITLINK
  1251. index = self.repo.open_index()
  1252. index[b"sub"] = IndexEntry(
  1253. ctime=0,
  1254. mtime=0,
  1255. dev=0,
  1256. ino=0,
  1257. mode=S_IFGITLINK,
  1258. uid=0,
  1259. gid=0,
  1260. size=0,
  1261. sha=sub_commit,
  1262. flags=0,
  1263. )
  1264. index.write()
  1265. porcelain.add(self.repo, paths=[".gitmodules"])
  1266. porcelain.commit(
  1267. self.repo,
  1268. message=b"Add submodule",
  1269. author=b"Test Author <test@example.com>",
  1270. committer=b"Test Committer <test@example.com>",
  1271. )
  1272. # Clone with recurse_submodules
  1273. target_path = tempfile.mkdtemp()
  1274. self.addCleanup(shutil.rmtree, target_path)
  1275. cloned = porcelain.clone(
  1276. self.repo.path,
  1277. target_path,
  1278. recurse_submodules=True,
  1279. )
  1280. self.addCleanup(cloned.close)
  1281. # Check main file exists
  1282. cloned_main = os.path.join(target_path, "main.txt")
  1283. self.assertTrue(os.path.exists(cloned_main))
  1284. with open(cloned_main) as f:
  1285. self.assertEqual(f.read(), "main content")
  1286. # Check submodule file exists
  1287. cloned_sub_file = os.path.join(target_path, "sub", "subfile.txt")
  1288. self.assertTrue(os.path.exists(cloned_sub_file))
  1289. with open(cloned_sub_file) as f:
  1290. self.assertEqual(f.read(), "submodule content")
  1291. class InitTests(TestCase):
  1292. def test_non_bare(self) -> None:
  1293. repo_dir = tempfile.mkdtemp()
  1294. self.addCleanup(shutil.rmtree, repo_dir)
  1295. porcelain.init(repo_dir)
  1296. def test_bare(self) -> None:
  1297. repo_dir = tempfile.mkdtemp()
  1298. self.addCleanup(shutil.rmtree, repo_dir)
  1299. porcelain.init(repo_dir, bare=True)
  1300. def test_init_pathlib(self) -> None:
  1301. from pathlib import Path
  1302. repo_dir = tempfile.mkdtemp()
  1303. self.addCleanup(shutil.rmtree, repo_dir)
  1304. repo_path = Path(repo_dir)
  1305. # Test non-bare repo with pathlib
  1306. repo = porcelain.init(repo_path)
  1307. self.assertTrue(os.path.exists(os.path.join(repo_dir, ".git")))
  1308. repo.close()
  1309. def test_init_bare_pathlib(self) -> None:
  1310. from pathlib import Path
  1311. repo_dir = tempfile.mkdtemp()
  1312. self.addCleanup(shutil.rmtree, repo_dir)
  1313. repo_path = Path(repo_dir)
  1314. # Test bare repo with pathlib
  1315. repo = porcelain.init(repo_path, bare=True)
  1316. self.assertTrue(os.path.exists(os.path.join(repo_dir, "refs")))
  1317. repo.close()
  1318. class AddTests(PorcelainTestCase):
  1319. def test_add_default_paths(self) -> None:
  1320. # create a file for initial commit
  1321. fullpath = os.path.join(self.repo.path, "blah")
  1322. with open(fullpath, "w") as f:
  1323. f.write("\n")
  1324. porcelain.add(repo=self.repo.path, paths=[fullpath])
  1325. porcelain.commit(
  1326. repo=self.repo.path,
  1327. message=b"test",
  1328. author=b"test <email>",
  1329. committer=b"test <email>",
  1330. )
  1331. # Add a second test file and a file in a directory
  1332. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1333. f.write("\n")
  1334. os.mkdir(os.path.join(self.repo.path, "adir"))
  1335. with open(os.path.join(self.repo.path, "adir", "afile"), "w") as f:
  1336. f.write("\n")
  1337. cwd = os.getcwd()
  1338. self.addCleanup(os.chdir, cwd)
  1339. os.chdir(self.repo.path)
  1340. self.assertEqual({"foo", "blah", "adir", ".git"}, set(os.listdir(".")))
  1341. added, ignored = porcelain.add(self.repo.path)
  1342. # Normalize paths to use forward slashes for comparison
  1343. added_normalized = [path.replace(os.sep, "/") for path in added]
  1344. self.assertEqual(
  1345. (added_normalized, ignored),
  1346. (["foo", "adir/afile"], set()),
  1347. )
  1348. # Check that foo was added and nothing in .git was modified
  1349. index = self.repo.open_index()
  1350. self.assertEqual(sorted(index), [b"adir/afile", b"blah", b"foo"])
  1351. def test_add_default_paths_subdir(self) -> None:
  1352. os.mkdir(os.path.join(self.repo.path, "foo"))
  1353. with open(os.path.join(self.repo.path, "blah"), "w") as f:
  1354. f.write("\n")
  1355. with open(os.path.join(self.repo.path, "foo", "blie"), "w") as f:
  1356. f.write("\n")
  1357. cwd = os.getcwd()
  1358. self.addCleanup(os.chdir, cwd)
  1359. os.chdir(os.path.join(self.repo.path, "foo"))
  1360. porcelain.add(repo=self.repo.path)
  1361. porcelain.commit(
  1362. repo=self.repo.path,
  1363. message=b"test",
  1364. author=b"test <email>",
  1365. committer=b"test <email>",
  1366. )
  1367. index = self.repo.open_index()
  1368. # After fix: add() with no paths should behave like git add -A (add everything)
  1369. self.assertEqual(sorted(index), [b"blah", b"foo/blie"])
  1370. def test_add_file(self) -> None:
  1371. fullpath = os.path.join(self.repo.path, "foo")
  1372. with open(fullpath, "w") as f:
  1373. f.write("BAR")
  1374. porcelain.add(self.repo.path, paths=[fullpath])
  1375. self.assertIn(b"foo", self.repo.open_index())
  1376. def test_add_ignored(self) -> None:
  1377. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1378. f.write("foo\nsubdir/")
  1379. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1380. f.write("BAR")
  1381. with open(os.path.join(self.repo.path, "bar"), "w") as f:
  1382. f.write("BAR")
  1383. os.mkdir(os.path.join(self.repo.path, "subdir"))
  1384. with open(os.path.join(self.repo.path, "subdir", "baz"), "w") as f:
  1385. f.write("BAZ")
  1386. (added, ignored) = porcelain.add(
  1387. self.repo.path,
  1388. paths=[
  1389. os.path.join(self.repo.path, "foo"),
  1390. os.path.join(self.repo.path, "bar"),
  1391. os.path.join(self.repo.path, "subdir"),
  1392. ],
  1393. )
  1394. self.assertIn(b"bar", self.repo.open_index())
  1395. self.assertEqual({"bar"}, set(added))
  1396. self.assertEqual({"foo", "subdir/"}, ignored)
  1397. def test_add_from_ignored_directory(self) -> None:
  1398. # Test for issue #550 - adding files when cwd is in ignored directory
  1399. # Create .gitignore that ignores build/
  1400. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1401. f.write("build/\n")
  1402. # Create ignored directory
  1403. build_dir = os.path.join(self.repo.path, "build")
  1404. os.mkdir(build_dir)
  1405. # Create a file in the repo (not in ignored directory)
  1406. src_file = os.path.join(self.repo.path, "source.py")
  1407. with open(src_file, "w") as f:
  1408. f.write("print('hello')\n")
  1409. # Save current directory and change to ignored directory
  1410. original_cwd = os.getcwd()
  1411. try:
  1412. os.chdir(build_dir)
  1413. # Add file using absolute path from within ignored directory
  1414. (added, _ignored) = porcelain.add(self.repo.path, paths=[src_file])
  1415. self.assertIn(b"source.py", self.repo.open_index())
  1416. self.assertEqual({"source.py"}, set(added))
  1417. finally:
  1418. os.chdir(original_cwd)
  1419. def test_add_file_absolute_path(self) -> None:
  1420. # Absolute paths are (not yet) supported
  1421. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1422. f.write("BAR")
  1423. porcelain.add(self.repo, paths=[os.path.join(self.repo.path, "foo")])
  1424. self.assertIn(b"foo", self.repo.open_index())
  1425. def test_add_not_in_repo(self) -> None:
  1426. with open(os.path.join(self.test_dir, "foo"), "w") as f:
  1427. f.write("BAR")
  1428. self.assertRaises(
  1429. ValueError,
  1430. porcelain.add,
  1431. self.repo,
  1432. paths=[os.path.join(self.test_dir, "foo")],
  1433. )
  1434. self.assertRaises(
  1435. (ValueError, FileNotFoundError),
  1436. porcelain.add,
  1437. self.repo,
  1438. paths=["../foo"],
  1439. )
  1440. self.assertEqual([], list(self.repo.open_index()))
  1441. def test_add_file_clrf_conversion(self) -> None:
  1442. from dulwich.index import IndexEntry
  1443. # Set the right configuration to the repo
  1444. c = self.repo.get_config()
  1445. c.set("core", "autocrlf", "input")
  1446. c.write_to_path()
  1447. # Add a file with CRLF line-ending
  1448. fullpath = os.path.join(self.repo.path, "foo")
  1449. with open(fullpath, "wb") as f:
  1450. f.write(b"line1\r\nline2")
  1451. porcelain.add(self.repo.path, paths=[fullpath])
  1452. # The line-endings should have been converted to LF
  1453. index = self.repo.open_index()
  1454. self.assertIn(b"foo", index)
  1455. entry = index[b"foo"]
  1456. assert isinstance(entry, IndexEntry)
  1457. blob = self.repo[entry.sha]
  1458. self.assertEqual(blob.data, b"line1\nline2")
  1459. def test_add_symlink_outside_repo(self) -> None:
  1460. """Test adding a symlink that points outside the repository."""
  1461. # Create a symlink pointing outside the repository
  1462. symlink_path = os.path.join(self.repo.path, "symlink_to_nowhere")
  1463. os.symlink("/nonexistent/path", symlink_path)
  1464. # Adding the symlink should succeed (matching Git's behavior)
  1465. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1466. # Should successfully add the symlink
  1467. self.assertIn("symlink_to_nowhere", added)
  1468. self.assertEqual(len(ignored), 0)
  1469. # Verify symlink is actually staged
  1470. index = self.repo.open_index()
  1471. self.assertIn(b"symlink_to_nowhere", index)
  1472. def test_add_symlink_to_file_inside_repo(self) -> None:
  1473. """Test adding a symlink that points to a file inside the repository."""
  1474. # Create a regular file
  1475. target_file = os.path.join(self.repo.path, "target.txt")
  1476. with open(target_file, "w") as f:
  1477. f.write("target content")
  1478. # Create a symlink to the file
  1479. symlink_path = os.path.join(self.repo.path, "link_to_target")
  1480. os.symlink("target.txt", symlink_path)
  1481. # Add both the target and the symlink
  1482. added, ignored = porcelain.add(
  1483. self.repo.path, paths=[target_file, symlink_path]
  1484. )
  1485. # Both should be added successfully
  1486. self.assertIn("target.txt", added)
  1487. self.assertIn("link_to_target", added)
  1488. self.assertEqual(len(ignored), 0)
  1489. # Verify both are in the index
  1490. index = self.repo.open_index()
  1491. self.assertIn(b"target.txt", index)
  1492. self.assertIn(b"link_to_target", index)
  1493. def test_add_symlink_to_directory_inside_repo(self) -> None:
  1494. """Test adding a symlink that points to a directory inside the repository."""
  1495. # Create a directory with some files
  1496. target_dir = os.path.join(self.repo.path, "target_dir")
  1497. os.mkdir(target_dir)
  1498. with open(os.path.join(target_dir, "file1.txt"), "w") as f:
  1499. f.write("content1")
  1500. with open(os.path.join(target_dir, "file2.txt"), "w") as f:
  1501. f.write("content2")
  1502. # Create a symlink to the directory
  1503. symlink_path = os.path.join(self.repo.path, "link_to_dir")
  1504. os.symlink("target_dir", symlink_path)
  1505. # Add the symlink
  1506. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1507. # When adding a symlink to a directory, it follows the symlink and adds contents
  1508. self.assertEqual(len(added), 2)
  1509. self.assertIn("link_to_dir/file1.txt", added)
  1510. self.assertIn("link_to_dir/file2.txt", added)
  1511. self.assertEqual(len(ignored), 0)
  1512. # Verify files are added through the symlink path
  1513. index = self.repo.open_index()
  1514. self.assertIn(b"link_to_dir/file1.txt", index)
  1515. self.assertIn(b"link_to_dir/file2.txt", index)
  1516. # The original target directory files are not added
  1517. self.assertNotIn(b"target_dir/file1.txt", index)
  1518. self.assertNotIn(b"target_dir/file2.txt", index)
  1519. def test_add_symlink_chain(self) -> None:
  1520. """Test adding a chain of symlinks (symlink to symlink)."""
  1521. # Create a regular file
  1522. target_file = os.path.join(self.repo.path, "original.txt")
  1523. with open(target_file, "w") as f:
  1524. f.write("original content")
  1525. # Create first symlink
  1526. first_link = os.path.join(self.repo.path, "link1")
  1527. os.symlink("original.txt", first_link)
  1528. # Create second symlink pointing to first
  1529. second_link = os.path.join(self.repo.path, "link2")
  1530. os.symlink("link1", second_link)
  1531. # Add all files
  1532. added, _ignored = porcelain.add(
  1533. self.repo.path, paths=[target_file, first_link, second_link]
  1534. )
  1535. # All should be added
  1536. self.assertEqual(len(added), 3)
  1537. self.assertIn("original.txt", added)
  1538. self.assertIn("link1", added)
  1539. self.assertIn("link2", added)
  1540. # Verify all are in the index
  1541. index = self.repo.open_index()
  1542. self.assertIn(b"original.txt", index)
  1543. self.assertIn(b"link1", index)
  1544. self.assertIn(b"link2", index)
  1545. def test_add_broken_symlink(self) -> None:
  1546. """Test adding a broken symlink (points to non-existent target)."""
  1547. # Create a symlink to a non-existent file
  1548. broken_link = os.path.join(self.repo.path, "broken_link")
  1549. os.symlink("does_not_exist.txt", broken_link)
  1550. # Add the broken symlink
  1551. added, ignored = porcelain.add(self.repo.path, paths=[broken_link])
  1552. # Should be added successfully (Git tracks the symlink, not its target)
  1553. self.assertIn("broken_link", added)
  1554. self.assertEqual(len(ignored), 0)
  1555. # Verify it's in the index
  1556. index = self.repo.open_index()
  1557. self.assertIn(b"broken_link", index)
  1558. def test_add_symlink_relative_outside_repo(self) -> None:
  1559. """Test adding a symlink that uses '..' to point outside the repository."""
  1560. # Create a file outside the repo
  1561. outside_file = os.path.join(self.test_dir, "outside.txt")
  1562. with open(outside_file, "w") as f:
  1563. f.write("outside content")
  1564. # Create a symlink using relative path to go outside
  1565. symlink_path = os.path.join(self.repo.path, "link_outside")
  1566. os.symlink("../outside.txt", symlink_path)
  1567. # Add the symlink
  1568. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1569. # Should be added successfully
  1570. self.assertIn("link_outside", added)
  1571. self.assertEqual(len(ignored), 0)
  1572. # Verify it's in the index
  1573. index = self.repo.open_index()
  1574. self.assertIn(b"link_outside", index)
  1575. def test_add_symlink_absolute_to_system(self) -> None:
  1576. """Test adding a symlink with absolute path to system directory."""
  1577. # Create a symlink to a system directory
  1578. symlink_path = os.path.join(self.repo.path, "link_to_tmp")
  1579. if os.name == "nt":
  1580. # On Windows, use a system directory like TEMP
  1581. symlink_target = os.environ["TEMP"]
  1582. else:
  1583. # On Unix-like systems, use /tmp
  1584. symlink_target = os.environ.get("TMPDIR", "/tmp")
  1585. os.symlink(symlink_target, symlink_path)
  1586. # Adding a symlink to a directory outside the repo should raise ValueError
  1587. with self.assertRaises(ValueError) as cm:
  1588. porcelain.add(self.repo.path, paths=[symlink_path])
  1589. # Check that the error indicates the path is outside the repository
  1590. self.assertIn("is not in the subpath of", str(cm.exception))
  1591. def test_add_file_through_symlink(self) -> None:
  1592. """Test adding a file through a symlinked directory."""
  1593. # Create a directory with a file
  1594. real_dir = os.path.join(self.repo.path, "real_dir")
  1595. os.mkdir(real_dir)
  1596. real_file = os.path.join(real_dir, "file.txt")
  1597. with open(real_file, "w") as f:
  1598. f.write("content")
  1599. # Create a symlink to the directory
  1600. link_dir = os.path.join(self.repo.path, "link_dir")
  1601. os.symlink("real_dir", link_dir)
  1602. # Try to add the file through the symlink path
  1603. symlink_file_path = os.path.join(link_dir, "file.txt")
  1604. # This should add the real file, not create a new entry
  1605. added, _ignored = porcelain.add(self.repo.path, paths=[symlink_file_path])
  1606. # The real file should be added
  1607. self.assertIn("real_dir/file.txt", added)
  1608. self.assertEqual(len(added), 1)
  1609. # Verify correct path in index
  1610. index = self.repo.open_index()
  1611. self.assertIn(b"real_dir/file.txt", index)
  1612. # Should not create a separate entry for the symlink path
  1613. self.assertNotIn(b"link_dir/file.txt", index)
  1614. def test_add_repo_path(self) -> None:
  1615. """Test adding the repository path itself should add all untracked files."""
  1616. # Create some untracked files
  1617. with open(os.path.join(self.repo.path, "file1.txt"), "w") as f:
  1618. f.write("content1")
  1619. with open(os.path.join(self.repo.path, "file2.txt"), "w") as f:
  1620. f.write("content2")
  1621. # Add the repository path itself
  1622. added, _ignored = porcelain.add(self.repo.path, paths=[self.repo.path])
  1623. # Should add all untracked files, not stage './'
  1624. self.assertIn("file1.txt", added)
  1625. self.assertIn("file2.txt", added)
  1626. self.assertNotIn("./", added)
  1627. # Verify files are actually staged
  1628. index = self.repo.open_index()
  1629. self.assertIn(b"file1.txt", index)
  1630. self.assertIn(b"file2.txt", index)
  1631. def test_add_directory_contents(self) -> None:
  1632. """Test adding a directory adds all files within it."""
  1633. # Create a subdirectory with multiple files
  1634. subdir = os.path.join(self.repo.path, "subdir")
  1635. os.mkdir(subdir)
  1636. with open(os.path.join(subdir, "file1.txt"), "w") as f:
  1637. f.write("content1")
  1638. with open(os.path.join(subdir, "file2.txt"), "w") as f:
  1639. f.write("content2")
  1640. with open(os.path.join(subdir, "file3.txt"), "w") as f:
  1641. f.write("content3")
  1642. # Add the directory
  1643. added, _ignored = porcelain.add(self.repo.path, paths=["subdir"])
  1644. # Should add all files in the directory
  1645. self.assertEqual(len(added), 3)
  1646. # Normalize paths to use forward slashes for comparison
  1647. added_normalized = [path.replace(os.sep, "/") for path in added]
  1648. self.assertIn("subdir/file1.txt", added_normalized)
  1649. self.assertIn("subdir/file2.txt", added_normalized)
  1650. self.assertIn("subdir/file3.txt", added_normalized)
  1651. # Verify files are actually staged
  1652. index = self.repo.open_index()
  1653. self.assertIn(b"subdir/file1.txt", index)
  1654. self.assertIn(b"subdir/file2.txt", index)
  1655. self.assertIn(b"subdir/file3.txt", index)
  1656. def test_add_nested_directories(self) -> None:
  1657. """Test adding a directory with nested subdirectories."""
  1658. # Create nested directory structure
  1659. dir1 = os.path.join(self.repo.path, "dir1")
  1660. dir2 = os.path.join(dir1, "dir2")
  1661. dir3 = os.path.join(dir2, "dir3")
  1662. os.makedirs(dir3)
  1663. # Add files at each level
  1664. with open(os.path.join(dir1, "file1.txt"), "w") as f:
  1665. f.write("level1")
  1666. with open(os.path.join(dir2, "file2.txt"), "w") as f:
  1667. f.write("level2")
  1668. with open(os.path.join(dir3, "file3.txt"), "w") as f:
  1669. f.write("level3")
  1670. # Add the top-level directory
  1671. added, _ignored = porcelain.add(self.repo.path, paths=["dir1"])
  1672. # Should add all files recursively
  1673. self.assertEqual(len(added), 3)
  1674. # Normalize paths to use forward slashes for comparison
  1675. added_normalized = [path.replace(os.sep, "/") for path in added]
  1676. self.assertIn("dir1/file1.txt", added_normalized)
  1677. self.assertIn("dir1/dir2/file2.txt", added_normalized)
  1678. self.assertIn("dir1/dir2/dir3/file3.txt", added_normalized)
  1679. # Verify files are actually staged
  1680. index = self.repo.open_index()
  1681. self.assertIn(b"dir1/file1.txt", index)
  1682. self.assertIn(b"dir1/dir2/file2.txt", index)
  1683. self.assertIn(b"dir1/dir2/dir3/file3.txt", index)
  1684. def test_add_directory_with_tracked_files(self) -> None:
  1685. """Test adding a directory with some files already tracked."""
  1686. # Create a subdirectory with files
  1687. subdir = os.path.join(self.repo.path, "mixed")
  1688. os.mkdir(subdir)
  1689. # Create and commit one file
  1690. tracked_file = os.path.join(subdir, "tracked.txt")
  1691. with open(tracked_file, "w") as f:
  1692. f.write("already tracked")
  1693. porcelain.add(self.repo.path, paths=[tracked_file])
  1694. porcelain.commit(
  1695. repo=self.repo.path,
  1696. message=b"Add tracked file",
  1697. author=b"test <email>",
  1698. committer=b"test <email>",
  1699. )
  1700. # Add more untracked files
  1701. with open(os.path.join(subdir, "untracked1.txt"), "w") as f:
  1702. f.write("new file 1")
  1703. with open(os.path.join(subdir, "untracked2.txt"), "w") as f:
  1704. f.write("new file 2")
  1705. # Add the directory
  1706. added, _ignored = porcelain.add(self.repo.path, paths=["mixed"])
  1707. # Should only add the untracked files
  1708. self.assertEqual(len(added), 2)
  1709. # Normalize paths to use forward slashes for comparison
  1710. added_normalized = [path.replace(os.sep, "/") for path in added]
  1711. self.assertIn("mixed/untracked1.txt", added_normalized)
  1712. self.assertIn("mixed/untracked2.txt", added_normalized)
  1713. self.assertNotIn("mixed/tracked.txt", added)
  1714. # Verify the index contains all files
  1715. index = self.repo.open_index()
  1716. self.assertIn(b"mixed/tracked.txt", index)
  1717. self.assertIn(b"mixed/untracked1.txt", index)
  1718. self.assertIn(b"mixed/untracked2.txt", index)
  1719. def test_add_directory_with_gitignore(self) -> None:
  1720. """Test adding a directory respects .gitignore patterns."""
  1721. # Create .gitignore
  1722. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1723. f.write("*.log\n*.tmp\nbuild/\n")
  1724. # Create directory with mixed files
  1725. testdir = os.path.join(self.repo.path, "testdir")
  1726. os.mkdir(testdir)
  1727. # Create various files
  1728. with open(os.path.join(testdir, "important.txt"), "w") as f:
  1729. f.write("keep this")
  1730. with open(os.path.join(testdir, "debug.log"), "w") as f:
  1731. f.write("ignore this")
  1732. with open(os.path.join(testdir, "temp.tmp"), "w") as f:
  1733. f.write("ignore this too")
  1734. with open(os.path.join(testdir, "readme.md"), "w") as f:
  1735. f.write("keep this too")
  1736. # Create a build directory that should be ignored
  1737. builddir = os.path.join(testdir, "build")
  1738. os.mkdir(builddir)
  1739. with open(os.path.join(builddir, "output.txt"), "w") as f:
  1740. f.write("ignore entire directory")
  1741. # Add the directory
  1742. added, ignored = porcelain.add(self.repo.path, paths=["testdir"])
  1743. # Should only add non-ignored files
  1744. # Normalize paths to use forward slashes for comparison
  1745. added_normalized = {path.replace(os.sep, "/") for path in added}
  1746. self.assertEqual(
  1747. added_normalized, {"testdir/important.txt", "testdir/readme.md"}
  1748. )
  1749. # Check ignored files
  1750. # Normalize paths to use forward slashes for comparison
  1751. ignored_normalized = {path.replace(os.sep, "/") for path in ignored}
  1752. self.assertIn("testdir/debug.log", ignored_normalized)
  1753. self.assertIn("testdir/temp.tmp", ignored_normalized)
  1754. self.assertIn("testdir/build/", ignored_normalized)
  1755. def test_add_multiple_directories(self) -> None:
  1756. """Test adding multiple directories in one call."""
  1757. # Create multiple directories
  1758. for dirname in ["dir1", "dir2", "dir3"]:
  1759. dirpath = os.path.join(self.repo.path, dirname)
  1760. os.mkdir(dirpath)
  1761. # Add files to each directory
  1762. for i in range(2):
  1763. with open(os.path.join(dirpath, f"file{i}.txt"), "w") as f:
  1764. f.write(f"content {dirname} {i}")
  1765. # Add all directories at once
  1766. added, _ignored = porcelain.add(self.repo.path, paths=["dir1", "dir2", "dir3"])
  1767. # Should add all files from all directories
  1768. self.assertEqual(len(added), 6)
  1769. # Normalize paths to use forward slashes for comparison
  1770. added_normalized = [path.replace(os.sep, "/") for path in added]
  1771. for dirname in ["dir1", "dir2", "dir3"]:
  1772. for i in range(2):
  1773. self.assertIn(f"{dirname}/file{i}.txt", added_normalized)
  1774. # Verify all files are staged
  1775. index = self.repo.open_index()
  1776. self.assertEqual(len(index), 6)
  1777. def test_add_default_paths_includes_modified_files(self) -> None:
  1778. """Test that add() with no paths includes both untracked and modified files."""
  1779. # Create and commit initial file
  1780. initial_file = os.path.join(self.repo.path, "existing.txt")
  1781. with open(initial_file, "w") as f:
  1782. f.write("initial content\n")
  1783. porcelain.add(repo=self.repo.path, paths=[initial_file])
  1784. porcelain.commit(
  1785. repo=self.repo.path,
  1786. message=b"initial commit",
  1787. author=b"test <email>",
  1788. committer=b"test <email>",
  1789. )
  1790. # Modify the existing file (this creates an unstaged change)
  1791. with open(initial_file, "w") as f:
  1792. f.write("modified content\n")
  1793. # Create a new untracked file
  1794. new_file = os.path.join(self.repo.path, "new.txt")
  1795. with open(new_file, "w") as f:
  1796. f.write("new file content\n")
  1797. # Call add() with no paths - should stage both modified and untracked files
  1798. added_files, ignored_files = porcelain.add(repo=self.repo.path)
  1799. # Verify both files were added
  1800. self.assertIn("existing.txt", added_files)
  1801. self.assertIn("new.txt", added_files)
  1802. self.assertEqual(len(ignored_files), 0)
  1803. # Verify both files are now staged
  1804. index = self.repo.open_index()
  1805. self.assertIn(b"existing.txt", index)
  1806. self.assertIn(b"new.txt", index)
  1807. class RemoveTests(PorcelainTestCase):
  1808. def test_remove_file(self) -> None:
  1809. fullpath = os.path.join(self.repo.path, "foo")
  1810. with open(fullpath, "w") as f:
  1811. f.write("BAR")
  1812. porcelain.add(self.repo.path, paths=[fullpath])
  1813. porcelain.commit(
  1814. repo=self.repo,
  1815. message=b"test",
  1816. author=b"test <email>",
  1817. committer=b"test <email>",
  1818. )
  1819. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "foo")))
  1820. cwd = os.getcwd()
  1821. self.addCleanup(os.chdir, cwd)
  1822. os.chdir(self.repo.path)
  1823. porcelain.remove(self.repo.path, paths=["foo"])
  1824. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1825. def test_remove_file_staged(self) -> None:
  1826. fullpath = os.path.join(self.repo.path, "foo")
  1827. with open(fullpath, "w") as f:
  1828. f.write("BAR")
  1829. cwd = os.getcwd()
  1830. self.addCleanup(os.chdir, cwd)
  1831. os.chdir(self.repo.path)
  1832. porcelain.add(self.repo.path, paths=[fullpath])
  1833. self.assertRaises(Exception, porcelain.rm, self.repo.path, paths=["foo"])
  1834. def test_remove_file_removed_on_disk(self) -> None:
  1835. fullpath = os.path.join(self.repo.path, "foo")
  1836. with open(fullpath, "w") as f:
  1837. f.write("BAR")
  1838. porcelain.add(self.repo.path, paths=[fullpath])
  1839. cwd = os.getcwd()
  1840. self.addCleanup(os.chdir, cwd)
  1841. os.chdir(self.repo.path)
  1842. os.remove(fullpath)
  1843. porcelain.remove(self.repo.path, paths=["foo"])
  1844. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1845. def test_remove_from_different_directory(self) -> None:
  1846. # Create a subdirectory with a file
  1847. subdir = os.path.join(self.repo.path, "mydir")
  1848. os.makedirs(subdir)
  1849. fullpath = os.path.join(subdir, "myfile")
  1850. with open(fullpath, "w") as f:
  1851. f.write("BAR")
  1852. # Add and commit the file
  1853. porcelain.add(self.repo.path, paths=[fullpath])
  1854. porcelain.commit(
  1855. repo=self.repo,
  1856. message=b"test",
  1857. author=b"test <email>",
  1858. committer=b"test <email>",
  1859. )
  1860. # Change to a different directory
  1861. cwd = os.getcwd()
  1862. tempdir = tempfile.mkdtemp()
  1863. def cleanup():
  1864. os.chdir(cwd)
  1865. shutil.rmtree(tempdir)
  1866. self.addCleanup(cleanup)
  1867. os.chdir(tempdir)
  1868. # Remove the file using relative path from repository root
  1869. porcelain.remove(self.repo.path, paths=["mydir/myfile"])
  1870. # Verify file was removed
  1871. self.assertFalse(os.path.exists(fullpath))
  1872. def test_remove_with_absolute_path(self) -> None:
  1873. # Create a file
  1874. fullpath = os.path.join(self.repo.path, "foo")
  1875. with open(fullpath, "w") as f:
  1876. f.write("BAR")
  1877. # Add and commit the file
  1878. porcelain.add(self.repo.path, paths=[fullpath])
  1879. porcelain.commit(
  1880. repo=self.repo,
  1881. message=b"test",
  1882. author=b"test <email>",
  1883. committer=b"test <email>",
  1884. )
  1885. # Change to a different directory
  1886. cwd = os.getcwd()
  1887. tempdir = tempfile.mkdtemp()
  1888. def cleanup():
  1889. os.chdir(cwd)
  1890. shutil.rmtree(tempdir)
  1891. self.addCleanup(cleanup)
  1892. os.chdir(tempdir)
  1893. # Remove the file using absolute path
  1894. porcelain.remove(self.repo.path, paths=[fullpath])
  1895. # Verify file was removed
  1896. self.assertFalse(os.path.exists(fullpath))
  1897. def test_remove_with_filter_normalization(self) -> None:
  1898. # Enable autocrlf to normalize line endings
  1899. config = self.repo.get_config()
  1900. config.set(("core",), "autocrlf", b"true")
  1901. config.write_to_path()
  1902. # Create a file with LF line endings (will be stored with LF in index)
  1903. fullpath = os.path.join(self.repo.path, "foo.txt")
  1904. with open(fullpath, "wb") as f:
  1905. f.write(b"line1\nline2\nline3")
  1906. # Add and commit the file (stored with LF in index)
  1907. porcelain.add(self.repo.path, paths=[fullpath])
  1908. porcelain.commit(
  1909. repo=self.repo,
  1910. message=b"Add file with LF",
  1911. author=b"test <email>",
  1912. committer=b"test <email>",
  1913. )
  1914. # Simulate checkout with CRLF conversion (as would happen on Windows)
  1915. with open(fullpath, "wb") as f:
  1916. f.write(b"line1\r\nline2\r\nline3")
  1917. # Verify file exists
  1918. self.assertTrue(os.path.exists(fullpath))
  1919. # Remove the file - this should not fail even though working tree has CRLF
  1920. # and index has LF (thanks to the normalization in the commit)
  1921. cwd = os.getcwd()
  1922. os.chdir(self.repo.path)
  1923. self.addCleanup(os.chdir, cwd)
  1924. porcelain.remove(self.repo.path, paths=["foo.txt"])
  1925. # Verify file was removed
  1926. self.assertFalse(os.path.exists(fullpath))
  1927. class MvTests(PorcelainTestCase):
  1928. def test_mv_file(self) -> None:
  1929. # Create a file
  1930. fullpath = os.path.join(self.repo.path, "foo")
  1931. with open(fullpath, "w") as f:
  1932. f.write("BAR")
  1933. # Add and commit the file
  1934. porcelain.add(self.repo.path, paths=[fullpath])
  1935. porcelain.commit(
  1936. repo=self.repo,
  1937. message=b"test",
  1938. author=b"test <email>",
  1939. committer=b"test <email>",
  1940. )
  1941. # Move the file
  1942. porcelain.mv(self.repo.path, "foo", "bar")
  1943. # Verify old path doesn't exist and new path does
  1944. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1945. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "bar")))
  1946. # Verify index was updated
  1947. index = self.repo.open_index()
  1948. self.assertNotIn(b"foo", index)
  1949. self.assertIn(b"bar", index)
  1950. def test_mv_file_to_existing_directory(self) -> None:
  1951. # Create a file and a directory
  1952. fullpath = os.path.join(self.repo.path, "foo")
  1953. with open(fullpath, "w") as f:
  1954. f.write("BAR")
  1955. dirpath = os.path.join(self.repo.path, "mydir")
  1956. os.makedirs(dirpath)
  1957. # Add and commit the file
  1958. porcelain.add(self.repo.path, paths=[fullpath])
  1959. porcelain.commit(
  1960. repo=self.repo,
  1961. message=b"test",
  1962. author=b"test <email>",
  1963. committer=b"test <email>",
  1964. )
  1965. # Move the file into the directory
  1966. porcelain.mv(self.repo.path, "foo", "mydir")
  1967. # Verify file moved into directory
  1968. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1969. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "mydir", "foo")))
  1970. # Verify index was updated
  1971. index = self.repo.open_index()
  1972. self.assertNotIn(b"foo", index)
  1973. self.assertIn(b"mydir/foo", index)
  1974. def test_mv_file_force_overwrite(self) -> None:
  1975. # Create two files
  1976. fullpath1 = os.path.join(self.repo.path, "foo")
  1977. with open(fullpath1, "w") as f:
  1978. f.write("FOO")
  1979. fullpath2 = os.path.join(self.repo.path, "bar")
  1980. with open(fullpath2, "w") as f:
  1981. f.write("BAR")
  1982. # Add and commit both files
  1983. porcelain.add(self.repo.path, paths=[fullpath1, fullpath2])
  1984. porcelain.commit(
  1985. repo=self.repo,
  1986. message=b"test",
  1987. author=b"test <email>",
  1988. committer=b"test <email>",
  1989. )
  1990. # Try to move without force (should fail)
  1991. self.assertRaises(porcelain.Error, porcelain.mv, self.repo.path, "foo", "bar")
  1992. # Move with force
  1993. porcelain.mv(self.repo.path, "foo", "bar", force=True)
  1994. # Verify foo doesn't exist and bar has foo's content
  1995. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1996. with open(os.path.join(self.repo.path, "bar")) as f:
  1997. self.assertEqual(f.read(), "FOO")
  1998. def test_mv_file_not_tracked(self) -> None:
  1999. # Create an untracked file
  2000. fullpath = os.path.join(self.repo.path, "untracked")
  2001. with open(fullpath, "w") as f:
  2002. f.write("UNTRACKED")
  2003. # Try to move it (should fail)
  2004. self.assertRaises(
  2005. porcelain.Error, porcelain.mv, self.repo.path, "untracked", "tracked"
  2006. )
  2007. def test_mv_file_not_exists(self) -> None:
  2008. # Try to move a non-existent file
  2009. self.assertRaises(
  2010. porcelain.Error, porcelain.mv, self.repo.path, "nonexistent", "destination"
  2011. )
  2012. def test_mv_absolute_paths(self) -> None:
  2013. # Create a file
  2014. fullpath = os.path.join(self.repo.path, "foo")
  2015. with open(fullpath, "w") as f:
  2016. f.write("BAR")
  2017. # Add and commit the file
  2018. porcelain.add(self.repo.path, paths=[fullpath])
  2019. porcelain.commit(
  2020. repo=self.repo,
  2021. message=b"test",
  2022. author=b"test <email>",
  2023. committer=b"test <email>",
  2024. )
  2025. # Move using absolute paths
  2026. dest_path = os.path.join(self.repo.path, "bar")
  2027. porcelain.mv(self.repo.path, fullpath, dest_path)
  2028. # Verify file moved
  2029. self.assertFalse(os.path.exists(fullpath))
  2030. self.assertTrue(os.path.exists(dest_path))
  2031. def test_mv_from_different_directory(self) -> None:
  2032. # Create a subdirectory with a file
  2033. subdir = os.path.join(self.repo.path, "mydir")
  2034. os.makedirs(subdir)
  2035. fullpath = os.path.join(subdir, "myfile")
  2036. with open(fullpath, "w") as f:
  2037. f.write("BAR")
  2038. # Add and commit the file
  2039. porcelain.add(self.repo.path, paths=[fullpath])
  2040. porcelain.commit(
  2041. repo=self.repo,
  2042. message=b"test",
  2043. author=b"test <email>",
  2044. committer=b"test <email>",
  2045. )
  2046. # Change to a different directory and move the file
  2047. cwd = os.getcwd()
  2048. tempdir = tempfile.mkdtemp()
  2049. def cleanup():
  2050. os.chdir(cwd)
  2051. shutil.rmtree(tempdir)
  2052. self.addCleanup(cleanup)
  2053. os.chdir(tempdir)
  2054. # Move the file using relative path from repository root
  2055. porcelain.mv(self.repo.path, "mydir/myfile", "renamed")
  2056. # Verify file was moved
  2057. self.assertFalse(os.path.exists(fullpath))
  2058. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "renamed")))
  2059. class LogTests(PorcelainTestCase):
  2060. def test_simple(self) -> None:
  2061. _c1, _c2, c3 = build_commit_graph(
  2062. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2063. )
  2064. self.repo.refs[b"HEAD"] = c3.id
  2065. self.maxDiff = None
  2066. outstream = StringIO()
  2067. porcelain.log(self.repo.path, outstream=outstream)
  2068. self.assertEqual(
  2069. outstream.getvalue(),
  2070. """\
  2071. --------------------------------------------------
  2072. commit: 4a3b887baa9ecb2d054d2469b628aef84e2d74f0
  2073. merge: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  2074. Author: Test Author <test@nodomain.com>
  2075. Committer: Test Committer <test@nodomain.com>
  2076. Date: Fri Jan 01 2010 00:00:00 +0000
  2077. Commit 3
  2078. --------------------------------------------------
  2079. commit: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  2080. Author: Test Author <test@nodomain.com>
  2081. Committer: Test Committer <test@nodomain.com>
  2082. Date: Fri Jan 01 2010 00:00:00 +0000
  2083. Commit 2
  2084. --------------------------------------------------
  2085. commit: 11d3cf672a19366435c1983c7340b008ec6b8bf3
  2086. Author: Test Author <test@nodomain.com>
  2087. Committer: Test Committer <test@nodomain.com>
  2088. Date: Fri Jan 01 2010 00:00:00 +0000
  2089. Commit 1
  2090. """,
  2091. )
  2092. def test_max_entries(self) -> None:
  2093. _c1, _c2, c3 = build_commit_graph(
  2094. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2095. )
  2096. self.repo.refs[b"HEAD"] = c3.id
  2097. outstream = StringIO()
  2098. porcelain.log(self.repo.path, outstream=outstream, max_entries=1)
  2099. self.assertEqual(1, outstream.getvalue().count("-" * 50))
  2100. def test_no_revisions(self) -> None:
  2101. outstream = StringIO()
  2102. porcelain.log(self.repo.path, outstream=outstream)
  2103. self.assertEqual("", outstream.getvalue())
  2104. def test_empty_message(self) -> None:
  2105. c1 = make_commit(message="")
  2106. self.repo.object_store.add_object(c1)
  2107. self.repo.refs[b"HEAD"] = c1.id
  2108. outstream = StringIO()
  2109. porcelain.log(self.repo.path, outstream=outstream)
  2110. self.assertEqual(
  2111. outstream.getvalue(),
  2112. """\
  2113. --------------------------------------------------
  2114. commit: 4a7ad5552fad70647a81fb9a4a923ccefcca4b76
  2115. Author: Test Author <test@nodomain.com>
  2116. Committer: Test Committer <test@nodomain.com>
  2117. Date: Fri Jan 01 2010 00:00:00 +0000
  2118. """,
  2119. )
  2120. class ShowTests(PorcelainTestCase):
  2121. def test_nolist(self) -> None:
  2122. _c1, _c2, c3 = build_commit_graph(
  2123. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2124. )
  2125. self.repo.refs[b"HEAD"] = c3.id
  2126. outstream = StringIO()
  2127. porcelain.show(self.repo.path, objects=c3.id, outstream=outstream)
  2128. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  2129. def test_simple(self) -> None:
  2130. _c1, _c2, c3 = build_commit_graph(
  2131. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2132. )
  2133. self.repo.refs[b"HEAD"] = c3.id
  2134. outstream = StringIO()
  2135. porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream)
  2136. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  2137. def test_blob(self) -> None:
  2138. b = Blob.from_string(b"The Foo\n")
  2139. self.repo.object_store.add_object(b)
  2140. outstream = StringIO()
  2141. porcelain.show(self.repo.path, objects=[b.id], outstream=outstream)
  2142. self.assertEqual(outstream.getvalue(), "The Foo\n")
  2143. def test_commit_no_parent(self) -> None:
  2144. a = Blob.from_string(b"The Foo\n")
  2145. ta = Tree()
  2146. ta.add(b"somename", 0o100644, a.id)
  2147. ca = make_commit(tree=ta.id)
  2148. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2149. outstream = StringIO()
  2150. porcelain.show(self.repo.path, objects=[ca.id], outstream=outstream)
  2151. self.assertMultiLineEqual(
  2152. outstream.getvalue(),
  2153. """\
  2154. --------------------------------------------------
  2155. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2156. Author: Test Author <test@nodomain.com>
  2157. Committer: Test Committer <test@nodomain.com>
  2158. Date: Fri Jan 01 2010 00:00:00 +0000
  2159. Test message.
  2160. diff --git a/somename b/somename
  2161. new file mode 100644
  2162. index 0000000..ea5c7bf
  2163. --- /dev/null
  2164. +++ b/somename
  2165. @@ -0,0 +1 @@
  2166. +The Foo
  2167. """,
  2168. )
  2169. def test_tag(self) -> None:
  2170. a = Blob.from_string(b"The Foo\n")
  2171. ta = Tree()
  2172. ta.add(b"somename", 0o100644, a.id)
  2173. ca = make_commit(tree=ta.id)
  2174. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2175. porcelain.tag_create(
  2176. self.repo.path,
  2177. b"tryme",
  2178. b"foo <foo@bar.com>",
  2179. b"bar",
  2180. annotated=True,
  2181. objectish=ca.id,
  2182. tag_time=1552854211,
  2183. tag_timezone=0,
  2184. )
  2185. outstream = StringIO()
  2186. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2187. self.maxDiff = None
  2188. self.assertMultiLineEqual(
  2189. outstream.getvalue(),
  2190. """\
  2191. Tagger: foo <foo@bar.com>
  2192. Date: Sun Mar 17 2019 20:23:31 +0000
  2193. bar
  2194. --------------------------------------------------
  2195. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2196. Author: Test Author <test@nodomain.com>
  2197. Committer: Test Committer <test@nodomain.com>
  2198. Date: Fri Jan 01 2010 00:00:00 +0000
  2199. Test message.
  2200. diff --git a/somename b/somename
  2201. new file mode 100644
  2202. index 0000000..ea5c7bf
  2203. --- /dev/null
  2204. +++ b/somename
  2205. @@ -0,0 +1 @@
  2206. +The Foo
  2207. """,
  2208. )
  2209. def test_tag_unicode(self) -> None:
  2210. a = Blob.from_string(b"The Foo\n")
  2211. ta = Tree()
  2212. ta.add(b"somename", 0o100644, a.id)
  2213. ca = make_commit(tree=ta.id)
  2214. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2215. porcelain.tag_create(
  2216. self.repo.path,
  2217. "tryme",
  2218. "foo <foo@bar.com>",
  2219. "bar",
  2220. annotated=True,
  2221. objectish=ca.id,
  2222. tag_time=1552854211,
  2223. tag_timezone=0,
  2224. )
  2225. outstream = StringIO()
  2226. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2227. self.maxDiff = None
  2228. self.assertMultiLineEqual(
  2229. outstream.getvalue(),
  2230. """\
  2231. Tagger: foo <foo@bar.com>
  2232. Date: Sun Mar 17 2019 20:23:31 +0000
  2233. bar
  2234. --------------------------------------------------
  2235. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2236. Author: Test Author <test@nodomain.com>
  2237. Committer: Test Committer <test@nodomain.com>
  2238. Date: Fri Jan 01 2010 00:00:00 +0000
  2239. Test message.
  2240. diff --git a/somename b/somename
  2241. new file mode 100644
  2242. index 0000000..ea5c7bf
  2243. --- /dev/null
  2244. +++ b/somename
  2245. @@ -0,0 +1 @@
  2246. +The Foo
  2247. """,
  2248. )
  2249. def test_commit_with_change(self) -> None:
  2250. a = Blob.from_string(b"The Foo\n")
  2251. ta = Tree()
  2252. ta.add(b"somename", 0o100644, a.id)
  2253. ca = make_commit(tree=ta.id)
  2254. b = Blob.from_string(b"The Bar\n")
  2255. tb = Tree()
  2256. tb.add(b"somename", 0o100644, b.id)
  2257. cb = make_commit(tree=tb.id, parents=[ca.id])
  2258. self.repo.object_store.add_objects(
  2259. [
  2260. (a, None),
  2261. (b, None),
  2262. (ta, None),
  2263. (tb, None),
  2264. (ca, None),
  2265. (cb, None),
  2266. ]
  2267. )
  2268. outstream = StringIO()
  2269. porcelain.show(self.repo.path, objects=[cb.id], outstream=outstream)
  2270. self.assertMultiLineEqual(
  2271. outstream.getvalue(),
  2272. """\
  2273. --------------------------------------------------
  2274. commit: 2c6b6c9cb72c130956657e1fdae58e5b103744fa
  2275. Author: Test Author <test@nodomain.com>
  2276. Committer: Test Committer <test@nodomain.com>
  2277. Date: Fri Jan 01 2010 00:00:00 +0000
  2278. Test message.
  2279. diff --git a/somename b/somename
  2280. index ea5c7bf..fd38bcb 100644
  2281. --- a/somename
  2282. +++ b/somename
  2283. @@ -1 +1 @@
  2284. -The Foo
  2285. +The Bar
  2286. """,
  2287. )
  2288. class FormatPatchTests(PorcelainTestCase):
  2289. def test_format_patch_single_commit(self) -> None:
  2290. # Create initial commit
  2291. tree1 = Tree()
  2292. c1 = make_commit(
  2293. tree=tree1,
  2294. message=b"Initial commit",
  2295. )
  2296. self.repo.object_store.add_objects([(tree1, None), (c1, None)])
  2297. # Create second commit
  2298. b = Blob.from_string(b"modified")
  2299. tree = Tree()
  2300. tree.add(b"test.txt", 0o100644, b.id)
  2301. c2 = make_commit(
  2302. tree=tree,
  2303. parents=[c1.id],
  2304. message=b"Add test.txt",
  2305. )
  2306. self.repo.object_store.add_objects([(b, None), (tree, None), (c2, None)])
  2307. self.repo[b"HEAD"] = c2.id
  2308. # Generate patch for single commit
  2309. with tempfile.TemporaryDirectory() as tmpdir:
  2310. patches = porcelain.format_patch(
  2311. self.repo.path,
  2312. committish=c2.id,
  2313. outdir=tmpdir,
  2314. )
  2315. self.assertEqual(len(patches), 1)
  2316. self.assertTrue(patches[0].endswith("-Add-test.txt.patch"))
  2317. # Verify patch content
  2318. with open(patches[0], "rb") as f:
  2319. content = f.read()
  2320. self.assertIn(b"Subject: [PATCH 1/1] Add test.txt", content)
  2321. self.assertIn(b"+modified", content)
  2322. def test_format_patch_multiple_commits(self) -> None:
  2323. # Create commit chain
  2324. commits = []
  2325. for i in range(3):
  2326. blob = Blob.from_string(f"content {i}".encode())
  2327. tree = Tree()
  2328. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  2329. parents = [commits[-1].id] if commits else []
  2330. commit = make_commit(
  2331. tree=tree,
  2332. parents=parents,
  2333. message=f"Commit {i}".encode(),
  2334. )
  2335. self.repo.object_store.add_objects(
  2336. [(blob, None), (tree, None), (commit, None)]
  2337. )
  2338. commits.append(commit)
  2339. self.repo[b"HEAD"] = commits[-1].id
  2340. # Test generating last 2 commits
  2341. with tempfile.TemporaryDirectory() as tmpdir:
  2342. patches = porcelain.format_patch(
  2343. self.repo.path,
  2344. n=2,
  2345. outdir=tmpdir,
  2346. )
  2347. self.assertEqual(len(patches), 2)
  2348. self.assertTrue(patches[0].endswith("-Commit-1.patch"))
  2349. self.assertTrue(patches[1].endswith("-Commit-2.patch"))
  2350. # Check patch numbering
  2351. with open(patches[0], "rb") as f:
  2352. self.assertIn(b"Subject: [PATCH 1/2] Commit 1", f.read())
  2353. with open(patches[1], "rb") as f:
  2354. self.assertIn(b"Subject: [PATCH 2/2] Commit 2", f.read())
  2355. def test_format_patch_range(self) -> None:
  2356. # Create commit chain
  2357. c1, _c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  2358. self.repo[b"HEAD"] = c3.id
  2359. # Test commit range
  2360. with tempfile.TemporaryDirectory() as tmpdir:
  2361. patches = porcelain.format_patch(
  2362. self.repo.path,
  2363. committish=(c1.id, c3.id),
  2364. outdir=tmpdir,
  2365. )
  2366. # Should include c2 and c3
  2367. self.assertEqual(len(patches), 2)
  2368. def test_format_patch_stdout(self) -> None:
  2369. # Create a commit
  2370. blob = Blob.from_string(b"test content")
  2371. tree = Tree()
  2372. tree.add(b"test.txt", 0o100644, blob.id)
  2373. commit = make_commit(
  2374. tree=tree,
  2375. message=b"Test commit",
  2376. )
  2377. self.repo.object_store.add_objects([(blob, None), (tree, None), (commit, None)])
  2378. self.repo[b"HEAD"] = commit.id
  2379. # Test stdout output
  2380. outstream = BytesIO()
  2381. patches = porcelain.format_patch(
  2382. self.repo.path,
  2383. committish=commit.id,
  2384. stdout=True,
  2385. outstream=outstream,
  2386. )
  2387. # Should return empty list when writing to stdout
  2388. self.assertEqual(patches, [])
  2389. # Check stdout content
  2390. outstream.seek(0)
  2391. content = outstream.read()
  2392. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  2393. self.assertIn(b"diff --git", content)
  2394. def test_format_patch_no_commits(self) -> None:
  2395. # Test with a new repository with no commits
  2396. # Just remove HEAD to simulate empty repo
  2397. patches = porcelain.format_patch(
  2398. self.repo.path,
  2399. n=5,
  2400. )
  2401. self.assertEqual(patches, [])
  2402. class SymbolicRefTests(PorcelainTestCase):
  2403. def test_set_wrong_symbolic_ref(self) -> None:
  2404. _c1, _c2, c3 = build_commit_graph(
  2405. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2406. )
  2407. self.repo.refs[b"HEAD"] = c3.id
  2408. self.assertRaises(
  2409. porcelain.Error, porcelain.symbolic_ref, self.repo.path, b"foobar"
  2410. )
  2411. def test_set_force_wrong_symbolic_ref(self) -> None:
  2412. _c1, _c2, c3 = build_commit_graph(
  2413. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2414. )
  2415. self.repo.refs[b"HEAD"] = c3.id
  2416. porcelain.symbolic_ref(self.repo.path, b"force_foobar", force=True)
  2417. # test if we actually changed the file
  2418. with self.repo.get_named_file("HEAD") as f:
  2419. new_ref = f.read()
  2420. self.assertEqual(new_ref, b"ref: refs/heads/force_foobar\n")
  2421. def test_set_symbolic_ref(self) -> None:
  2422. _c1, _c2, c3 = build_commit_graph(
  2423. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2424. )
  2425. self.repo.refs[b"HEAD"] = c3.id
  2426. porcelain.symbolic_ref(self.repo.path, b"master")
  2427. def test_set_symbolic_ref_other_than_master(self) -> None:
  2428. _c1, _c2, c3 = build_commit_graph(
  2429. self.repo.object_store,
  2430. [[1], [2, 1], [3, 1, 2]],
  2431. attrs=dict(refs="develop"),
  2432. )
  2433. self.repo.refs[b"HEAD"] = c3.id
  2434. self.repo.refs[b"refs/heads/develop"] = c3.id
  2435. porcelain.symbolic_ref(self.repo.path, b"develop")
  2436. # test if we actually changed the file
  2437. with self.repo.get_named_file("HEAD") as f:
  2438. new_ref = f.read()
  2439. self.assertEqual(new_ref, b"ref: refs/heads/develop\n")
  2440. class DiffTreeTests(PorcelainTestCase):
  2441. def test_empty(self) -> None:
  2442. _c1, c2, c3 = build_commit_graph(
  2443. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2444. )
  2445. self.repo.refs[b"HEAD"] = c3.id
  2446. outstream = BytesIO()
  2447. porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream)
  2448. self.assertEqual(outstream.getvalue(), b"")
  2449. class DiffTests(PorcelainTestCase):
  2450. def test_diff_uncommitted_stage(self) -> None:
  2451. # Test diff in repository with no commits yet
  2452. fullpath = os.path.join(self.repo.path, "test.txt")
  2453. with open(fullpath, "w") as f:
  2454. f.write("Hello, world!\n")
  2455. porcelain.add(self.repo.path, paths=["test.txt"])
  2456. outstream = BytesIO()
  2457. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2458. diff_output = outstream.getvalue()
  2459. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2460. self.assertIn(b"new file mode", diff_output)
  2461. self.assertIn(b"+Hello, world!", diff_output)
  2462. def test_diff_uncommitted_working_tree(self) -> None:
  2463. # Test unstaged changes in repository with no commits
  2464. fullpath = os.path.join(self.repo.path, "test.txt")
  2465. with open(fullpath, "w") as f:
  2466. f.write("Hello, world!\n")
  2467. porcelain.add(self.repo.path, paths=["test.txt"])
  2468. # Modify file in working tree
  2469. with open(fullpath, "w") as f:
  2470. f.write("Hello, world!\nNew line\n")
  2471. outstream = BytesIO()
  2472. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2473. diff_output = outstream.getvalue()
  2474. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2475. self.assertIn(b"+New line", diff_output)
  2476. def test_diff_with_commits_staged(self) -> None:
  2477. # Test staged changes with existing commits
  2478. fullpath = os.path.join(self.repo.path, "test.txt")
  2479. with open(fullpath, "w") as f:
  2480. f.write("Initial content\n")
  2481. porcelain.add(self.repo.path, paths=["test.txt"])
  2482. porcelain.commit(self.repo.path, message=b"Initial commit")
  2483. # Modify and stage
  2484. with open(fullpath, "w") as f:
  2485. f.write("Initial content\nModified\n")
  2486. porcelain.add(self.repo.path, paths=["test.txt"])
  2487. outstream = BytesIO()
  2488. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2489. diff_output = outstream.getvalue()
  2490. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2491. self.assertIn(b"+Modified", diff_output)
  2492. def test_diff_with_commits_unstaged(self) -> None:
  2493. # Test unstaged changes with existing commits
  2494. fullpath = os.path.join(self.repo.path, "test.txt")
  2495. with open(fullpath, "w") as f:
  2496. f.write("Initial content\n")
  2497. porcelain.add(self.repo.path, paths=["test.txt"])
  2498. porcelain.commit(self.repo.path, message=b"Initial commit")
  2499. # Modify without staging
  2500. with open(fullpath, "w") as f:
  2501. f.write("Initial content\nModified\n")
  2502. outstream = BytesIO()
  2503. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2504. diff_output = outstream.getvalue()
  2505. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2506. self.assertIn(b"+Modified", diff_output)
  2507. def test_diff_file_deletion(self) -> None:
  2508. # Test showing file deletion
  2509. fullpath = os.path.join(self.repo.path, "test.txt")
  2510. with open(fullpath, "w") as f:
  2511. f.write("Content to delete\n")
  2512. porcelain.add(self.repo.path, paths=["test.txt"])
  2513. porcelain.commit(self.repo.path, message=b"Add file")
  2514. # Delete file
  2515. os.unlink(fullpath)
  2516. outstream = BytesIO()
  2517. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2518. diff_output = outstream.getvalue()
  2519. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2520. self.assertIn(b"deleted file mode", diff_output)
  2521. self.assertIn(b"-Content to delete", diff_output)
  2522. def test_diff_with_paths(self) -> None:
  2523. # Test diff with specific paths
  2524. # Create two files
  2525. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2526. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2527. with open(fullpath1, "w") as f:
  2528. f.write("File 1 content\n")
  2529. with open(fullpath2, "w") as f:
  2530. f.write("File 2 content\n")
  2531. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2532. porcelain.commit(self.repo.path, message=b"Add two files")
  2533. # Modify both files
  2534. with open(fullpath1, "w") as f:
  2535. f.write("File 1 modified\n")
  2536. with open(fullpath2, "w") as f:
  2537. f.write("File 2 modified\n")
  2538. # Test diff with specific path
  2539. outstream = BytesIO()
  2540. porcelain.diff(self.repo.path, paths=["file1.txt"], outstream=outstream)
  2541. diff_output = outstream.getvalue()
  2542. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2543. self.assertIn(b"-File 1 content", diff_output)
  2544. self.assertIn(b"+File 1 modified", diff_output)
  2545. # file2.txt should not appear in diff
  2546. self.assertNotIn(b"file2.txt", diff_output)
  2547. def test_diff_with_paths_multiple(self) -> None:
  2548. # Test diff with multiple paths
  2549. # Create three files
  2550. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2551. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2552. fullpath3 = os.path.join(self.repo.path, "file3.txt")
  2553. with open(fullpath1, "w") as f:
  2554. f.write("File 1 content\n")
  2555. with open(fullpath2, "w") as f:
  2556. f.write("File 2 content\n")
  2557. with open(fullpath3, "w") as f:
  2558. f.write("File 3 content\n")
  2559. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt", "file3.txt"])
  2560. porcelain.commit(self.repo.path, message=b"Add three files")
  2561. # Modify all files
  2562. with open(fullpath1, "w") as f:
  2563. f.write("File 1 modified\n")
  2564. with open(fullpath2, "w") as f:
  2565. f.write("File 2 modified\n")
  2566. with open(fullpath3, "w") as f:
  2567. f.write("File 3 modified\n")
  2568. # Test diff with two specific paths
  2569. outstream = BytesIO()
  2570. porcelain.diff(
  2571. self.repo.path, paths=["file1.txt", "file3.txt"], outstream=outstream
  2572. )
  2573. diff_output = outstream.getvalue()
  2574. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2575. self.assertIn(b"diff --git a/file3.txt b/file3.txt", diff_output)
  2576. # file2.txt should not appear in diff
  2577. self.assertNotIn(b"file2.txt", diff_output)
  2578. def test_diff_with_paths_directory(self) -> None:
  2579. # Test diff with directory paths
  2580. # Create files in subdirectory
  2581. os.mkdir(os.path.join(self.repo.path, "subdir"))
  2582. fullpath1 = os.path.join(self.repo.path, "subdir", "file1.txt")
  2583. fullpath2 = os.path.join(self.repo.path, "subdir", "file2.txt")
  2584. fullpath3 = os.path.join(self.repo.path, "root.txt")
  2585. with open(fullpath1, "w") as f:
  2586. f.write("Subdir file 1\n")
  2587. with open(fullpath2, "w") as f:
  2588. f.write("Subdir file 2\n")
  2589. with open(fullpath3, "w") as f:
  2590. f.write("Root file\n")
  2591. porcelain.add(
  2592. self.repo.path, paths=["subdir/file1.txt", "subdir/file2.txt", "root.txt"]
  2593. )
  2594. porcelain.commit(self.repo.path, message=b"Add files in subdir")
  2595. # Modify all files
  2596. with open(fullpath1, "w") as f:
  2597. f.write("Subdir file 1 modified\n")
  2598. with open(fullpath2, "w") as f:
  2599. f.write("Subdir file 2 modified\n")
  2600. with open(fullpath3, "w") as f:
  2601. f.write("Root file modified\n")
  2602. # Test diff with directory path
  2603. outstream = BytesIO()
  2604. porcelain.diff(self.repo.path, paths=["subdir"], outstream=outstream)
  2605. diff_output = outstream.getvalue()
  2606. self.assertIn(b"subdir/file1.txt", diff_output)
  2607. self.assertIn(b"subdir/file2.txt", diff_output)
  2608. # root.txt should not appear in diff
  2609. self.assertNotIn(b"root.txt", diff_output)
  2610. def test_diff_staged_with_paths(self) -> None:
  2611. # Test staged diff with specific paths
  2612. # Create two files
  2613. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2614. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2615. with open(fullpath1, "w") as f:
  2616. f.write("File 1 content\n")
  2617. with open(fullpath2, "w") as f:
  2618. f.write("File 2 content\n")
  2619. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2620. porcelain.commit(self.repo.path, message=b"Add two files")
  2621. # Modify and stage both files
  2622. with open(fullpath1, "w") as f:
  2623. f.write("File 1 staged\n")
  2624. with open(fullpath2, "w") as f:
  2625. f.write("File 2 staged\n")
  2626. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2627. # Test staged diff with specific path
  2628. outstream = BytesIO()
  2629. porcelain.diff(
  2630. self.repo.path, staged=True, paths=["file1.txt"], outstream=outstream
  2631. )
  2632. diff_output = outstream.getvalue()
  2633. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2634. self.assertIn(b"-File 1 content", diff_output)
  2635. self.assertIn(b"+File 1 staged", diff_output)
  2636. # file2.txt should not appear in diff
  2637. self.assertNotIn(b"file2.txt", diff_output)
  2638. def test_diff_with_commit_and_paths(self) -> None:
  2639. # Test diff against specific commit with paths
  2640. # Create initial file
  2641. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2642. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2643. with open(fullpath1, "w") as f:
  2644. f.write("Initial content 1\n")
  2645. with open(fullpath2, "w") as f:
  2646. f.write("Initial content 2\n")
  2647. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2648. first_commit = porcelain.commit(self.repo.path, message=b"Initial commit")
  2649. # Make second commit
  2650. with open(fullpath1, "w") as f:
  2651. f.write("Second content 1\n")
  2652. with open(fullpath2, "w") as f:
  2653. f.write("Second content 2\n")
  2654. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2655. porcelain.commit(self.repo.path, message=b"Second commit")
  2656. # Modify working tree
  2657. with open(fullpath1, "w") as f:
  2658. f.write("Working content 1\n")
  2659. with open(fullpath2, "w") as f:
  2660. f.write("Working content 2\n")
  2661. # Test diff against first commit with specific path
  2662. outstream = BytesIO()
  2663. porcelain.diff(
  2664. self.repo.path,
  2665. commit=first_commit,
  2666. paths=["file1.txt"],
  2667. outstream=outstream,
  2668. )
  2669. diff_output = outstream.getvalue()
  2670. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2671. self.assertIn(b"-Initial content 1", diff_output)
  2672. self.assertIn(b"+Working content 1", diff_output)
  2673. # file2.txt should not appear in diff
  2674. self.assertNotIn(b"file2.txt", diff_output)
  2675. class CommitTreeTests(PorcelainTestCase):
  2676. def test_simple(self) -> None:
  2677. _c1, _c2, _c3 = build_commit_graph(
  2678. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2679. )
  2680. b = Blob()
  2681. b.data = b"foo the bar"
  2682. t = Tree()
  2683. t.add(b"somename", 0o100644, b.id)
  2684. self.repo.object_store.add_object(t)
  2685. self.repo.object_store.add_object(b)
  2686. sha = porcelain.commit_tree(
  2687. self.repo.path,
  2688. t.id,
  2689. message=b"Withcommit.",
  2690. author=b"Joe <joe@example.com>",
  2691. committer=b"Jane <jane@example.com>",
  2692. )
  2693. self.assertIsInstance(sha, bytes)
  2694. self.assertEqual(len(sha), 40)
  2695. class RevListTests(PorcelainTestCase):
  2696. def test_simple(self) -> None:
  2697. c1, c2, c3 = build_commit_graph(
  2698. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2699. )
  2700. outstream = BytesIO()
  2701. porcelain.rev_list(self.repo.path, [c3.id], outstream=outstream)
  2702. self.assertEqual(
  2703. c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue()
  2704. )
  2705. @skipIf(
  2706. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  2707. "gpgme not easily available or supported on Windows and PyPy",
  2708. )
  2709. class TagCreateSignTests(PorcelainGpgTestCase):
  2710. def test_default_key(self) -> None:
  2711. _c1, _c2, c3 = build_commit_graph(
  2712. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2713. )
  2714. self.repo.refs[b"HEAD"] = c3.id
  2715. cfg = self.repo.get_config()
  2716. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2717. self.import_default_key()
  2718. porcelain.tag_create(
  2719. self.repo.path,
  2720. b"tryme",
  2721. b"foo <foo@bar.com>",
  2722. b"bar",
  2723. annotated=True,
  2724. sign=True,
  2725. )
  2726. tags = self.repo.refs.as_dict(b"refs/tags")
  2727. self.assertEqual(list(tags.keys()), [b"tryme"])
  2728. tag = self.repo[b"refs/tags/tryme"]
  2729. self.assertIsInstance(tag, Tag)
  2730. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2731. self.assertEqual(b"bar\n", tag.message)
  2732. self.assertRecentTimestamp(tag.tag_time)
  2733. tag = self.repo[b"refs/tags/tryme"]
  2734. assert isinstance(tag, Tag)
  2735. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2736. tag.verify()
  2737. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2738. self.import_non_default_key()
  2739. self.assertRaises(
  2740. gpg.errors.MissingSignatures,
  2741. tag.verify,
  2742. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  2743. )
  2744. assert tag.signature is not None
  2745. tag._chunked_text = [b"bad data", tag.signature]
  2746. self.assertRaises(
  2747. gpg.errors.BadSignatures,
  2748. tag.verify,
  2749. )
  2750. def test_non_default_key(self) -> None:
  2751. _c1, _c2, c3 = build_commit_graph(
  2752. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2753. )
  2754. self.repo.refs[b"HEAD"] = c3.id
  2755. cfg = self.repo.get_config()
  2756. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2757. self.import_non_default_key()
  2758. porcelain.tag_create(
  2759. self.repo.path,
  2760. b"tryme",
  2761. b"foo <foo@bar.com>",
  2762. b"bar",
  2763. annotated=True,
  2764. sign=True,
  2765. )
  2766. tags = self.repo.refs.as_dict(b"refs/tags")
  2767. self.assertEqual(list(tags.keys()), [b"tryme"])
  2768. tag = self.repo[b"refs/tags/tryme"]
  2769. self.assertIsInstance(tag, Tag)
  2770. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2771. self.assertEqual(b"bar\n", tag.message)
  2772. self.assertRecentTimestamp(tag.tag_time)
  2773. tag = self.repo[b"refs/tags/tryme"]
  2774. assert isinstance(tag, Tag)
  2775. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2776. tag.verify()
  2777. def test_sign_uses_config_signingkey(self) -> None:
  2778. """Test that sign=True uses user.signingKey from config."""
  2779. _c1, _c2, c3 = build_commit_graph(
  2780. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2781. )
  2782. self.repo.refs[b"HEAD"] = c3.id
  2783. # Set up user.signingKey in config
  2784. cfg = self.repo.get_config()
  2785. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2786. cfg.write_to_path()
  2787. self.import_default_key()
  2788. # Create tag with sign=True (should use signingKey from config)
  2789. porcelain.tag_create(
  2790. self.repo.path,
  2791. b"signed-tag",
  2792. b"foo <foo@bar.com>",
  2793. b"Tag with configured key",
  2794. annotated=True,
  2795. sign=True, # This should read user.signingKey from config
  2796. )
  2797. tags = self.repo.refs.as_dict(b"refs/tags")
  2798. self.assertEqual(list(tags.keys()), [b"signed-tag"])
  2799. tag = self.repo[b"refs/tags/signed-tag"]
  2800. self.assertIsInstance(tag, Tag)
  2801. # Verify the tag is signed with the configured key
  2802. tag.verify()
  2803. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2804. def test_tag_gpg_sign_config_enabled(self) -> None:
  2805. """Test that tag.gpgSign=true automatically signs tags."""
  2806. _c1, _c2, c3 = build_commit_graph(
  2807. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2808. )
  2809. self.repo.refs[b"HEAD"] = c3.id
  2810. # Set up user.signingKey and tag.gpgSign in config
  2811. cfg = self.repo.get_config()
  2812. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2813. cfg.set(("tag",), "gpgSign", True)
  2814. cfg.write_to_path()
  2815. self.import_default_key()
  2816. # Create tag without explicit sign parameter (should auto-sign due to config)
  2817. porcelain.tag_create(
  2818. self.repo.path,
  2819. b"auto-signed-tag",
  2820. b"foo <foo@bar.com>",
  2821. b"Auto-signed tag",
  2822. annotated=True,
  2823. # No sign parameter - should use tag.gpgSign config
  2824. )
  2825. tags = self.repo.refs.as_dict(b"refs/tags")
  2826. self.assertEqual(list(tags.keys()), [b"auto-signed-tag"])
  2827. tag = self.repo[b"refs/tags/auto-signed-tag"]
  2828. self.assertIsInstance(tag, Tag)
  2829. # Verify the tag is signed due to config
  2830. tag.verify()
  2831. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2832. def test_tag_gpg_sign_config_disabled(self) -> None:
  2833. """Test that tag.gpgSign=false does not sign tags."""
  2834. _c1, _c2, c3 = build_commit_graph(
  2835. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2836. )
  2837. self.repo.refs[b"HEAD"] = c3.id
  2838. # Set up user.signingKey and tag.gpgSign=false in config
  2839. cfg = self.repo.get_config()
  2840. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2841. cfg.set(("tag",), "gpgSign", False)
  2842. cfg.write_to_path()
  2843. self.import_default_key()
  2844. # Create tag without explicit sign parameter (should not sign)
  2845. porcelain.tag_create(
  2846. self.repo.path,
  2847. b"unsigned-tag",
  2848. b"foo <foo@bar.com>",
  2849. b"Unsigned tag",
  2850. annotated=True,
  2851. # No sign parameter - should use tag.gpgSign=false config
  2852. )
  2853. tags = self.repo.refs.as_dict(b"refs/tags")
  2854. self.assertEqual(list(tags.keys()), [b"unsigned-tag"])
  2855. tag = self.repo[b"refs/tags/unsigned-tag"]
  2856. self.assertIsInstance(tag, Tag)
  2857. # Verify the tag is not signed
  2858. self.assertIsNone(tag._signature)
  2859. def test_tag_gpg_sign_config_no_signing_key(self) -> None:
  2860. """Test that tag.gpgSign=true works without user.signingKey (uses default)."""
  2861. _c1, _c2, c3 = build_commit_graph(
  2862. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2863. )
  2864. self.repo.refs[b"HEAD"] = c3.id
  2865. # Set up tag.gpgSign but no user.signingKey
  2866. cfg = self.repo.get_config()
  2867. cfg.set(("tag",), "gpgSign", True)
  2868. cfg.write_to_path()
  2869. self.import_default_key()
  2870. # Create tag without explicit sign parameter (should auto-sign with default key)
  2871. porcelain.tag_create(
  2872. self.repo.path,
  2873. b"default-signed-tag",
  2874. b"foo <foo@bar.com>",
  2875. b"Default signed tag",
  2876. annotated=True,
  2877. # No sign parameter - should use tag.gpgSign config with default key
  2878. )
  2879. tags = self.repo.refs.as_dict(b"refs/tags")
  2880. self.assertEqual(list(tags.keys()), [b"default-signed-tag"])
  2881. tag = self.repo[b"refs/tags/default-signed-tag"]
  2882. self.assertIsInstance(tag, Tag)
  2883. # Verify the tag is signed with default key
  2884. tag.verify()
  2885. def test_explicit_sign_overrides_config(self) -> None:
  2886. """Test that explicit sign parameter overrides tag.gpgSign config."""
  2887. _c1, _c2, c3 = build_commit_graph(
  2888. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2889. )
  2890. self.repo.refs[b"HEAD"] = c3.id
  2891. # Set up tag.gpgSign=false but explicitly pass sign=True
  2892. cfg = self.repo.get_config()
  2893. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2894. cfg.set(("tag",), "gpgSign", False)
  2895. cfg.write_to_path()
  2896. self.import_default_key()
  2897. # Create tag with explicit sign=True (should override config)
  2898. porcelain.tag_create(
  2899. self.repo.path,
  2900. b"explicit-signed-tag",
  2901. b"foo <foo@bar.com>",
  2902. b"Explicitly signed tag",
  2903. annotated=True,
  2904. sign=True, # This should override tag.gpgSign=false
  2905. )
  2906. tags = self.repo.refs.as_dict(b"refs/tags")
  2907. self.assertEqual(list(tags.keys()), [b"explicit-signed-tag"])
  2908. tag = self.repo[b"refs/tags/explicit-signed-tag"]
  2909. self.assertIsInstance(tag, Tag)
  2910. # Verify the tag is signed despite config=false
  2911. tag.verify()
  2912. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2913. def test_explicit_false_disables_tag_signing(self) -> None:
  2914. """Test that explicit sign=False disables signing even with config=true."""
  2915. _c1, _c2, c3 = build_commit_graph(
  2916. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2917. )
  2918. self.repo.refs[b"HEAD"] = c3.id
  2919. # Set up tag.gpgSign=true but explicitly pass sign=False
  2920. cfg = self.repo.get_config()
  2921. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2922. cfg.set(("tag",), "gpgSign", True)
  2923. cfg.write_to_path()
  2924. self.import_default_key()
  2925. # Create tag with explicit sign=False (should disable signing)
  2926. porcelain.tag_create(
  2927. self.repo.path,
  2928. b"explicit-unsigned-tag",
  2929. b"foo <foo@bar.com>",
  2930. b"Explicitly unsigned tag",
  2931. annotated=True,
  2932. sign=False, # This should override tag.gpgSign=true
  2933. )
  2934. tags = self.repo.refs.as_dict(b"refs/tags")
  2935. self.assertEqual(list(tags.keys()), [b"explicit-unsigned-tag"])
  2936. tag = self.repo[b"refs/tags/explicit-unsigned-tag"]
  2937. self.assertIsInstance(tag, Tag)
  2938. # Verify the tag is NOT signed despite config=true
  2939. self.assertIsNone(tag._signature)
  2940. class TagCreateTests(PorcelainTestCase):
  2941. def test_annotated(self) -> None:
  2942. _c1, _c2, c3 = build_commit_graph(
  2943. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2944. )
  2945. self.repo.refs[b"HEAD"] = c3.id
  2946. porcelain.tag_create(
  2947. self.repo.path,
  2948. b"tryme",
  2949. b"foo <foo@bar.com>",
  2950. b"bar",
  2951. annotated=True,
  2952. )
  2953. tags = self.repo.refs.as_dict(b"refs/tags")
  2954. self.assertEqual(list(tags.keys()), [b"tryme"])
  2955. tag = self.repo[b"refs/tags/tryme"]
  2956. self.assertIsInstance(tag, Tag)
  2957. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2958. self.assertEqual(b"bar\n", tag.message)
  2959. self.assertRecentTimestamp(tag.tag_time)
  2960. def test_unannotated(self) -> None:
  2961. _c1, _c2, c3 = build_commit_graph(
  2962. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2963. )
  2964. self.repo.refs[b"HEAD"] = c3.id
  2965. porcelain.tag_create(self.repo.path, b"tryme", annotated=False)
  2966. tags = self.repo.refs.as_dict(b"refs/tags")
  2967. self.assertEqual(list(tags.keys()), [b"tryme"])
  2968. self.repo[b"refs/tags/tryme"]
  2969. self.assertEqual(list(tags.values()), [self.repo.head()])
  2970. def test_unannotated_unicode(self) -> None:
  2971. _c1, _c2, c3 = build_commit_graph(
  2972. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2973. )
  2974. self.repo.refs[b"HEAD"] = c3.id
  2975. porcelain.tag_create(self.repo.path, "tryme", annotated=False)
  2976. tags = self.repo.refs.as_dict(b"refs/tags")
  2977. self.assertEqual(list(tags.keys()), [b"tryme"])
  2978. self.repo[b"refs/tags/tryme"]
  2979. self.assertEqual(list(tags.values()), [self.repo.head()])
  2980. class TagListTests(PorcelainTestCase):
  2981. def test_empty(self) -> None:
  2982. tags = porcelain.tag_list(self.repo.path)
  2983. self.assertEqual([], tags)
  2984. def test_simple(self) -> None:
  2985. self.repo.refs[b"refs/tags/foo"] = b"aa" * 20
  2986. self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20
  2987. tags = porcelain.tag_list(self.repo.path)
  2988. self.assertEqual([b"bar/bla", b"foo"], tags)
  2989. class TagDeleteTests(PorcelainTestCase):
  2990. def test_simple(self) -> None:
  2991. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  2992. self.repo[b"HEAD"] = c1.id
  2993. porcelain.tag_create(self.repo, b"foo")
  2994. self.assertIn(b"foo", porcelain.tag_list(self.repo))
  2995. porcelain.tag_delete(self.repo, b"foo")
  2996. self.assertNotIn(b"foo", porcelain.tag_list(self.repo))
  2997. class ResetTests(PorcelainTestCase):
  2998. def test_hard_head(self) -> None:
  2999. fullpath = os.path.join(self.repo.path, "foo")
  3000. with open(fullpath, "w") as f:
  3001. f.write("BAR")
  3002. porcelain.add(self.repo.path, paths=[fullpath])
  3003. porcelain.commit(
  3004. self.repo.path,
  3005. message=b"Some message",
  3006. committer=b"Jane <jane@example.com>",
  3007. author=b"John <john@example.com>",
  3008. )
  3009. with open(os.path.join(self.repo.path, "foo"), "wb") as f:
  3010. f.write(b"OOH")
  3011. porcelain.reset(self.repo, "hard", b"HEAD")
  3012. index = self.repo.open_index()
  3013. changes = list(
  3014. tree_changes(
  3015. self.repo.object_store,
  3016. index.commit(self.repo.object_store),
  3017. self.repo[b"HEAD"].tree,
  3018. )
  3019. )
  3020. self.assertEqual([], changes)
  3021. def test_hard_commit(self) -> None:
  3022. fullpath = os.path.join(self.repo.path, "foo")
  3023. with open(fullpath, "w") as f:
  3024. f.write("BAR")
  3025. porcelain.add(self.repo.path, paths=[fullpath])
  3026. sha = porcelain.commit(
  3027. self.repo.path,
  3028. message=b"Some message",
  3029. committer=b"Jane <jane@example.com>",
  3030. author=b"John <john@example.com>",
  3031. )
  3032. with open(fullpath, "wb") as f:
  3033. f.write(b"BAZ")
  3034. porcelain.add(self.repo.path, paths=[fullpath])
  3035. porcelain.commit(
  3036. self.repo.path,
  3037. message=b"Some other message",
  3038. committer=b"Jane <jane@example.com>",
  3039. author=b"John <john@example.com>",
  3040. )
  3041. porcelain.reset(self.repo, "hard", sha)
  3042. index = self.repo.open_index()
  3043. changes = list(
  3044. tree_changes(
  3045. self.repo.object_store,
  3046. index.commit(self.repo.object_store),
  3047. self.repo[sha].tree,
  3048. )
  3049. )
  3050. self.assertEqual([], changes)
  3051. def test_hard_commit_short_hash(self) -> None:
  3052. fullpath = os.path.join(self.repo.path, "foo")
  3053. with open(fullpath, "w") as f:
  3054. f.write("BAR")
  3055. porcelain.add(self.repo.path, paths=[fullpath])
  3056. sha = porcelain.commit(
  3057. self.repo.path,
  3058. message=b"Some message",
  3059. committer=b"Jane <jane@example.com>",
  3060. author=b"John <john@example.com>",
  3061. )
  3062. with open(fullpath, "wb") as f:
  3063. f.write(b"BAZ")
  3064. porcelain.add(self.repo.path, paths=[fullpath])
  3065. porcelain.commit(
  3066. self.repo.path,
  3067. message=b"Some other message",
  3068. committer=b"Jane <jane@example.com>",
  3069. author=b"John <john@example.com>",
  3070. )
  3071. # Test with short hash (7 characters)
  3072. short_sha = sha[:7].decode("ascii")
  3073. porcelain.reset(self.repo, "hard", short_sha)
  3074. index = self.repo.open_index()
  3075. changes = list(
  3076. tree_changes(
  3077. self.repo.object_store,
  3078. index.commit(self.repo.object_store),
  3079. self.repo[sha].tree,
  3080. )
  3081. )
  3082. self.assertEqual([], changes)
  3083. def test_hard_deletes_untracked_files(self) -> None:
  3084. """Test that reset --hard deletes files that don't exist in target tree."""
  3085. # Create and commit a file
  3086. fullpath = os.path.join(self.repo.path, "foo")
  3087. with open(fullpath, "w") as f:
  3088. f.write("BAR")
  3089. porcelain.add(self.repo.path, paths=[fullpath])
  3090. sha1 = porcelain.commit(
  3091. self.repo.path,
  3092. message=b"First commit",
  3093. committer=b"Jane <jane@example.com>",
  3094. author=b"John <john@example.com>",
  3095. )
  3096. # Create another file and commit
  3097. fullpath2 = os.path.join(self.repo.path, "bar")
  3098. with open(fullpath2, "w") as f:
  3099. f.write("BAZ")
  3100. porcelain.add(self.repo.path, paths=[fullpath2])
  3101. porcelain.commit(
  3102. self.repo.path,
  3103. message=b"Second commit",
  3104. committer=b"Jane <jane@example.com>",
  3105. author=b"John <john@example.com>",
  3106. )
  3107. # Reset hard to first commit - this should delete 'bar'
  3108. porcelain.reset(self.repo, "hard", sha1)
  3109. # Check that 'foo' still exists and 'bar' is deleted
  3110. self.assertTrue(os.path.exists(fullpath))
  3111. self.assertFalse(os.path.exists(fullpath2))
  3112. # Check index matches first commit
  3113. index = self.repo.open_index()
  3114. self.assertIn(b"foo", index)
  3115. self.assertNotIn(b"bar", index)
  3116. def test_hard_deletes_files_in_subdirs(self) -> None:
  3117. """Test that reset --hard deletes files in subdirectories."""
  3118. # Create and commit files in subdirectory
  3119. subdir = os.path.join(self.repo.path, "subdir")
  3120. os.makedirs(subdir)
  3121. file1 = os.path.join(subdir, "file1")
  3122. file2 = os.path.join(subdir, "file2")
  3123. with open(file1, "w") as f:
  3124. f.write("content1")
  3125. with open(file2, "w") as f:
  3126. f.write("content2")
  3127. porcelain.add(self.repo.path, paths=[file1, file2])
  3128. porcelain.commit(
  3129. self.repo.path,
  3130. message=b"First commit",
  3131. committer=b"Jane <jane@example.com>",
  3132. author=b"John <john@example.com>",
  3133. )
  3134. # Remove one file from subdirectory and commit
  3135. porcelain.rm(self.repo.path, paths=[file2])
  3136. sha2 = porcelain.commit(
  3137. self.repo.path,
  3138. message=b"Remove file2",
  3139. committer=b"Jane <jane@example.com>",
  3140. author=b"John <john@example.com>",
  3141. )
  3142. # Create file2 again (untracked)
  3143. with open(file2, "w") as f:
  3144. f.write("new content")
  3145. # Reset to commit that has file2 removed - untracked file2 should remain
  3146. porcelain.reset(self.repo, "hard", sha2)
  3147. self.assertTrue(os.path.exists(file1))
  3148. # Untracked files are not removed by reset --hard
  3149. self.assertTrue(os.path.exists(file2))
  3150. def test_hard_reset_to_remote_branch(self) -> None:
  3151. """Test reset --hard to remote branch deletes local files not in remote."""
  3152. # Create a file and commit
  3153. file1 = os.path.join(self.repo.path, "file1")
  3154. with open(file1, "w") as f:
  3155. f.write("content1")
  3156. porcelain.add(self.repo.path, paths=[file1])
  3157. sha1 = porcelain.commit(
  3158. self.repo.path,
  3159. message=b"Initial commit",
  3160. committer=b"Jane <jane@example.com>",
  3161. author=b"John <john@example.com>",
  3162. )
  3163. # Create a "remote" ref that doesn't have additional files
  3164. self.repo.refs[b"refs/remotes/origin/master"] = sha1
  3165. # Add another file locally and commit
  3166. file2 = os.path.join(self.repo.path, "file2")
  3167. with open(file2, "w") as f:
  3168. f.write("content2")
  3169. porcelain.add(self.repo.path, paths=[file2])
  3170. porcelain.commit(
  3171. self.repo.path,
  3172. message=b"Add file2",
  3173. committer=b"Jane <jane@example.com>",
  3174. author=b"John <john@example.com>",
  3175. )
  3176. # Both files should exist
  3177. self.assertTrue(os.path.exists(file1))
  3178. self.assertTrue(os.path.exists(file2))
  3179. # Reset to remote branch - should delete file2
  3180. porcelain.reset(self.repo, "hard", b"refs/remotes/origin/master")
  3181. # file1 should exist, file2 should be deleted
  3182. self.assertTrue(os.path.exists(file1))
  3183. self.assertFalse(os.path.exists(file2))
  3184. def test_mixed_reset(self) -> None:
  3185. # Create initial commit
  3186. fullpath = os.path.join(self.repo.path, "foo")
  3187. with open(fullpath, "w") as f:
  3188. f.write("BAR")
  3189. porcelain.add(self.repo.path, paths=[fullpath])
  3190. first_sha = porcelain.commit(
  3191. self.repo.path,
  3192. message=b"First commit",
  3193. committer=b"Jane <jane@example.com>",
  3194. author=b"John <john@example.com>",
  3195. )
  3196. # Make second commit with modified content
  3197. with open(fullpath, "w") as f:
  3198. f.write("BAZ")
  3199. porcelain.add(self.repo.path, paths=[fullpath])
  3200. porcelain.commit(
  3201. self.repo.path,
  3202. message=b"Second commit",
  3203. committer=b"Jane <jane@example.com>",
  3204. author=b"John <john@example.com>",
  3205. )
  3206. # Modify working tree without staging
  3207. with open(fullpath, "w") as f:
  3208. f.write("MODIFIED")
  3209. # Mixed reset to first commit
  3210. porcelain.reset(self.repo, "mixed", first_sha)
  3211. # Check that HEAD points to first commit
  3212. self.assertEqual(self.repo.head(), first_sha)
  3213. # Check that index matches first commit
  3214. index = self.repo.open_index()
  3215. changes = list(
  3216. tree_changes(
  3217. self.repo.object_store,
  3218. index.commit(self.repo.object_store),
  3219. self.repo[first_sha].tree,
  3220. )
  3221. )
  3222. self.assertEqual([], changes)
  3223. # Check that working tree is unchanged (still has "MODIFIED")
  3224. with open(fullpath) as f:
  3225. self.assertEqual(f.read(), "MODIFIED")
  3226. def test_soft_reset(self) -> None:
  3227. # Create initial commit
  3228. fullpath = os.path.join(self.repo.path, "foo")
  3229. with open(fullpath, "w") as f:
  3230. f.write("BAR")
  3231. porcelain.add(self.repo.path, paths=[fullpath])
  3232. first_sha = porcelain.commit(
  3233. self.repo.path,
  3234. message=b"First commit",
  3235. committer=b"Jane <jane@example.com>",
  3236. author=b"John <john@example.com>",
  3237. )
  3238. # Make second commit with modified content
  3239. with open(fullpath, "w") as f:
  3240. f.write("BAZ")
  3241. porcelain.add(self.repo.path, paths=[fullpath])
  3242. porcelain.commit(
  3243. self.repo.path,
  3244. message=b"Second commit",
  3245. committer=b"Jane <jane@example.com>",
  3246. author=b"John <john@example.com>",
  3247. )
  3248. # Stage a new change
  3249. with open(fullpath, "w") as f:
  3250. f.write("STAGED")
  3251. porcelain.add(self.repo.path, paths=[fullpath])
  3252. # Soft reset to first commit
  3253. porcelain.reset(self.repo, "soft", first_sha)
  3254. # Check that HEAD points to first commit
  3255. self.assertEqual(self.repo.head(), first_sha)
  3256. # Check that index still has the staged change (not reset)
  3257. index = self.repo.open_index()
  3258. # The index should still contain the staged content, not the first commit's content
  3259. self.assertIn(b"foo", index)
  3260. # Check that working tree is unchanged
  3261. with open(fullpath) as f:
  3262. self.assertEqual(f.read(), "STAGED")
  3263. class ResetFileTests(PorcelainTestCase):
  3264. def test_reset_modify_file_to_commit(self) -> None:
  3265. file = "foo"
  3266. full_path = os.path.join(self.repo.path, file)
  3267. with open(full_path, "w") as f:
  3268. f.write("hello")
  3269. porcelain.add(self.repo, paths=[full_path])
  3270. sha = porcelain.commit(
  3271. self.repo,
  3272. message=b"unitest",
  3273. committer=b"Jane <jane@example.com>",
  3274. author=b"John <john@example.com>",
  3275. )
  3276. with open(full_path, "a") as f:
  3277. f.write("something new")
  3278. porcelain.reset_file(self.repo, file, target=sha)
  3279. with open(full_path) as f:
  3280. self.assertEqual("hello", f.read())
  3281. def test_reset_remove_file_to_commit(self) -> None:
  3282. file = "foo"
  3283. full_path = os.path.join(self.repo.path, file)
  3284. with open(full_path, "w") as f:
  3285. f.write("hello")
  3286. porcelain.add(self.repo, paths=[full_path])
  3287. sha = porcelain.commit(
  3288. self.repo,
  3289. message=b"unitest",
  3290. committer=b"Jane <jane@example.com>",
  3291. author=b"John <john@example.com>",
  3292. )
  3293. os.remove(full_path)
  3294. porcelain.reset_file(self.repo, file, target=sha)
  3295. with open(full_path) as f:
  3296. self.assertEqual("hello", f.read())
  3297. def test_resetfile_with_dir(self) -> None:
  3298. os.mkdir(os.path.join(self.repo.path, "new_dir"))
  3299. full_path = os.path.join(self.repo.path, "new_dir", "foo")
  3300. with open(full_path, "w") as f:
  3301. f.write("hello")
  3302. porcelain.add(self.repo, paths=[full_path])
  3303. sha = porcelain.commit(
  3304. self.repo,
  3305. message=b"unitest",
  3306. committer=b"Jane <jane@example.com>",
  3307. author=b"John <john@example.com>",
  3308. )
  3309. with open(full_path, "a") as f:
  3310. f.write("something new")
  3311. porcelain.commit(
  3312. self.repo,
  3313. message=b"unitest 2",
  3314. committer=b"Jane <jane@example.com>",
  3315. author=b"John <john@example.com>",
  3316. )
  3317. porcelain.reset_file(self.repo, os.path.join("new_dir", "foo"), target=sha)
  3318. with open(full_path) as f:
  3319. self.assertEqual("hello", f.read())
  3320. def _commit_file_with_content(repo, filename, content):
  3321. file_path = os.path.join(repo.path, filename)
  3322. with open(file_path, "w") as f:
  3323. f.write(content)
  3324. porcelain.add(repo, paths=[file_path])
  3325. sha = porcelain.commit(
  3326. repo,
  3327. message=b"add " + filename.encode(),
  3328. committer=b"Jane <jane@example.com>",
  3329. author=b"John <john@example.com>",
  3330. )
  3331. return sha, file_path
  3332. class RevertTests(PorcelainTestCase):
  3333. def test_revert_simple(self) -> None:
  3334. # Create initial commit
  3335. fullpath = os.path.join(self.repo.path, "foo")
  3336. with open(fullpath, "w") as f:
  3337. f.write("initial content\n")
  3338. porcelain.add(self.repo.path, paths=[fullpath])
  3339. porcelain.commit(
  3340. self.repo.path,
  3341. message=b"Initial commit",
  3342. committer=b"Jane <jane@example.com>",
  3343. author=b"John <john@example.com>",
  3344. )
  3345. # Make a change
  3346. with open(fullpath, "w") as f:
  3347. f.write("modified content\n")
  3348. porcelain.add(self.repo.path, paths=[fullpath])
  3349. change_sha = porcelain.commit(
  3350. self.repo.path,
  3351. message=b"Change content",
  3352. committer=b"Jane <jane@example.com>",
  3353. author=b"John <john@example.com>",
  3354. )
  3355. # Revert the change
  3356. revert_sha = porcelain.revert(self.repo.path, commits=[change_sha])
  3357. # Check the file content is back to initial
  3358. with open(fullpath) as f:
  3359. self.assertEqual("initial content\n", f.read())
  3360. # Check the revert commit message
  3361. revert_commit = self.repo[revert_sha]
  3362. self.assertIn(b'Revert "Change content"', revert_commit.message)
  3363. self.assertIn(change_sha[:7], revert_commit.message)
  3364. def test_revert_multiple(self) -> None:
  3365. # Create initial commit
  3366. fullpath = os.path.join(self.repo.path, "foo")
  3367. with open(fullpath, "w") as f:
  3368. f.write("line1\n")
  3369. porcelain.add(self.repo.path, paths=[fullpath])
  3370. porcelain.commit(
  3371. self.repo.path,
  3372. message=b"Initial commit",
  3373. committer=b"Jane <jane@example.com>",
  3374. author=b"John <john@example.com>",
  3375. )
  3376. # Add line2
  3377. with open(fullpath, "a") as f:
  3378. f.write("line2\n")
  3379. porcelain.add(self.repo.path, paths=[fullpath])
  3380. commit1 = porcelain.commit(
  3381. self.repo.path,
  3382. message=b"Add line2",
  3383. committer=b"Jane <jane@example.com>",
  3384. author=b"John <john@example.com>",
  3385. )
  3386. # Add line3
  3387. with open(fullpath, "a") as f:
  3388. f.write("line3\n")
  3389. porcelain.add(self.repo.path, paths=[fullpath])
  3390. commit2 = porcelain.commit(
  3391. self.repo.path,
  3392. message=b"Add line3",
  3393. committer=b"Jane <jane@example.com>",
  3394. author=b"John <john@example.com>",
  3395. )
  3396. # Revert both commits (in reverse order)
  3397. porcelain.revert(self.repo.path, commits=[commit2, commit1])
  3398. # Check file is back to initial state
  3399. with open(fullpath) as f:
  3400. self.assertEqual("line1\n", f.read())
  3401. def test_revert_no_commit(self) -> None:
  3402. # Create initial commit
  3403. fullpath = os.path.join(self.repo.path, "foo")
  3404. with open(fullpath, "w") as f:
  3405. f.write("initial\n")
  3406. porcelain.add(self.repo.path, paths=[fullpath])
  3407. porcelain.commit(
  3408. self.repo.path,
  3409. message=b"Initial",
  3410. committer=b"Jane <jane@example.com>",
  3411. author=b"John <john@example.com>",
  3412. )
  3413. # Make a change
  3414. with open(fullpath, "w") as f:
  3415. f.write("changed\n")
  3416. porcelain.add(self.repo.path, paths=[fullpath])
  3417. change_sha = porcelain.commit(
  3418. self.repo.path,
  3419. message=b"Change",
  3420. committer=b"Jane <jane@example.com>",
  3421. author=b"John <john@example.com>",
  3422. )
  3423. # Revert with no_commit
  3424. result = porcelain.revert(self.repo.path, commits=[change_sha], no_commit=True)
  3425. # Should return None
  3426. self.assertIsNone(result)
  3427. # File should be reverted
  3428. with open(fullpath) as f:
  3429. self.assertEqual("initial\n", f.read())
  3430. # HEAD should still point to the change commit
  3431. self.assertEqual(self.repo.refs[b"HEAD"], change_sha)
  3432. def test_revert_custom_message(self) -> None:
  3433. # Create commits
  3434. fullpath = os.path.join(self.repo.path, "foo")
  3435. with open(fullpath, "w") as f:
  3436. f.write("initial\n")
  3437. porcelain.add(self.repo.path, paths=[fullpath])
  3438. porcelain.commit(
  3439. self.repo.path,
  3440. message=b"Initial",
  3441. committer=b"Jane <jane@example.com>",
  3442. author=b"John <john@example.com>",
  3443. )
  3444. with open(fullpath, "w") as f:
  3445. f.write("changed\n")
  3446. porcelain.add(self.repo.path, paths=[fullpath])
  3447. change_sha = porcelain.commit(
  3448. self.repo.path,
  3449. message=b"Change",
  3450. committer=b"Jane <jane@example.com>",
  3451. author=b"John <john@example.com>",
  3452. )
  3453. # Revert with custom message
  3454. custom_msg = "Custom revert message"
  3455. revert_sha = porcelain.revert(
  3456. self.repo.path, commits=[change_sha], message=custom_msg
  3457. )
  3458. # Check the message
  3459. revert_commit = self.repo[revert_sha]
  3460. self.assertEqual(custom_msg.encode("utf-8"), revert_commit.message)
  3461. def test_revert_no_parent(self) -> None:
  3462. # Try to revert the initial commit (no parent)
  3463. fullpath = os.path.join(self.repo.path, "foo")
  3464. with open(fullpath, "w") as f:
  3465. f.write("content\n")
  3466. porcelain.add(self.repo.path, paths=[fullpath])
  3467. initial_sha = porcelain.commit(
  3468. self.repo.path,
  3469. message=b"Initial",
  3470. committer=b"Jane <jane@example.com>",
  3471. author=b"John <john@example.com>",
  3472. )
  3473. # Should raise an error
  3474. with self.assertRaises(porcelain.Error) as cm:
  3475. porcelain.revert(self.repo.path, commits=[initial_sha])
  3476. self.assertIn("no parents", str(cm.exception))
  3477. class CheckoutTests(PorcelainTestCase):
  3478. def setUp(self) -> None:
  3479. super().setUp()
  3480. self._sha, self._foo_path = _commit_file_with_content(
  3481. self.repo, "foo", "hello\n"
  3482. )
  3483. porcelain.branch_create(self.repo, "uni")
  3484. def test_checkout_to_existing_branch(self) -> None:
  3485. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3486. porcelain.checkout(self.repo, b"uni")
  3487. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3488. def test_checkout_to_non_existing_branch(self) -> None:
  3489. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3490. with self.assertRaises(KeyError):
  3491. porcelain.checkout(self.repo, b"bob")
  3492. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3493. def test_checkout_to_branch_with_modified_files(self) -> None:
  3494. with open(self._foo_path, "a") as f:
  3495. f.write("new message\n")
  3496. porcelain.add(self.repo, paths=[self._foo_path])
  3497. status = list(porcelain.status(self.repo))
  3498. self.assertEqual(
  3499. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  3500. )
  3501. # The new checkout behavior prevents switching with staged changes
  3502. with self.assertRaises(porcelain.CheckoutError):
  3503. porcelain.checkout(self.repo, b"uni")
  3504. # Should still be on master
  3505. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3506. # Force checkout should work
  3507. porcelain.checkout(self.repo, b"uni", force=True)
  3508. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3509. def test_checkout_with_deleted_files(self) -> None:
  3510. porcelain.remove(self.repo.path, [os.path.join(self.repo.path, "foo")])
  3511. status = list(porcelain.status(self.repo))
  3512. self.assertEqual(
  3513. [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status
  3514. )
  3515. # The new checkout behavior prevents switching with staged deletions
  3516. with self.assertRaises(porcelain.CheckoutError):
  3517. porcelain.checkout(self.repo, b"uni")
  3518. # Should still be on master
  3519. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3520. # Force checkout should work
  3521. porcelain.checkout(self.repo, b"uni", force=True)
  3522. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3523. def test_checkout_to_branch_with_added_files(self) -> None:
  3524. file_path = os.path.join(self.repo.path, "bar")
  3525. with open(file_path, "w") as f:
  3526. f.write("bar content\n")
  3527. porcelain.add(self.repo, paths=[file_path])
  3528. status = list(porcelain.status(self.repo))
  3529. self.assertEqual(
  3530. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3531. )
  3532. # Both branches have file 'foo' checkout should be fine.
  3533. porcelain.checkout(self.repo, b"uni")
  3534. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3535. status = list(porcelain.status(self.repo))
  3536. self.assertEqual(
  3537. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3538. )
  3539. def test_checkout_to_branch_with_modified_file_not_present(self) -> None:
  3540. # Commit a new file that the other branch doesn't have.
  3541. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3542. # Modify the file the other branch doesn't have.
  3543. with open(nee_path, "a") as f:
  3544. f.write("bar content\n")
  3545. porcelain.add(self.repo, paths=[nee_path])
  3546. status = list(porcelain.status(self.repo))
  3547. self.assertEqual(
  3548. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3549. )
  3550. # Checkout should fail when there are staged changes that would be lost
  3551. # This matches Git's behavior to prevent data loss
  3552. from dulwich.errors import WorkingTreeModifiedError
  3553. with self.assertRaises(WorkingTreeModifiedError) as cm:
  3554. porcelain.checkout(self.repo, b"uni")
  3555. self.assertIn("nee", str(cm.exception))
  3556. # Should still be on master branch
  3557. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3558. # The staged changes should still be present
  3559. status = list(porcelain.status(self.repo))
  3560. self.assertEqual(
  3561. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3562. )
  3563. self.assertTrue(os.path.exists(nee_path))
  3564. # Force checkout should work and lose the changes
  3565. porcelain.checkout(self.repo, b"uni", force=True)
  3566. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3567. # Now the file should be gone
  3568. self.assertFalse(os.path.exists(nee_path))
  3569. def test_checkout_to_branch_with_modified_file_not_present_forced(self) -> None:
  3570. # Commit a new file that the other branch doesn't have.
  3571. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3572. # Modify the file the other branch doesn't have.
  3573. with open(nee_path, "a") as f:
  3574. f.write("bar content\n")
  3575. porcelain.add(self.repo, paths=[nee_path])
  3576. status = list(porcelain.status(self.repo))
  3577. self.assertEqual(
  3578. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3579. )
  3580. # 'uni' branch doesn't have 'nee' and it has been modified, but we force to reset the entire index.
  3581. porcelain.checkout(self.repo, b"uni", force=True)
  3582. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3583. status = list(porcelain.status(self.repo))
  3584. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3585. def test_checkout_to_branch_with_unstaged_files(self) -> None:
  3586. # Edit `foo`.
  3587. with open(self._foo_path, "a") as f:
  3588. f.write("new message")
  3589. status = list(porcelain.status(self.repo))
  3590. self.assertEqual(
  3591. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  3592. )
  3593. # The new checkout behavior prevents switching with unstaged changes
  3594. with self.assertRaises(porcelain.CheckoutError):
  3595. porcelain.checkout(self.repo, b"uni")
  3596. # Should still be on master
  3597. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3598. # Force checkout should work
  3599. porcelain.checkout(self.repo, b"uni", force=True)
  3600. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3601. def test_checkout_to_branch_with_untracked_files(self) -> None:
  3602. with open(os.path.join(self.repo.path, "neu"), "a") as f:
  3603. f.write("new message\n")
  3604. status = list(porcelain.status(self.repo))
  3605. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3606. porcelain.checkout(self.repo, b"uni")
  3607. status = list(porcelain.status(self.repo))
  3608. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3609. def test_checkout_to_branch_with_new_files(self) -> None:
  3610. porcelain.checkout(self.repo, b"uni")
  3611. sub_directory = os.path.join(self.repo.path, "sub1")
  3612. os.mkdir(sub_directory)
  3613. for index in range(5):
  3614. _commit_file_with_content(
  3615. self.repo, "new_file_" + str(index + 1), "Some content\n"
  3616. )
  3617. _commit_file_with_content(
  3618. self.repo,
  3619. os.path.join("sub1", "new_file_" + str(index + 10)),
  3620. "Good content\n",
  3621. )
  3622. status = list(porcelain.status(self.repo))
  3623. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3624. porcelain.checkout(self.repo, b"master")
  3625. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3626. status = list(porcelain.status(self.repo))
  3627. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3628. porcelain.checkout(self.repo, b"uni")
  3629. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3630. status = list(porcelain.status(self.repo))
  3631. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3632. def test_checkout_to_branch_with_file_in_sub_directory(self) -> None:
  3633. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3634. os.makedirs(sub_directory)
  3635. sub_directory_file = os.path.join(sub_directory, "neu")
  3636. with open(sub_directory_file, "w") as f:
  3637. f.write("new message\n")
  3638. porcelain.add(self.repo, paths=[sub_directory_file])
  3639. porcelain.commit(
  3640. self.repo,
  3641. message=b"add " + sub_directory_file.encode(),
  3642. committer=b"Jane <jane@example.com>",
  3643. author=b"John <john@example.com>",
  3644. )
  3645. status = list(porcelain.status(self.repo))
  3646. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3647. self.assertTrue(os.path.isdir(sub_directory))
  3648. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3649. porcelain.checkout(self.repo, b"uni")
  3650. status = list(porcelain.status(self.repo))
  3651. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3652. self.assertFalse(os.path.isdir(sub_directory))
  3653. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3654. porcelain.checkout(self.repo, b"master")
  3655. self.assertTrue(os.path.isdir(sub_directory))
  3656. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3657. def test_checkout_to_branch_with_multiple_files_in_sub_directory(self) -> None:
  3658. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3659. os.makedirs(sub_directory)
  3660. sub_directory_file_1 = os.path.join(sub_directory, "neu")
  3661. with open(sub_directory_file_1, "w") as f:
  3662. f.write("new message\n")
  3663. sub_directory_file_2 = os.path.join(sub_directory, "gus")
  3664. with open(sub_directory_file_2, "w") as f:
  3665. f.write("alternative message\n")
  3666. porcelain.add(self.repo, paths=[sub_directory_file_1, sub_directory_file_2])
  3667. porcelain.commit(
  3668. self.repo,
  3669. message=b"add files neu and gus.",
  3670. committer=b"Jane <jane@example.com>",
  3671. author=b"John <john@example.com>",
  3672. )
  3673. status = list(porcelain.status(self.repo))
  3674. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3675. self.assertTrue(os.path.isdir(sub_directory))
  3676. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3677. porcelain.checkout(self.repo, b"uni")
  3678. status = list(porcelain.status(self.repo))
  3679. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3680. self.assertFalse(os.path.isdir(sub_directory))
  3681. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3682. def _commit_something_wrong(self):
  3683. with open(self._foo_path, "a") as f:
  3684. f.write("something wrong")
  3685. porcelain.add(self.repo, paths=[self._foo_path])
  3686. return porcelain.commit(
  3687. self.repo,
  3688. message=b"I may added something wrong",
  3689. committer=b"Jane <jane@example.com>",
  3690. author=b"John <john@example.com>",
  3691. )
  3692. def test_checkout_to_commit_sha(self) -> None:
  3693. self._commit_something_wrong()
  3694. porcelain.checkout(self.repo, self._sha)
  3695. self.assertEqual(self._sha, self.repo.head())
  3696. def test_checkout_to_head(self) -> None:
  3697. new_sha = self._commit_something_wrong()
  3698. porcelain.checkout(self.repo, b"HEAD")
  3699. self.assertEqual(new_sha, self.repo.head())
  3700. def _checkout_remote_branch(self):
  3701. errstream = BytesIO()
  3702. outstream = BytesIO()
  3703. porcelain.commit(
  3704. repo=self.repo.path,
  3705. message=b"init",
  3706. author=b"author <email>",
  3707. committer=b"committer <email>",
  3708. )
  3709. # Setup target repo cloned from temp test repo
  3710. clone_path = tempfile.mkdtemp()
  3711. self.addCleanup(shutil.rmtree, clone_path)
  3712. target_repo = porcelain.clone(
  3713. self.repo.path, target=clone_path, errstream=errstream
  3714. )
  3715. self.addCleanup(target_repo.close)
  3716. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  3717. # create a second file to be pushed back to origin
  3718. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3719. os.close(handle)
  3720. porcelain.add(repo=clone_path, paths=[fullpath])
  3721. porcelain.commit(
  3722. repo=clone_path,
  3723. message=b"push",
  3724. author=b"author <email>",
  3725. committer=b"committer <email>",
  3726. )
  3727. # Setup a non-checked out branch in the remote
  3728. refs_path = b"refs/heads/foo"
  3729. new_id = self.repo[b"HEAD"].id
  3730. self.assertNotEqual(new_id, ZERO_SHA)
  3731. self.repo.refs[refs_path] = new_id
  3732. # Push to the remote
  3733. porcelain.push(
  3734. clone_path,
  3735. "origin",
  3736. b"HEAD:" + refs_path,
  3737. outstream=outstream,
  3738. errstream=errstream,
  3739. )
  3740. self.assertEqual(
  3741. target_repo.refs[b"refs/remotes/origin/foo"],
  3742. target_repo.refs[b"HEAD"],
  3743. )
  3744. # The new checkout behavior treats origin/foo as a ref and creates detached HEAD
  3745. porcelain.checkout(target_repo, b"origin/foo")
  3746. original_id = target_repo[b"HEAD"].id
  3747. uni_id = target_repo[b"refs/remotes/origin/uni"].id
  3748. # Should be in detached HEAD state
  3749. with self.assertRaises((ValueError, IndexError)):
  3750. porcelain.active_branch(target_repo)
  3751. expected_refs = {
  3752. b"HEAD": original_id,
  3753. b"refs/heads/master": original_id,
  3754. # No local foo branch is created anymore
  3755. b"refs/remotes/origin/foo": original_id,
  3756. b"refs/remotes/origin/uni": uni_id,
  3757. b"refs/remotes/origin/HEAD": new_id,
  3758. b"refs/remotes/origin/master": new_id,
  3759. }
  3760. self.assertEqual(expected_refs, target_repo.get_refs())
  3761. return target_repo
  3762. def test_checkout_remote_branch(self) -> None:
  3763. repo = self._checkout_remote_branch()
  3764. repo.close()
  3765. def test_checkout_remote_branch_then_master_then_remote_branch_again(self) -> None:
  3766. target_repo = self._checkout_remote_branch()
  3767. # Should be in detached HEAD state
  3768. with self.assertRaises((ValueError, IndexError)):
  3769. porcelain.active_branch(target_repo)
  3770. # Save the commit SHA before adding bar
  3771. detached_commit_sha, _ = _commit_file_with_content(
  3772. target_repo, "bar", "something\n"
  3773. )
  3774. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3775. porcelain.checkout(target_repo, b"master")
  3776. self.assertEqual(b"master", porcelain.active_branch(target_repo))
  3777. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3778. # Going back to origin/foo won't have bar because the commit was made in detached state
  3779. porcelain.checkout(target_repo, b"origin/foo")
  3780. # Should be in detached HEAD state again
  3781. with self.assertRaises((ValueError, IndexError)):
  3782. porcelain.active_branch(target_repo)
  3783. # bar is NOT there because we're back at the original origin/foo commit
  3784. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3785. # But we can checkout the specific commit to get bar back
  3786. porcelain.checkout(target_repo, detached_commit_sha.decode())
  3787. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3788. target_repo.close()
  3789. def test_checkout_new_branch_from_remote_sets_tracking(self) -> None:
  3790. # Create a "remote" repository
  3791. remote_path = tempfile.mkdtemp()
  3792. self.addCleanup(shutil.rmtree, remote_path)
  3793. remote_repo = porcelain.init(remote_path)
  3794. # Add a commit to the remote
  3795. remote_sha, _ = _commit_file_with_content(
  3796. remote_repo, "bar", "remote content\n"
  3797. )
  3798. # Clone the remote repository
  3799. target_path = tempfile.mkdtemp()
  3800. self.addCleanup(shutil.rmtree, target_path)
  3801. target_repo = porcelain.clone(remote_path, target_path)
  3802. self.addCleanup(target_repo.close)
  3803. # Create a remote tracking branch reference
  3804. remote_branch_ref = b"refs/remotes/origin/feature"
  3805. target_repo.refs[remote_branch_ref] = remote_sha
  3806. # Checkout a new branch from the remote branch
  3807. porcelain.checkout(target_repo, remote_branch_ref, new_branch=b"local-feature")
  3808. # Verify the branch was created and is active
  3809. self.assertEqual(b"local-feature", porcelain.active_branch(target_repo))
  3810. # Verify tracking configuration was set
  3811. config = target_repo.get_config()
  3812. self.assertEqual(
  3813. b"origin", config.get((b"branch", b"local-feature"), b"remote")
  3814. )
  3815. self.assertEqual(
  3816. b"refs/heads/feature", config.get((b"branch", b"local-feature"), b"merge")
  3817. )
  3818. target_repo.close()
  3819. remote_repo.close()
  3820. class GeneralCheckoutTests(PorcelainTestCase):
  3821. """Tests for the general checkout function that handles branches, tags, and commits."""
  3822. def setUp(self) -> None:
  3823. super().setUp()
  3824. # Create initial commit
  3825. self._sha1, self._foo_path = _commit_file_with_content(
  3826. self.repo, "foo", "initial content\n"
  3827. )
  3828. # Create a branch
  3829. porcelain.branch_create(self.repo, "feature")
  3830. # Create another commit on master
  3831. self._sha2, self._bar_path = _commit_file_with_content(
  3832. self.repo, "bar", "bar content\n"
  3833. )
  3834. # Create a tag
  3835. porcelain.tag_create(self.repo, "v1.0", objectish=self._sha1)
  3836. def test_checkout_branch(self) -> None:
  3837. """Test checking out a branch."""
  3838. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3839. # Checkout feature branch
  3840. porcelain.checkout(self.repo, "feature")
  3841. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3842. # File 'bar' should not exist in feature branch
  3843. self.assertFalse(os.path.exists(self._bar_path))
  3844. # Go back to master
  3845. porcelain.checkout(self.repo, "master")
  3846. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3847. # File 'bar' should exist again
  3848. self.assertTrue(os.path.exists(self._bar_path))
  3849. def test_checkout_commit(self) -> None:
  3850. """Test checking out a specific commit (detached HEAD)."""
  3851. # Checkout first commit by SHA
  3852. porcelain.checkout(self.repo, self._sha1.decode("ascii"))
  3853. # Should be in detached HEAD state - active_branch raises IndexError
  3854. with self.assertRaises((ValueError, IndexError)):
  3855. porcelain.active_branch(self.repo)
  3856. # File 'bar' should not exist
  3857. self.assertFalse(os.path.exists(self._bar_path))
  3858. # HEAD should point to the commit
  3859. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3860. def test_checkout_tag(self) -> None:
  3861. """Test checking out a tag (detached HEAD)."""
  3862. # Checkout tag
  3863. porcelain.checkout(self.repo, "v1.0")
  3864. # Should be in detached HEAD state - active_branch raises IndexError
  3865. with self.assertRaises((ValueError, IndexError)):
  3866. porcelain.active_branch(self.repo)
  3867. # File 'bar' should not exist (tag points to first commit)
  3868. self.assertFalse(os.path.exists(self._bar_path))
  3869. # HEAD should point to the tagged commit
  3870. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3871. def test_checkout_new_branch(self) -> None:
  3872. """Test creating a new branch during checkout (like git checkout -b)."""
  3873. # Create and checkout new branch from current HEAD
  3874. porcelain.checkout(self.repo, "master", new_branch="new-feature")
  3875. self.assertEqual(b"new-feature", porcelain.active_branch(self.repo))
  3876. self.assertTrue(os.path.exists(self._bar_path))
  3877. # Create and checkout new branch from specific commit
  3878. porcelain.checkout(self.repo, self._sha1.decode("ascii"), new_branch="from-old")
  3879. self.assertEqual(b"from-old", porcelain.active_branch(self.repo))
  3880. self.assertFalse(os.path.exists(self._bar_path))
  3881. def test_checkout_with_uncommitted_changes(self) -> None:
  3882. """Test checkout behavior with uncommitted changes."""
  3883. # Modify a file
  3884. with open(self._foo_path, "w") as f:
  3885. f.write("modified content\n")
  3886. # Should raise error when trying to checkout
  3887. with self.assertRaises(porcelain.CheckoutError) as cm:
  3888. porcelain.checkout(self.repo, "feature")
  3889. self.assertIn("local changes", str(cm.exception))
  3890. self.assertIn("foo", str(cm.exception))
  3891. # Should still be on master
  3892. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3893. def test_checkout_force(self) -> None:
  3894. """Test forced checkout discards local changes for files that differ between branches."""
  3895. # Modify a file
  3896. with open(self._foo_path, "w") as f:
  3897. f.write("modified content\n")
  3898. # Force checkout should succeed
  3899. porcelain.checkout(self.repo, "feature", force=True)
  3900. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3901. # Since foo has the same content in master and feature branches,
  3902. # checkout should NOT restore it - the modified content should remain
  3903. with open(self._foo_path) as f:
  3904. content = f.read()
  3905. self.assertEqual("modified content\n", content)
  3906. def test_checkout_nonexistent_ref(self) -> None:
  3907. """Test checkout of non-existent branch/commit."""
  3908. with self.assertRaises(KeyError):
  3909. porcelain.checkout(self.repo, "nonexistent")
  3910. def test_checkout_partial_sha(self) -> None:
  3911. """Test checkout with partial SHA."""
  3912. # Git typically allows checkout with partial SHA
  3913. partial_sha = self._sha1.decode("ascii")[:7]
  3914. porcelain.checkout(self.repo, partial_sha)
  3915. # Should be in detached HEAD state at the right commit
  3916. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3917. def test_checkout_preserves_untracked_files(self) -> None:
  3918. """Test that checkout preserves untracked files."""
  3919. # Create an untracked file
  3920. untracked_path = os.path.join(self.repo.path, "untracked.txt")
  3921. with open(untracked_path, "w") as f:
  3922. f.write("untracked content\n")
  3923. # Checkout another branch
  3924. porcelain.checkout(self.repo, "feature")
  3925. # Untracked file should still exist
  3926. self.assertTrue(os.path.exists(untracked_path))
  3927. with open(untracked_path) as f:
  3928. content = f.read()
  3929. self.assertEqual("untracked content\n", content)
  3930. def test_checkout_full_ref_paths(self) -> None:
  3931. """Test checkout with full ref paths."""
  3932. # Test checkout with full branch ref path
  3933. porcelain.checkout(self.repo, "refs/heads/feature")
  3934. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3935. # Test checkout with full tag ref path
  3936. porcelain.checkout(self.repo, "refs/tags/v1.0")
  3937. # Should be in detached HEAD state
  3938. with self.assertRaises((ValueError, IndexError)):
  3939. porcelain.active_branch(self.repo)
  3940. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3941. def test_checkout_bytes_vs_string_target(self) -> None:
  3942. """Test that checkout works with both bytes and string targets."""
  3943. # Test with string target
  3944. porcelain.checkout(self.repo, "feature")
  3945. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3946. # Test with bytes target
  3947. porcelain.checkout(self.repo, b"master")
  3948. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3949. def test_checkout_new_branch_from_commit(self) -> None:
  3950. """Test creating a new branch from a specific commit."""
  3951. # Create new branch from first commit
  3952. porcelain.checkout(self.repo, self._sha1.decode(), new_branch="from-commit")
  3953. self.assertEqual(b"from-commit", porcelain.active_branch(self.repo))
  3954. # Should be at the first commit (no bar file)
  3955. self.assertFalse(os.path.exists(self._bar_path))
  3956. def test_checkout_with_staged_addition(self) -> None:
  3957. """Test checkout behavior with staged file additions."""
  3958. # Create and stage a new file that doesn't exist in target branch
  3959. new_file_path = os.path.join(self.repo.path, "new.txt")
  3960. with open(new_file_path, "w") as f:
  3961. f.write("new file content\n")
  3962. porcelain.add(self.repo, [new_file_path])
  3963. # This should succeed because the file doesn't exist in target branch
  3964. porcelain.checkout(self.repo, "feature")
  3965. # Should be on feature branch
  3966. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3967. # The new file should still exist and be staged
  3968. self.assertTrue(os.path.exists(new_file_path))
  3969. status = porcelain.status(self.repo)
  3970. self.assertIn(b"new.txt", status.staged["add"])
  3971. def test_checkout_with_staged_modification_conflict(self) -> None:
  3972. """Test checkout behavior with staged modifications that would conflict."""
  3973. # Stage changes to a file that exists in both branches
  3974. with open(self._foo_path, "w") as f:
  3975. f.write("modified content\n")
  3976. porcelain.add(self.repo, [self._foo_path])
  3977. # Should prevent checkout due to staged changes to existing file
  3978. with self.assertRaises(porcelain.CheckoutError) as cm:
  3979. porcelain.checkout(self.repo, "feature")
  3980. self.assertIn("local changes", str(cm.exception))
  3981. self.assertIn("foo", str(cm.exception))
  3982. def test_checkout_head_reference(self) -> None:
  3983. """Test checkout of HEAD reference."""
  3984. # Move to feature branch first
  3985. porcelain.checkout(self.repo, "feature")
  3986. # Checkout HEAD creates detached HEAD state
  3987. porcelain.checkout(self.repo, "HEAD")
  3988. # Should be in detached HEAD state
  3989. with self.assertRaises((ValueError, IndexError)):
  3990. porcelain.active_branch(self.repo)
  3991. def test_checkout_error_messages(self) -> None:
  3992. """Test that checkout error messages are helpful."""
  3993. # Create uncommitted changes
  3994. with open(self._foo_path, "w") as f:
  3995. f.write("uncommitted changes\n")
  3996. # Try to checkout
  3997. with self.assertRaises(porcelain.CheckoutError) as cm:
  3998. porcelain.checkout(self.repo, "feature")
  3999. error_msg = str(cm.exception)
  4000. self.assertIn("local changes", error_msg)
  4001. self.assertIn("foo", error_msg)
  4002. self.assertIn("overwritten", error_msg)
  4003. self.assertIn("commit or stash", error_msg)
  4004. class SubmoduleTests(PorcelainTestCase):
  4005. def test_empty(self) -> None:
  4006. porcelain.commit(
  4007. repo=self.repo.path,
  4008. message=b"init",
  4009. author=b"author <email>",
  4010. committer=b"committer <email>",
  4011. )
  4012. self.assertEqual([], list(porcelain.submodule_list(self.repo)))
  4013. def test_add(self) -> None:
  4014. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  4015. with open(f"{self.repo.path}/.gitmodules") as f:
  4016. self.assertEqual(
  4017. """\
  4018. [submodule "bar"]
  4019. \turl = ../bar.git
  4020. \tpath = bar
  4021. """,
  4022. f.read(),
  4023. )
  4024. def test_init(self) -> None:
  4025. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  4026. porcelain.submodule_init(self.repo)
  4027. def test_update(self) -> None:
  4028. # Create a submodule repository
  4029. sub_repo_path = tempfile.mkdtemp()
  4030. self.addCleanup(shutil.rmtree, sub_repo_path)
  4031. sub_repo = Repo.init(sub_repo_path)
  4032. self.addCleanup(sub_repo.close)
  4033. # Add a file to the submodule repo
  4034. sub_file = os.path.join(sub_repo_path, "test.txt")
  4035. with open(sub_file, "w") as f:
  4036. f.write("submodule content")
  4037. porcelain.add(sub_repo, paths=[sub_file])
  4038. sub_commit = porcelain.commit(
  4039. sub_repo,
  4040. message=b"Initial submodule commit",
  4041. author=b"Test Author <test@example.com>",
  4042. committer=b"Test Committer <test@example.com>",
  4043. )
  4044. # Add the submodule to the main repository
  4045. porcelain.submodule_add(self.repo, sub_repo_path, "test_submodule")
  4046. # Manually add the submodule to the index
  4047. from dulwich.index import IndexEntry
  4048. from dulwich.objects import S_IFGITLINK
  4049. index = self.repo.open_index()
  4050. index[b"test_submodule"] = IndexEntry(
  4051. ctime=0,
  4052. mtime=0,
  4053. dev=0,
  4054. ino=0,
  4055. mode=S_IFGITLINK,
  4056. uid=0,
  4057. gid=0,
  4058. size=0,
  4059. sha=sub_commit,
  4060. flags=0,
  4061. )
  4062. index.write()
  4063. porcelain.add(self.repo, paths=[".gitmodules"])
  4064. porcelain.commit(
  4065. self.repo,
  4066. message=b"Add submodule",
  4067. author=b"Test Author <test@example.com>",
  4068. committer=b"Test Committer <test@example.com>",
  4069. )
  4070. # Initialize and update the submodule
  4071. porcelain.submodule_init(self.repo)
  4072. porcelain.submodule_update(self.repo)
  4073. # Check that the submodule directory exists
  4074. submodule_path = os.path.join(self.repo.path, "test_submodule")
  4075. self.assertTrue(os.path.exists(submodule_path))
  4076. # Check that the submodule file exists
  4077. submodule_file = os.path.join(submodule_path, "test.txt")
  4078. self.assertTrue(os.path.exists(submodule_file))
  4079. with open(submodule_file) as f:
  4080. self.assertEqual(f.read(), "submodule content")
  4081. class PushTests(PorcelainTestCase):
  4082. def test_simple(self) -> None:
  4083. """Basic test of porcelain push where self.repo is the remote. First
  4084. clone the remote, commit a file to the clone, then push the changes
  4085. back to the remote.
  4086. """
  4087. outstream = BytesIO()
  4088. errstream = BytesIO()
  4089. porcelain.commit(
  4090. repo=self.repo.path,
  4091. message=b"init",
  4092. author=b"author <email>",
  4093. committer=b"committer <email>",
  4094. )
  4095. # Setup target repo cloned from temp test repo
  4096. clone_path = tempfile.mkdtemp()
  4097. self.addCleanup(shutil.rmtree, clone_path)
  4098. target_repo = porcelain.clone(
  4099. self.repo.path, target=clone_path, errstream=errstream
  4100. )
  4101. self.addCleanup(target_repo.close)
  4102. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  4103. # create a second file to be pushed back to origin
  4104. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4105. os.close(handle)
  4106. porcelain.add(repo=clone_path, paths=[fullpath])
  4107. porcelain.commit(
  4108. repo=clone_path,
  4109. message=b"push",
  4110. author=b"author <email>",
  4111. committer=b"committer <email>",
  4112. )
  4113. # Setup a non-checked out branch in the remote
  4114. refs_path = b"refs/heads/foo"
  4115. new_id = self.repo[b"HEAD"].id
  4116. self.assertNotEqual(new_id, ZERO_SHA)
  4117. self.repo.refs[refs_path] = new_id
  4118. # Push to the remote
  4119. porcelain.push(
  4120. clone_path,
  4121. "origin",
  4122. b"HEAD:" + refs_path,
  4123. outstream=outstream,
  4124. errstream=errstream,
  4125. )
  4126. self.assertEqual(
  4127. target_repo.refs[b"refs/remotes/origin/foo"],
  4128. target_repo.refs[b"HEAD"],
  4129. )
  4130. # Check that the target and source
  4131. with Repo(clone_path) as r_clone:
  4132. self.assertEqual(
  4133. {
  4134. b"HEAD": new_id,
  4135. b"refs/heads/foo": r_clone[b"HEAD"].id,
  4136. b"refs/heads/master": new_id,
  4137. },
  4138. self.repo.get_refs(),
  4139. )
  4140. self.assertEqual(r_clone[b"HEAD"].id, self.repo[refs_path].id)
  4141. # Get the change in the target repo corresponding to the add
  4142. # this will be in the foo branch.
  4143. change = next(
  4144. iter(
  4145. tree_changes(
  4146. self.repo.object_store,
  4147. self.repo[b"HEAD"].tree,
  4148. self.repo[b"refs/heads/foo"].tree,
  4149. )
  4150. )
  4151. )
  4152. self.assertEqual(
  4153. os.path.basename(fullpath), change.new.path.decode("ascii")
  4154. )
  4155. def test_local_missing(self) -> None:
  4156. """Pushing a new branch."""
  4157. outstream = BytesIO()
  4158. errstream = BytesIO()
  4159. # Setup target repo cloned from temp test repo
  4160. clone_path = tempfile.mkdtemp()
  4161. self.addCleanup(shutil.rmtree, clone_path)
  4162. target_repo = porcelain.init(clone_path)
  4163. target_repo.close()
  4164. self.assertRaises(
  4165. porcelain.Error,
  4166. porcelain.push,
  4167. self.repo,
  4168. clone_path,
  4169. b"HEAD:refs/heads/master",
  4170. outstream=outstream,
  4171. errstream=errstream,
  4172. )
  4173. def test_new(self) -> None:
  4174. """Pushing a new branch."""
  4175. outstream = BytesIO()
  4176. errstream = BytesIO()
  4177. # Setup target repo cloned from temp test repo
  4178. clone_path = tempfile.mkdtemp()
  4179. self.addCleanup(shutil.rmtree, clone_path)
  4180. target_repo = porcelain.init(clone_path)
  4181. target_repo.close()
  4182. # create a second file to be pushed back to origin
  4183. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4184. os.close(handle)
  4185. porcelain.add(repo=clone_path, paths=[fullpath])
  4186. new_id = porcelain.commit(
  4187. repo=self.repo,
  4188. message=b"push",
  4189. author=b"author <email>",
  4190. committer=b"committer <email>",
  4191. )
  4192. # Push to the remote
  4193. porcelain.push(
  4194. self.repo,
  4195. clone_path,
  4196. b"HEAD:refs/heads/master",
  4197. outstream=outstream,
  4198. errstream=errstream,
  4199. )
  4200. with Repo(clone_path) as r_clone:
  4201. self.assertEqual(
  4202. {
  4203. b"HEAD": new_id,
  4204. b"refs/heads/master": new_id,
  4205. },
  4206. r_clone.get_refs(),
  4207. )
  4208. def test_delete(self) -> None:
  4209. """Basic test of porcelain push, removing a branch."""
  4210. outstream = BytesIO()
  4211. errstream = BytesIO()
  4212. porcelain.commit(
  4213. repo=self.repo.path,
  4214. message=b"init",
  4215. author=b"author <email>",
  4216. committer=b"committer <email>",
  4217. )
  4218. # Setup target repo cloned from temp test repo
  4219. clone_path = tempfile.mkdtemp()
  4220. self.addCleanup(shutil.rmtree, clone_path)
  4221. target_repo = porcelain.clone(
  4222. self.repo.path, target=clone_path, errstream=errstream
  4223. )
  4224. target_repo.close()
  4225. # Setup a non-checked out branch in the remote
  4226. refs_path = b"refs/heads/foo"
  4227. new_id = self.repo[b"HEAD"].id
  4228. self.assertNotEqual(new_id, ZERO_SHA)
  4229. self.repo.refs[refs_path] = new_id
  4230. # Push to the remote
  4231. porcelain.push(
  4232. clone_path,
  4233. self.repo.path,
  4234. b":" + refs_path,
  4235. outstream=outstream,
  4236. errstream=errstream,
  4237. )
  4238. self.assertEqual(
  4239. {
  4240. b"HEAD": new_id,
  4241. b"refs/heads/master": new_id,
  4242. },
  4243. self.repo.get_refs(),
  4244. )
  4245. def test_diverged(self) -> None:
  4246. outstream = BytesIO()
  4247. errstream = BytesIO()
  4248. porcelain.commit(
  4249. repo=self.repo.path,
  4250. message=b"init",
  4251. author=b"author <email>",
  4252. committer=b"committer <email>",
  4253. )
  4254. # Setup target repo cloned from temp test repo
  4255. clone_path = tempfile.mkdtemp()
  4256. self.addCleanup(shutil.rmtree, clone_path)
  4257. target_repo = porcelain.clone(
  4258. self.repo.path, target=clone_path, errstream=errstream
  4259. )
  4260. target_repo.close()
  4261. remote_id = porcelain.commit(
  4262. repo=self.repo.path,
  4263. message=b"remote change",
  4264. author=b"author <email>",
  4265. committer=b"committer <email>",
  4266. )
  4267. local_id = porcelain.commit(
  4268. repo=clone_path,
  4269. message=b"local change",
  4270. author=b"author <email>",
  4271. committer=b"committer <email>",
  4272. )
  4273. outstream = BytesIO()
  4274. errstream = BytesIO()
  4275. # Push to the remote
  4276. self.assertRaises(
  4277. porcelain.DivergedBranches,
  4278. porcelain.push,
  4279. clone_path,
  4280. self.repo.path,
  4281. b"refs/heads/master",
  4282. outstream=outstream,
  4283. errstream=errstream,
  4284. )
  4285. self.assertEqual(
  4286. {
  4287. b"HEAD": remote_id,
  4288. b"refs/heads/master": remote_id,
  4289. },
  4290. self.repo.get_refs(),
  4291. )
  4292. self.assertEqual(b"", outstream.getvalue())
  4293. self.assertEqual(b"", errstream.getvalue())
  4294. outstream = BytesIO()
  4295. errstream = BytesIO()
  4296. # Push to the remote with --force
  4297. porcelain.push(
  4298. clone_path,
  4299. self.repo.path,
  4300. b"refs/heads/master",
  4301. outstream=outstream,
  4302. errstream=errstream,
  4303. force=True,
  4304. )
  4305. self.assertEqual(
  4306. {
  4307. b"HEAD": local_id,
  4308. b"refs/heads/master": local_id,
  4309. },
  4310. self.repo.get_refs(),
  4311. )
  4312. self.assertEqual(b"", outstream.getvalue())
  4313. self.assertTrue(re.match(b"Push to .* successful.\n", errstream.getvalue()))
  4314. def test_push_returns_sendpackresult(self) -> None:
  4315. """Test that push returns a SendPackResult with per-ref information."""
  4316. outstream = BytesIO()
  4317. errstream = BytesIO()
  4318. # Create initial commit
  4319. porcelain.commit(
  4320. repo=self.repo.path,
  4321. message=b"init",
  4322. author=b"author <email>",
  4323. committer=b"committer <email>",
  4324. )
  4325. # Setup target repo cloned from temp test repo
  4326. clone_path = tempfile.mkdtemp()
  4327. self.addCleanup(shutil.rmtree, clone_path)
  4328. target_repo = porcelain.clone(
  4329. self.repo.path, target=clone_path, errstream=errstream
  4330. )
  4331. target_repo.close()
  4332. # Create a commit in the clone
  4333. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4334. os.close(handle)
  4335. porcelain.add(repo=clone_path, paths=[fullpath])
  4336. porcelain.commit(
  4337. repo=clone_path,
  4338. message=b"push",
  4339. author=b"author <email>",
  4340. committer=b"committer <email>",
  4341. )
  4342. # Push and check the return value
  4343. result = porcelain.push(
  4344. clone_path,
  4345. "origin",
  4346. b"HEAD:refs/heads/new-branch",
  4347. outstream=outstream,
  4348. errstream=errstream,
  4349. )
  4350. # Verify that we get a SendPackResult
  4351. self.assertIsInstance(result, SendPackResult)
  4352. # Verify that it contains refs
  4353. self.assertIsNotNone(result.refs)
  4354. self.assertIn(b"refs/heads/new-branch", result.refs)
  4355. # Verify ref_status - should be None for successful updates
  4356. if result.ref_status:
  4357. self.assertIsNone(result.ref_status.get(b"refs/heads/new-branch"))
  4358. def test_mirror_mode(self) -> None:
  4359. """Test push with remote.<name>.mirror configuration."""
  4360. outstream = BytesIO()
  4361. errstream = BytesIO()
  4362. # Create initial commit
  4363. porcelain.commit(
  4364. repo=self.repo.path,
  4365. message=b"init",
  4366. author=b"author <email>",
  4367. committer=b"committer <email>",
  4368. )
  4369. # Setup target repo cloned from temp test repo
  4370. clone_path = tempfile.mkdtemp()
  4371. self.addCleanup(shutil.rmtree, clone_path)
  4372. target_repo = porcelain.clone(
  4373. self.repo.path, target=clone_path, errstream=errstream
  4374. )
  4375. target_repo.close()
  4376. # Create multiple refs in the clone
  4377. with Repo(clone_path) as r_clone:
  4378. # Create a new branch
  4379. r_clone.refs[b"refs/heads/feature"] = r_clone[b"HEAD"].id
  4380. # Create a tag
  4381. r_clone.refs[b"refs/tags/v1.0"] = r_clone[b"HEAD"].id
  4382. # Create a remote tracking branch
  4383. r_clone.refs[b"refs/remotes/upstream/main"] = r_clone[b"HEAD"].id
  4384. # Create a branch in the remote that doesn't exist in clone
  4385. self.repo.refs[b"refs/heads/to-be-deleted"] = self.repo[b"HEAD"].id
  4386. # Configure mirror mode
  4387. with Repo(clone_path) as r_clone:
  4388. config = r_clone.get_config()
  4389. config.set((b"remote", b"origin"), b"mirror", True)
  4390. config.write_to_path()
  4391. # Push with mirror mode
  4392. porcelain.push(
  4393. clone_path,
  4394. "origin",
  4395. outstream=outstream,
  4396. errstream=errstream,
  4397. )
  4398. # Verify refs were properly mirrored
  4399. with Repo(clone_path) as r_clone:
  4400. # All local branches should be pushed
  4401. self.assertEqual(
  4402. r_clone.refs[b"refs/heads/feature"],
  4403. self.repo.refs[b"refs/heads/feature"],
  4404. )
  4405. # All tags should be pushed
  4406. self.assertEqual(
  4407. r_clone.refs[b"refs/tags/v1.0"], self.repo.refs[b"refs/tags/v1.0"]
  4408. )
  4409. # Remote tracking branches should be pushed
  4410. self.assertEqual(
  4411. r_clone.refs[b"refs/remotes/upstream/main"],
  4412. self.repo.refs[b"refs/remotes/upstream/main"],
  4413. )
  4414. # Verify the extra branch was deleted
  4415. self.assertNotIn(b"refs/heads/to-be-deleted", self.repo.refs)
  4416. def test_mirror_mode_disabled(self) -> None:
  4417. """Test that mirror mode is properly disabled when set to false."""
  4418. outstream = BytesIO()
  4419. errstream = BytesIO()
  4420. # Create initial commit
  4421. porcelain.commit(
  4422. repo=self.repo.path,
  4423. message=b"init",
  4424. author=b"author <email>",
  4425. committer=b"committer <email>",
  4426. )
  4427. # Setup target repo cloned from temp test repo
  4428. clone_path = tempfile.mkdtemp()
  4429. self.addCleanup(shutil.rmtree, clone_path)
  4430. target_repo = porcelain.clone(
  4431. self.repo.path, target=clone_path, errstream=errstream
  4432. )
  4433. target_repo.close()
  4434. # Create a branch in the remote that doesn't exist in clone
  4435. self.repo.refs[b"refs/heads/should-not-be-deleted"] = self.repo[b"HEAD"].id
  4436. # Explicitly set mirror mode to false
  4437. with Repo(clone_path) as r_clone:
  4438. config = r_clone.get_config()
  4439. config.set((b"remote", b"origin"), b"mirror", False)
  4440. config.write_to_path()
  4441. # Push normally (not mirror mode)
  4442. porcelain.push(
  4443. clone_path,
  4444. "origin",
  4445. outstream=outstream,
  4446. errstream=errstream,
  4447. )
  4448. # Verify the extra branch was NOT deleted
  4449. self.assertIn(b"refs/heads/should-not-be-deleted", self.repo.refs)
  4450. class PullTests(PorcelainTestCase):
  4451. def setUp(self) -> None:
  4452. super().setUp()
  4453. # create a file for initial commit
  4454. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4455. os.close(handle)
  4456. porcelain.add(repo=self.repo.path, paths=fullpath)
  4457. porcelain.commit(
  4458. repo=self.repo.path,
  4459. message=b"test",
  4460. author=b"test <email>",
  4461. committer=b"test <email>",
  4462. )
  4463. # Setup target repo
  4464. self.target_path = tempfile.mkdtemp()
  4465. self.addCleanup(shutil.rmtree, self.target_path)
  4466. target_repo = porcelain.clone(
  4467. self.repo.path, target=self.target_path, errstream=BytesIO()
  4468. )
  4469. target_repo.close()
  4470. # create a second file to be pushed
  4471. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4472. os.close(handle)
  4473. porcelain.add(repo=self.repo.path, paths=fullpath)
  4474. porcelain.commit(
  4475. repo=self.repo.path,
  4476. message=b"test2",
  4477. author=b"test2 <email>",
  4478. committer=b"test2 <email>",
  4479. )
  4480. self.assertIn(b"refs/heads/master", self.repo.refs)
  4481. self.assertIn(b"refs/heads/master", target_repo.refs)
  4482. def test_simple(self) -> None:
  4483. outstream = BytesIO()
  4484. errstream = BytesIO()
  4485. # Pull changes into the cloned repo
  4486. porcelain.pull(
  4487. self.target_path,
  4488. self.repo.path,
  4489. b"refs/heads/master",
  4490. outstream=outstream,
  4491. errstream=errstream,
  4492. )
  4493. # Check the target repo for pushed changes
  4494. with Repo(self.target_path) as r:
  4495. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4496. def test_diverged(self) -> None:
  4497. outstream = BytesIO()
  4498. errstream = BytesIO()
  4499. c3a = porcelain.commit(
  4500. repo=self.target_path,
  4501. message=b"test3a",
  4502. author=b"test2 <email>",
  4503. committer=b"test2 <email>",
  4504. )
  4505. porcelain.commit(
  4506. repo=self.repo.path,
  4507. message=b"test3b",
  4508. author=b"test2 <email>",
  4509. committer=b"test2 <email>",
  4510. )
  4511. # Pull changes into the cloned repo
  4512. self.assertRaises(
  4513. porcelain.DivergedBranches,
  4514. porcelain.pull,
  4515. self.target_path,
  4516. self.repo.path,
  4517. b"refs/heads/master",
  4518. outstream=outstream,
  4519. errstream=errstream,
  4520. )
  4521. # Check the target repo for pushed changes
  4522. with Repo(self.target_path) as r:
  4523. self.assertEqual(r[b"refs/heads/master"].id, c3a)
  4524. # Pull with merge should now work
  4525. porcelain.pull(
  4526. self.target_path,
  4527. self.repo.path,
  4528. b"refs/heads/master",
  4529. outstream=outstream,
  4530. errstream=errstream,
  4531. fast_forward=False,
  4532. )
  4533. # Check the target repo for merged changes
  4534. with Repo(self.target_path) as r:
  4535. # HEAD should now be a merge commit
  4536. head = r[b"HEAD"]
  4537. # It should have two parents
  4538. self.assertEqual(len(head.parents), 2)
  4539. # One parent should be the previous HEAD (c3a)
  4540. self.assertIn(c3a, head.parents)
  4541. # The other parent should be from the source repo
  4542. self.assertIn(self.repo[b"HEAD"].id, head.parents)
  4543. def test_no_refspec(self) -> None:
  4544. outstream = BytesIO()
  4545. errstream = BytesIO()
  4546. # Pull changes into the cloned repo
  4547. porcelain.pull(
  4548. self.target_path,
  4549. self.repo.path,
  4550. outstream=outstream,
  4551. errstream=errstream,
  4552. )
  4553. # Check the target repo for pushed changes
  4554. with Repo(self.target_path) as r:
  4555. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4556. def test_no_remote_location(self) -> None:
  4557. outstream = BytesIO()
  4558. errstream = BytesIO()
  4559. # Pull changes into the cloned repo
  4560. porcelain.pull(
  4561. self.target_path,
  4562. refspecs=b"refs/heads/master",
  4563. outstream=outstream,
  4564. errstream=errstream,
  4565. )
  4566. # Check the target repo for pushed changes
  4567. with Repo(self.target_path) as r:
  4568. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4569. def test_pull_updates_working_tree(self) -> None:
  4570. """Test that pull updates the working tree with new files."""
  4571. outstream = BytesIO()
  4572. errstream = BytesIO()
  4573. # Create a new file with content in the source repo
  4574. new_file = os.path.join(self.repo.path, "newfile.txt")
  4575. with open(new_file, "w") as f:
  4576. f.write("This is new content")
  4577. porcelain.add(repo=self.repo.path, paths=[new_file])
  4578. porcelain.commit(
  4579. repo=self.repo.path,
  4580. message=b"Add new file",
  4581. author=b"test <email>",
  4582. committer=b"test <email>",
  4583. )
  4584. # Before pull, the file should not exist in target
  4585. target_file = os.path.join(self.target_path, "newfile.txt")
  4586. self.assertFalse(os.path.exists(target_file))
  4587. # Pull changes into the cloned repo
  4588. porcelain.pull(
  4589. self.target_path,
  4590. self.repo.path,
  4591. b"refs/heads/master",
  4592. outstream=outstream,
  4593. errstream=errstream,
  4594. )
  4595. # After pull, the file should exist with correct content
  4596. self.assertTrue(os.path.exists(target_file))
  4597. with open(target_file) as f:
  4598. self.assertEqual(f.read(), "This is new content")
  4599. # Check the HEAD is updated too
  4600. with Repo(self.target_path) as r:
  4601. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4602. def test_pull_protects_modified_files(self) -> None:
  4603. """Test that pull refuses to overwrite uncommitted changes by default."""
  4604. from dulwich.errors import WorkingTreeModifiedError
  4605. outstream = BytesIO()
  4606. errstream = BytesIO()
  4607. # Create a file with content in the source repo
  4608. test_file = os.path.join(self.repo.path, "testfile.txt")
  4609. with open(test_file, "w") as f:
  4610. f.write("original content")
  4611. porcelain.add(repo=self.repo.path, paths=[test_file])
  4612. porcelain.commit(
  4613. repo=self.repo.path,
  4614. message=b"Add test file",
  4615. author=b"test <email>",
  4616. committer=b"test <email>",
  4617. )
  4618. # Pull this change to target first
  4619. porcelain.pull(
  4620. self.target_path,
  4621. self.repo.path,
  4622. b"refs/heads/master",
  4623. outstream=outstream,
  4624. errstream=errstream,
  4625. )
  4626. # Now modify the file in source repo
  4627. with open(test_file, "w") as f:
  4628. f.write("updated content")
  4629. porcelain.add(repo=self.repo.path, paths=[test_file])
  4630. porcelain.commit(
  4631. repo=self.repo.path,
  4632. message=b"Update test file",
  4633. author=b"test <email>",
  4634. committer=b"test <email>",
  4635. )
  4636. # Modify the same file in target working directory (uncommitted)
  4637. target_file = os.path.join(self.target_path, "testfile.txt")
  4638. with open(target_file, "w") as f:
  4639. f.write("local modifications")
  4640. # Pull should fail because of uncommitted changes
  4641. with self.assertRaises(WorkingTreeModifiedError) as cm:
  4642. porcelain.pull(
  4643. self.target_path,
  4644. self.repo.path,
  4645. b"refs/heads/master",
  4646. outstream=outstream,
  4647. errstream=errstream,
  4648. )
  4649. self.assertIn("Your local changes", str(cm.exception))
  4650. self.assertIn("testfile.txt", str(cm.exception))
  4651. # Verify the file still has local modifications
  4652. with open(target_file) as f:
  4653. self.assertEqual(f.read(), "local modifications")
  4654. def test_pull_force_overwrites_modified_files(self) -> None:
  4655. """Test that pull with force=True overwrites uncommitted changes."""
  4656. outstream = BytesIO()
  4657. errstream = BytesIO()
  4658. # Create a file with content in the source repo
  4659. test_file = os.path.join(self.repo.path, "testfile.txt")
  4660. with open(test_file, "w") as f:
  4661. f.write("original content")
  4662. porcelain.add(repo=self.repo.path, paths=[test_file])
  4663. porcelain.commit(
  4664. repo=self.repo.path,
  4665. message=b"Add test file",
  4666. author=b"test <email>",
  4667. committer=b"test <email>",
  4668. )
  4669. # Pull this change to target first
  4670. porcelain.pull(
  4671. self.target_path,
  4672. self.repo.path,
  4673. b"refs/heads/master",
  4674. outstream=outstream,
  4675. errstream=errstream,
  4676. )
  4677. # Now modify the file in source repo
  4678. with open(test_file, "w") as f:
  4679. f.write("updated content")
  4680. porcelain.add(repo=self.repo.path, paths=[test_file])
  4681. porcelain.commit(
  4682. repo=self.repo.path,
  4683. message=b"Update test file",
  4684. author=b"test <email>",
  4685. committer=b"test <email>",
  4686. )
  4687. # Modify the same file in target working directory (uncommitted)
  4688. target_file = os.path.join(self.target_path, "testfile.txt")
  4689. with open(target_file, "w") as f:
  4690. f.write("local modifications")
  4691. # Pull with force=True should succeed and overwrite local changes
  4692. porcelain.pull(
  4693. self.target_path,
  4694. self.repo.path,
  4695. b"refs/heads/master",
  4696. outstream=outstream,
  4697. errstream=errstream,
  4698. force=True,
  4699. )
  4700. # Verify the file now has the remote content
  4701. with open(target_file) as f:
  4702. self.assertEqual(f.read(), "updated content")
  4703. # Check the HEAD is updated too
  4704. with Repo(self.target_path) as r:
  4705. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4706. def test_pull_allows_unmodified_files(self) -> None:
  4707. """Test that pull allows updating files that haven't been modified locally."""
  4708. outstream = BytesIO()
  4709. errstream = BytesIO()
  4710. # Create a file with content in the source repo
  4711. test_file = os.path.join(self.repo.path, "testfile.txt")
  4712. with open(test_file, "w") as f:
  4713. f.write("original content")
  4714. porcelain.add(repo=self.repo.path, paths=[test_file])
  4715. porcelain.commit(
  4716. repo=self.repo.path,
  4717. message=b"Add test file",
  4718. author=b"test <email>",
  4719. committer=b"test <email>",
  4720. )
  4721. # Pull this change to target first
  4722. porcelain.pull(
  4723. self.target_path,
  4724. self.repo.path,
  4725. b"refs/heads/master",
  4726. outstream=outstream,
  4727. errstream=errstream,
  4728. )
  4729. # Now modify the file in source repo
  4730. with open(test_file, "w") as f:
  4731. f.write("updated content")
  4732. porcelain.add(repo=self.repo.path, paths=[test_file])
  4733. porcelain.commit(
  4734. repo=self.repo.path,
  4735. message=b"Update test file",
  4736. author=b"test <email>",
  4737. committer=b"test <email>",
  4738. )
  4739. # Don't modify the file in target - it should be safe to update
  4740. target_file = os.path.join(self.target_path, "testfile.txt")
  4741. # Pull should succeed since the file wasn't modified locally
  4742. porcelain.pull(
  4743. self.target_path,
  4744. self.repo.path,
  4745. b"refs/heads/master",
  4746. outstream=outstream,
  4747. errstream=errstream,
  4748. )
  4749. # Verify the file now has the remote content
  4750. with open(target_file) as f:
  4751. self.assertEqual(f.read(), "updated content")
  4752. # Check the HEAD is updated too
  4753. with Repo(self.target_path) as r:
  4754. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4755. class StatusTests(PorcelainTestCase):
  4756. def test_empty(self) -> None:
  4757. results = porcelain.status(self.repo)
  4758. self.assertEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4759. self.assertEqual([], results.unstaged)
  4760. def test_status_base(self) -> None:
  4761. """Integration test for `status` functionality."""
  4762. # Commit a dummy file then modify it
  4763. fullpath = os.path.join(self.repo.path, "foo")
  4764. with open(fullpath, "w") as f:
  4765. f.write("origstuff")
  4766. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4767. porcelain.commit(
  4768. repo=self.repo.path,
  4769. message=b"test status",
  4770. author=b"author <email>",
  4771. committer=b"committer <email>",
  4772. )
  4773. # modify access and modify time of path
  4774. os.utime(fullpath, (0, 0))
  4775. with open(fullpath, "wb") as f:
  4776. f.write(b"stuff")
  4777. # Make a dummy file and stage it
  4778. filename_add = "bar"
  4779. fullpath = os.path.join(self.repo.path, filename_add)
  4780. with open(fullpath, "w") as f:
  4781. f.write("stuff")
  4782. porcelain.add(repo=self.repo.path, paths=fullpath)
  4783. results = porcelain.status(self.repo)
  4784. self.assertEqual(results.staged["add"][0], filename_add.encode("ascii"))
  4785. self.assertEqual(results.unstaged, [b"foo"])
  4786. def test_status_with_core_preloadindex(self) -> None:
  4787. """Test status with core.preloadIndex enabled."""
  4788. # Set core.preloadIndex to true
  4789. config = self.repo.get_config()
  4790. config.set(b"core", b"preloadIndex", b"true")
  4791. config.write_to_path()
  4792. # Create multiple files
  4793. files = []
  4794. for i in range(10):
  4795. filename = f"file{i}"
  4796. fullpath = os.path.join(self.repo.path, filename)
  4797. with open(fullpath, "w") as f:
  4798. f.write(f"content{i}")
  4799. files.append(fullpath)
  4800. porcelain.add(repo=self.repo.path, paths=files)
  4801. porcelain.commit(
  4802. repo=self.repo.path,
  4803. message=b"test preload status",
  4804. author=b"author <email>",
  4805. committer=b"committer <email>",
  4806. )
  4807. # Modify some files
  4808. modified_files = ["file1", "file3", "file5", "file7"]
  4809. for filename in modified_files:
  4810. fullpath = os.path.join(self.repo.path, filename)
  4811. with open(fullpath, "w") as f:
  4812. f.write("modified content")
  4813. os.utime(fullpath, (0, 0))
  4814. # Status should work correctly with preloadIndex enabled
  4815. results = porcelain.status(self.repo)
  4816. # Check that we detected the correct unstaged changes
  4817. unstaged_sorted = sorted(results.unstaged)
  4818. expected_sorted = sorted([f.encode("ascii") for f in modified_files])
  4819. self.assertEqual(unstaged_sorted, expected_sorted)
  4820. def test_status_all(self) -> None:
  4821. del_path = os.path.join(self.repo.path, "foo")
  4822. mod_path = os.path.join(self.repo.path, "bar")
  4823. add_path = os.path.join(self.repo.path, "baz")
  4824. us_path = os.path.join(self.repo.path, "blye")
  4825. ut_path = os.path.join(self.repo.path, "blyat")
  4826. with open(del_path, "w") as f:
  4827. f.write("origstuff")
  4828. with open(mod_path, "w") as f:
  4829. f.write("origstuff")
  4830. with open(us_path, "w") as f:
  4831. f.write("origstuff")
  4832. porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path])
  4833. porcelain.commit(
  4834. repo=self.repo.path,
  4835. message=b"test status",
  4836. author=b"author <email>",
  4837. committer=b"committer <email>",
  4838. )
  4839. porcelain.remove(self.repo.path, [del_path])
  4840. with open(add_path, "w") as f:
  4841. f.write("origstuff")
  4842. with open(mod_path, "w") as f:
  4843. f.write("more_origstuff")
  4844. with open(us_path, "w") as f:
  4845. f.write("more_origstuff")
  4846. porcelain.add(repo=self.repo.path, paths=[add_path, mod_path])
  4847. with open(us_path, "w") as f:
  4848. f.write("\norigstuff")
  4849. with open(ut_path, "w") as f:
  4850. f.write("origstuff")
  4851. results = porcelain.status(self.repo.path)
  4852. self.assertDictEqual(
  4853. {"add": [b"baz"], "delete": [b"foo"], "modify": [b"bar"]},
  4854. results.staged,
  4855. )
  4856. self.assertListEqual(results.unstaged, [b"blye"])
  4857. results_no_untracked = porcelain.status(self.repo.path, untracked_files="no")
  4858. self.assertListEqual(results_no_untracked.untracked, [])
  4859. def test_status_wrong_untracked_files_value(self) -> None:
  4860. with self.assertRaises(ValueError):
  4861. porcelain.status(self.repo.path, untracked_files="antani")
  4862. def test_status_untracked_path(self) -> None:
  4863. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  4864. os.mkdir(untracked_dir)
  4865. untracked_file = os.path.join(untracked_dir, "untracked_file")
  4866. with open(untracked_file, "w") as fh:
  4867. fh.write("untracked")
  4868. _, _, untracked = porcelain.status(self.repo.path, untracked_files="all")
  4869. self.assertEqual(untracked, ["untracked_dir/untracked_file"])
  4870. def test_status_untracked_path_normal(self) -> None:
  4871. # Create an untracked directory with multiple files
  4872. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  4873. os.mkdir(untracked_dir)
  4874. untracked_file1 = os.path.join(untracked_dir, "file1")
  4875. untracked_file2 = os.path.join(untracked_dir, "file2")
  4876. with open(untracked_file1, "w") as fh:
  4877. fh.write("untracked1")
  4878. with open(untracked_file2, "w") as fh:
  4879. fh.write("untracked2")
  4880. # Create a nested untracked directory
  4881. nested_dir = os.path.join(untracked_dir, "nested")
  4882. os.mkdir(nested_dir)
  4883. nested_file = os.path.join(nested_dir, "file3")
  4884. with open(nested_file, "w") as fh:
  4885. fh.write("untracked3")
  4886. # Test "normal" mode - should only show the directory, not individual files
  4887. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  4888. self.assertEqual(untracked, ["untracked_dir/"])
  4889. # Test "all" mode - should show all files
  4890. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  4891. self.assertEqual(
  4892. sorted(untracked_all),
  4893. [
  4894. "untracked_dir/file1",
  4895. "untracked_dir/file2",
  4896. "untracked_dir/nested/file3",
  4897. ],
  4898. )
  4899. def test_status_mixed_tracked_untracked(self) -> None:
  4900. # Create a directory with both tracked and untracked files
  4901. mixed_dir = os.path.join(self.repo_path, "mixed_dir")
  4902. os.mkdir(mixed_dir)
  4903. # Add a tracked file
  4904. tracked_file = os.path.join(mixed_dir, "tracked.txt")
  4905. with open(tracked_file, "w") as fh:
  4906. fh.write("tracked content")
  4907. porcelain.add(self.repo.path, paths=[tracked_file])
  4908. porcelain.commit(
  4909. repo=self.repo.path,
  4910. message=b"add tracked file",
  4911. author=b"author <email>",
  4912. committer=b"committer <email>",
  4913. )
  4914. # Add untracked files to the same directory
  4915. untracked_file = os.path.join(mixed_dir, "untracked.txt")
  4916. with open(untracked_file, "w") as fh:
  4917. fh.write("untracked content")
  4918. # In "normal" mode, should show individual untracked files in mixed dirs
  4919. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  4920. self.assertEqual(untracked, ["mixed_dir/untracked.txt"])
  4921. # In "all" mode, should be the same for mixed directories
  4922. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  4923. self.assertEqual(untracked_all, ["mixed_dir/untracked.txt"])
  4924. def test_status_crlf_mismatch(self) -> None:
  4925. # First make a commit as if the file has been added on a Linux system
  4926. # or with core.autocrlf=True
  4927. file_path = os.path.join(self.repo.path, "crlf")
  4928. with open(file_path, "wb") as f:
  4929. f.write(b"line1\nline2")
  4930. porcelain.add(repo=self.repo.path, paths=[file_path])
  4931. porcelain.commit(
  4932. repo=self.repo.path,
  4933. message=b"test status",
  4934. author=b"author <email>",
  4935. committer=b"committer <email>",
  4936. )
  4937. # Then update the file as if it was created by CGit on a Windows
  4938. # system with core.autocrlf=true
  4939. with open(file_path, "wb") as f:
  4940. f.write(b"line1\r\nline2")
  4941. results = porcelain.status(self.repo)
  4942. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4943. self.assertListEqual(results.unstaged, [b"crlf"])
  4944. self.assertListEqual(results.untracked, [])
  4945. def test_status_autocrlf_true(self) -> None:
  4946. # First make a commit as if the file has been added on a Linux system
  4947. # or with core.autocrlf=True
  4948. file_path = os.path.join(self.repo.path, "crlf")
  4949. with open(file_path, "wb") as f:
  4950. f.write(b"line1\nline2")
  4951. porcelain.add(repo=self.repo.path, paths=[file_path])
  4952. porcelain.commit(
  4953. repo=self.repo.path,
  4954. message=b"test status",
  4955. author=b"author <email>",
  4956. committer=b"committer <email>",
  4957. )
  4958. # Then update the file as if it was created by CGit on a Windows
  4959. # system with core.autocrlf=true
  4960. with open(file_path, "wb") as f:
  4961. f.write(b"line1\r\nline2")
  4962. # TODO: It should be set automatically by looking at the configuration
  4963. c = self.repo.get_config()
  4964. c.set("core", "autocrlf", True)
  4965. c.write_to_path()
  4966. results = porcelain.status(self.repo)
  4967. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4968. self.assertListEqual(results.unstaged, [])
  4969. self.assertListEqual(results.untracked, [])
  4970. def test_status_autocrlf_input(self) -> None:
  4971. # Commit existing file with CRLF
  4972. file_path = os.path.join(self.repo.path, "crlf-exists")
  4973. with open(file_path, "wb") as f:
  4974. f.write(b"line1\r\nline2")
  4975. porcelain.add(repo=self.repo.path, paths=[file_path])
  4976. porcelain.commit(
  4977. repo=self.repo.path,
  4978. message=b"test status",
  4979. author=b"author <email>",
  4980. committer=b"committer <email>",
  4981. )
  4982. c = self.repo.get_config()
  4983. c.set("core", "autocrlf", "input")
  4984. c.write_to_path()
  4985. # Add new (untracked) file
  4986. file_path = os.path.join(self.repo.path, "crlf-new")
  4987. with open(file_path, "wb") as f:
  4988. f.write(b"line1\r\nline2")
  4989. porcelain.add(repo=self.repo.path, paths=[file_path])
  4990. results = porcelain.status(self.repo)
  4991. self.assertDictEqual(
  4992. {"add": [b"crlf-new"], "delete": [], "modify": []}, results.staged
  4993. )
  4994. # File committed with CRLF before autocrlf=input was enabled
  4995. # will appear as unstaged because working tree is normalized to LF
  4996. # during comparison but index still has CRLF
  4997. self.assertListEqual(results.unstaged, [b"crlf-exists"])
  4998. self.assertListEqual(results.untracked, [])
  4999. def test_status_autocrlf_input_modified(self) -> None:
  5000. """Test that modified files with CRLF are correctly detected with autocrlf=input."""
  5001. # Commit existing file with CRLF
  5002. file_path = os.path.join(self.repo.path, "crlf-file.txt")
  5003. with open(file_path, "wb") as f:
  5004. f.write(b"line1\r\nline2\r\nline3\r\n")
  5005. porcelain.add(repo=self.repo.path, paths=[file_path])
  5006. porcelain.commit(
  5007. repo=self.repo.path,
  5008. message=b"initial commit",
  5009. author=b"author <email>",
  5010. committer=b"committer <email>",
  5011. )
  5012. c = self.repo.get_config()
  5013. c.set("core", "autocrlf", "input")
  5014. c.write_to_path()
  5015. # Modify the file content but keep CRLF
  5016. with open(file_path, "wb") as f:
  5017. f.write(b"line1\r\nline2 modified\r\nline3\r\n")
  5018. results = porcelain.status(self.repo)
  5019. # Modified file should be detected as unstaged
  5020. self.assertListEqual(results.unstaged, [b"crlf-file.txt"])
  5021. def test_status_autocrlf_input_binary(self) -> None:
  5022. """Test that binary files are not affected by autocrlf=input."""
  5023. # Set autocrlf=input first
  5024. c = self.repo.get_config()
  5025. c.set("core", "autocrlf", "input")
  5026. c.write_to_path()
  5027. # Commit binary file with CRLF-like sequences
  5028. file_path = os.path.join(self.repo.path, "binary.dat")
  5029. with open(file_path, "wb") as f:
  5030. f.write(b"binary\r\ndata\x00\xff\r\nmore")
  5031. porcelain.add(repo=self.repo.path, paths=[file_path])
  5032. porcelain.commit(
  5033. repo=self.repo.path,
  5034. message=b"add binary",
  5035. author=b"author <email>",
  5036. committer=b"committer <email>",
  5037. )
  5038. # Status should be clean - binary files not normalized
  5039. results = porcelain.status(self.repo)
  5040. self.assertListEqual(results.unstaged, [])
  5041. def test_status_autocrlf_input_mixed_endings(self) -> None:
  5042. """Test files with mixed line endings with autocrlf=input."""
  5043. # Set autocrlf=input
  5044. c = self.repo.get_config()
  5045. c.set("core", "autocrlf", "input")
  5046. c.write_to_path()
  5047. # Create file with mixed line endings
  5048. file_path = os.path.join(self.repo.path, "mixed.txt")
  5049. with open(file_path, "wb") as f:
  5050. f.write(b"line1\r\nline2\nline3\r\n")
  5051. porcelain.add(repo=self.repo.path, paths=[file_path])
  5052. porcelain.commit(
  5053. repo=self.repo.path,
  5054. message=b"add mixed",
  5055. author=b"author <email>",
  5056. committer=b"committer <email>",
  5057. )
  5058. # The file was normalized on commit, so working tree should match
  5059. results = porcelain.status(self.repo)
  5060. self.assertListEqual(results.unstaged, [])
  5061. def test_status_autocrlf_input_issue_1770(self) -> None:
  5062. """Test the specific scenario from issue #1770.
  5063. Files with CRLF committed with autocrlf=input should not show as unstaged
  5064. when their content hasn't changed.
  5065. """
  5066. # Set autocrlf=input BEFORE committing
  5067. c = self.repo.get_config()
  5068. c.set("core", "autocrlf", "input")
  5069. c.write_to_path()
  5070. # Create and commit file with CRLF endings
  5071. file_path = os.path.join(self.repo.path, "crlf-test.dsp")
  5072. with open(file_path, "wb") as f:
  5073. f.write(b"# Microsoft DSP file\r\n\r\nContent here\r\n")
  5074. porcelain.add(repo=self.repo.path, paths=[file_path])
  5075. porcelain.commit(
  5076. repo=self.repo.path,
  5077. message=b"add dsp file",
  5078. author=b"author <email>",
  5079. committer=b"committer <email>",
  5080. )
  5081. # File was normalized to LF in index, but working tree still has CRLF
  5082. # Status should be clean because comparison normalizes working tree too
  5083. results = porcelain.status(self.repo)
  5084. self.assertListEqual(results.unstaged, [])
  5085. def test_get_tree_changes_add(self) -> None:
  5086. """Unit test for get_tree_changes add."""
  5087. # Make a dummy file, stage
  5088. filename = "bar"
  5089. fullpath = os.path.join(self.repo.path, filename)
  5090. with open(fullpath, "w") as f:
  5091. f.write("stuff")
  5092. porcelain.add(repo=self.repo.path, paths=fullpath)
  5093. porcelain.commit(
  5094. repo=self.repo.path,
  5095. message=b"test status",
  5096. author=b"author <email>",
  5097. committer=b"committer <email>",
  5098. )
  5099. filename = "foo"
  5100. fullpath = os.path.join(self.repo.path, filename)
  5101. with open(fullpath, "w") as f:
  5102. f.write("stuff")
  5103. porcelain.add(repo=self.repo.path, paths=fullpath)
  5104. changes = porcelain.get_tree_changes(self.repo.path)
  5105. self.assertEqual(changes["add"][0], filename.encode("ascii"))
  5106. self.assertEqual(len(changes["add"]), 1)
  5107. self.assertEqual(len(changes["modify"]), 0)
  5108. self.assertEqual(len(changes["delete"]), 0)
  5109. def test_get_tree_changes_modify(self) -> None:
  5110. """Unit test for get_tree_changes modify."""
  5111. # Make a dummy file, stage, commit, modify
  5112. filename = "foo"
  5113. fullpath = os.path.join(self.repo.path, filename)
  5114. with open(fullpath, "w") as f:
  5115. f.write("stuff")
  5116. porcelain.add(repo=self.repo.path, paths=fullpath)
  5117. porcelain.commit(
  5118. repo=self.repo.path,
  5119. message=b"test status",
  5120. author=b"author <email>",
  5121. committer=b"committer <email>",
  5122. )
  5123. with open(fullpath, "w") as f:
  5124. f.write("otherstuff")
  5125. porcelain.add(repo=self.repo.path, paths=fullpath)
  5126. changes = porcelain.get_tree_changes(self.repo.path)
  5127. self.assertEqual(changes["modify"][0], filename.encode("ascii"))
  5128. self.assertEqual(len(changes["add"]), 0)
  5129. self.assertEqual(len(changes["modify"]), 1)
  5130. self.assertEqual(len(changes["delete"]), 0)
  5131. def test_get_tree_changes_delete(self) -> None:
  5132. """Unit test for get_tree_changes delete."""
  5133. # Make a dummy file, stage, commit, remove
  5134. filename = "foo"
  5135. fullpath = os.path.join(self.repo.path, filename)
  5136. with open(fullpath, "w") as f:
  5137. f.write("stuff")
  5138. porcelain.add(repo=self.repo.path, paths=fullpath)
  5139. porcelain.commit(
  5140. repo=self.repo.path,
  5141. message=b"test status",
  5142. author=b"author <email>",
  5143. committer=b"committer <email>",
  5144. )
  5145. cwd = os.getcwd()
  5146. self.addCleanup(os.chdir, cwd)
  5147. os.chdir(self.repo.path)
  5148. porcelain.remove(repo=self.repo.path, paths=[filename])
  5149. changes = porcelain.get_tree_changes(self.repo.path)
  5150. self.assertEqual(changes["delete"][0], filename.encode("ascii"))
  5151. self.assertEqual(len(changes["add"]), 0)
  5152. self.assertEqual(len(changes["modify"]), 0)
  5153. self.assertEqual(len(changes["delete"]), 1)
  5154. def test_get_untracked_paths(self) -> None:
  5155. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5156. f.write("ignored\n")
  5157. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  5158. f.write("blah\n")
  5159. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5160. f.write("blah\n")
  5161. os.symlink(
  5162. os.path.join(self.repo.path, os.pardir, "external_target"),
  5163. os.path.join(self.repo.path, "link"),
  5164. )
  5165. self.assertEqual(
  5166. {"ignored", "notignored", ".gitignore", "link"},
  5167. set(
  5168. porcelain.get_untracked_paths(
  5169. self.repo.path, self.repo.path, self.repo.open_index()
  5170. )
  5171. ),
  5172. )
  5173. self.assertEqual(
  5174. {".gitignore", "notignored", "link"},
  5175. set(porcelain.status(self.repo).untracked),
  5176. )
  5177. self.assertEqual(
  5178. {".gitignore", "notignored", "ignored", "link"},
  5179. set(porcelain.status(self.repo, ignored=True).untracked),
  5180. )
  5181. def test_get_untracked_paths_subrepo(self) -> None:
  5182. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5183. f.write("nested/\n")
  5184. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5185. f.write("blah\n")
  5186. subrepo = Repo.init(os.path.join(self.repo.path, "nested"), mkdir=True)
  5187. with open(os.path.join(subrepo.path, "ignored"), "w") as f:
  5188. f.write("bleep\n")
  5189. with open(os.path.join(subrepo.path, "with"), "w") as f:
  5190. f.write("bloop\n")
  5191. with open(os.path.join(subrepo.path, "manager"), "w") as f:
  5192. f.write("blop\n")
  5193. self.assertEqual(
  5194. {".gitignore", "notignored", os.path.join("nested", "")},
  5195. set(
  5196. porcelain.get_untracked_paths(
  5197. self.repo.path, self.repo.path, self.repo.open_index()
  5198. )
  5199. ),
  5200. )
  5201. self.assertEqual(
  5202. {".gitignore", "notignored"},
  5203. set(
  5204. porcelain.get_untracked_paths(
  5205. self.repo.path,
  5206. self.repo.path,
  5207. self.repo.open_index(),
  5208. exclude_ignored=True,
  5209. )
  5210. ),
  5211. )
  5212. self.assertEqual(
  5213. {"ignored", "with", "manager"},
  5214. set(
  5215. porcelain.get_untracked_paths(
  5216. subrepo.path, subrepo.path, subrepo.open_index()
  5217. )
  5218. ),
  5219. )
  5220. self.assertEqual(
  5221. set(),
  5222. set(
  5223. porcelain.get_untracked_paths(
  5224. subrepo.path,
  5225. self.repo.path,
  5226. self.repo.open_index(),
  5227. )
  5228. ),
  5229. )
  5230. self.assertEqual(
  5231. {
  5232. os.path.join("nested", "ignored"),
  5233. os.path.join("nested", "with"),
  5234. os.path.join("nested", "manager"),
  5235. },
  5236. set(
  5237. porcelain.get_untracked_paths(
  5238. self.repo.path,
  5239. subrepo.path,
  5240. self.repo.open_index(),
  5241. )
  5242. ),
  5243. )
  5244. def test_get_untracked_paths_nested_gitignore(self) -> None:
  5245. """Test directories with nested .gitignore files that ignore all contents."""
  5246. # Create cache directories with .gitignore files that contain "*"
  5247. cache_dirs = [".ruff_cache", ".pytest_cache", "__pycache__"]
  5248. for cache_dir in cache_dirs:
  5249. cache_path = os.path.join(self.repo.path, cache_dir)
  5250. os.mkdir(cache_path)
  5251. # Create .gitignore with * pattern (ignores everything)
  5252. with open(os.path.join(cache_path, ".gitignore"), "w") as f:
  5253. f.write("*\n")
  5254. # Create some files in the cache directory
  5255. with open(os.path.join(cache_path, "somefile.txt"), "w") as f:
  5256. f.write("cached data\n")
  5257. with open(os.path.join(cache_path, "data.json"), "w") as f:
  5258. f.write("{}\n")
  5259. # Create a normal untracked file
  5260. with open(os.path.join(self.repo.path, "untracked.txt"), "w") as f:
  5261. f.write("untracked content\n")
  5262. # Test with exclude_ignored=True (default for status)
  5263. untracked = set(
  5264. porcelain.get_untracked_paths(
  5265. self.repo.path,
  5266. self.repo.path,
  5267. self.repo.open_index(),
  5268. exclude_ignored=True,
  5269. untracked_files="normal",
  5270. )
  5271. )
  5272. # Cache directories should NOT be in untracked since all their contents are ignored
  5273. self.assertEqual({"untracked.txt"}, untracked)
  5274. # Test with exclude_ignored=False
  5275. untracked_with_ignored = set(
  5276. porcelain.get_untracked_paths(
  5277. self.repo.path,
  5278. self.repo.path,
  5279. self.repo.open_index(),
  5280. exclude_ignored=False,
  5281. untracked_files="normal",
  5282. )
  5283. )
  5284. # Cache directories should be included when not excluding ignored
  5285. expected = {"untracked.txt"}
  5286. for cache_dir in cache_dirs:
  5287. expected.add(cache_dir + os.sep)
  5288. self.assertEqual(expected, untracked_with_ignored)
  5289. # Test status() which uses exclude_ignored=True by default
  5290. status = porcelain.status(self.repo)
  5291. self.assertEqual(["untracked.txt"], status.untracked)
  5292. # Test status() with ignored=True which uses exclude_ignored=False
  5293. status_with_ignored = porcelain.status(self.repo, ignored=True)
  5294. # Should include cache directories
  5295. self.assertIn("untracked.txt", status_with_ignored.untracked)
  5296. for cache_dir in cache_dirs:
  5297. self.assertIn(cache_dir + "/", status_with_ignored.untracked)
  5298. def test_get_untracked_paths_mixed_directory(self) -> None:
  5299. """Test directory with both ignored and non-ignored files."""
  5300. # Create a directory with mixed content
  5301. mixed_dir = os.path.join(self.repo.path, "mixed")
  5302. os.mkdir(mixed_dir)
  5303. # Create .gitignore that ignores .log files
  5304. with open(os.path.join(mixed_dir, ".gitignore"), "w") as f:
  5305. f.write("*.log\n")
  5306. # Create ignored and non-ignored files
  5307. with open(os.path.join(mixed_dir, "debug.log"), "w") as f:
  5308. f.write("debug info\n")
  5309. with open(os.path.join(mixed_dir, "readme.txt"), "w") as f:
  5310. f.write("important\n")
  5311. # Test with exclude_ignored=True and normal mode
  5312. untracked = set(
  5313. porcelain.get_untracked_paths(
  5314. self.repo.path,
  5315. self.repo.path,
  5316. self.repo.open_index(),
  5317. exclude_ignored=True,
  5318. untracked_files="normal",
  5319. )
  5320. )
  5321. # In normal mode, should show the directory (matching git behavior)
  5322. self.assertEqual({os.path.join("mixed", "")}, untracked)
  5323. # Test with untracked_files="all"
  5324. untracked_all = set(
  5325. porcelain.get_untracked_paths(
  5326. self.repo.path,
  5327. self.repo.path,
  5328. self.repo.open_index(),
  5329. exclude_ignored=True,
  5330. untracked_files="all",
  5331. )
  5332. )
  5333. # Should list the non-ignored files
  5334. expected = {
  5335. os.path.join("mixed", ".gitignore"),
  5336. os.path.join("mixed", "readme.txt"),
  5337. }
  5338. self.assertEqual(expected, untracked_all)
  5339. def test_get_untracked_paths_specific_ignore_pattern(self) -> None:
  5340. """Test directory with .gitignore that ignores specific files, not all."""
  5341. # Create a directory
  5342. test_dir = os.path.join(self.repo.path, "testdir")
  5343. os.mkdir(test_dir)
  5344. # Create .gitignore that ignores only files named "test"
  5345. with open(os.path.join(test_dir, ".gitignore"), "w") as f:
  5346. f.write("test\n")
  5347. # Create files
  5348. with open(os.path.join(test_dir, "test"), "w") as f:
  5349. f.write("ignored\n")
  5350. with open(os.path.join(test_dir, "other.txt"), "w") as f:
  5351. f.write("not ignored\n")
  5352. # Test with exclude_ignored=True and normal mode
  5353. untracked = set(
  5354. porcelain.get_untracked_paths(
  5355. self.repo.path,
  5356. self.repo.path,
  5357. self.repo.open_index(),
  5358. exclude_ignored=True,
  5359. untracked_files="normal",
  5360. )
  5361. )
  5362. # Directory should be shown because it has non-ignored files
  5363. self.assertEqual({os.path.join("testdir", "")}, untracked)
  5364. def test_get_untracked_paths_nested_subdirs_all_ignored(self) -> None:
  5365. """Test directory containing only subdirectories where all files are ignored."""
  5366. # Create parent directory with .gitignore that ignores everything
  5367. parent_dir = os.path.join(self.repo.path, "parent")
  5368. os.mkdir(parent_dir)
  5369. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5370. f.write("*\n")
  5371. # Create subdirectories with files (all should be ignored by parent's .gitignore)
  5372. sub1 = os.path.join(parent_dir, "sub1")
  5373. sub2 = os.path.join(parent_dir, "sub2")
  5374. os.mkdir(sub1)
  5375. os.mkdir(sub2)
  5376. # Create files in subdirectories
  5377. with open(os.path.join(sub1, "file1.txt"), "w") as f:
  5378. f.write("content1\n")
  5379. with open(os.path.join(sub2, "file2.txt"), "w") as f:
  5380. f.write("content2\n")
  5381. # Create another normal untracked file
  5382. with open(os.path.join(self.repo.path, "normal.txt"), "w") as f:
  5383. f.write("normal\n")
  5384. # Test with exclude_ignored=True
  5385. untracked = set(
  5386. porcelain.get_untracked_paths(
  5387. self.repo.path,
  5388. self.repo.path,
  5389. self.repo.open_index(),
  5390. exclude_ignored=True,
  5391. untracked_files="normal",
  5392. )
  5393. )
  5394. # Parent directory should NOT be shown since all nested files are ignored
  5395. self.assertEqual({"normal.txt"}, untracked)
  5396. def test_get_untracked_paths_nested_subdirs_mixed(self) -> None:
  5397. """Test directory containing only subdirectories where some files are ignored, some aren't."""
  5398. # Create parent directory with .gitignore that ignores .log files
  5399. parent_dir = os.path.join(self.repo.path, "parent")
  5400. os.mkdir(parent_dir)
  5401. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5402. f.write("*.log\n")
  5403. # Create subdirectories
  5404. sub1 = os.path.join(parent_dir, "sub1")
  5405. sub2 = os.path.join(parent_dir, "sub2")
  5406. os.mkdir(sub1)
  5407. os.mkdir(sub2)
  5408. # sub1: only ignored files
  5409. with open(os.path.join(sub1, "debug.log"), "w") as f:
  5410. f.write("log content\n")
  5411. with open(os.path.join(sub1, "error.log"), "w") as f:
  5412. f.write("error log\n")
  5413. # sub2: mix of ignored and non-ignored files
  5414. with open(os.path.join(sub2, "access.log"), "w") as f:
  5415. f.write("access log\n")
  5416. with open(os.path.join(sub2, "readme.txt"), "w") as f:
  5417. f.write("important info\n")
  5418. # Test with exclude_ignored=True
  5419. untracked = set(
  5420. porcelain.get_untracked_paths(
  5421. self.repo.path,
  5422. self.repo.path,
  5423. self.repo.open_index(),
  5424. exclude_ignored=True,
  5425. untracked_files="normal",
  5426. )
  5427. )
  5428. # Parent directory SHOULD be shown since sub2 has non-ignored files
  5429. self.assertEqual({os.path.join("parent", "")}, untracked)
  5430. def test_get_untracked_paths_deeply_nested_all_ignored(self) -> None:
  5431. """Test deeply nested directories where all files are eventually ignored."""
  5432. # Create nested structure: parent/sub/subsub/
  5433. parent_dir = os.path.join(self.repo.path, "parent")
  5434. sub_dir = os.path.join(parent_dir, "sub")
  5435. subsub_dir = os.path.join(sub_dir, "subsub")
  5436. os.makedirs(subsub_dir)
  5437. # Parent has .gitignore that ignores everything
  5438. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5439. f.write("*\n")
  5440. # Create files at different levels
  5441. with open(os.path.join(subsub_dir, "deep_file.txt"), "w") as f:
  5442. f.write("deep content\n")
  5443. with open(os.path.join(sub_dir, "mid_file.txt"), "w") as f:
  5444. f.write("mid content\n")
  5445. # Test with exclude_ignored=True
  5446. untracked = set(
  5447. porcelain.get_untracked_paths(
  5448. self.repo.path,
  5449. self.repo.path,
  5450. self.repo.open_index(),
  5451. exclude_ignored=True,
  5452. untracked_files="normal",
  5453. )
  5454. )
  5455. # Parent directory should NOT be shown since all nested files are ignored
  5456. self.assertEqual(set(), untracked)
  5457. def test_get_untracked_paths_subdir(self) -> None:
  5458. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5459. f.write("subdir/\nignored")
  5460. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5461. f.write("blah\n")
  5462. os.mkdir(os.path.join(self.repo.path, "subdir"))
  5463. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  5464. f.write("foo")
  5465. with open(os.path.join(self.repo.path, "subdir", "ignored"), "w") as f:
  5466. f.write("foo")
  5467. self.assertEqual(
  5468. {
  5469. ".gitignore",
  5470. "notignored",
  5471. "ignored",
  5472. os.path.join("subdir", ""),
  5473. },
  5474. set(
  5475. porcelain.get_untracked_paths(
  5476. self.repo.path,
  5477. self.repo.path,
  5478. self.repo.open_index(),
  5479. )
  5480. ),
  5481. )
  5482. self.assertEqual(
  5483. {".gitignore", "notignored"},
  5484. set(
  5485. porcelain.get_untracked_paths(
  5486. self.repo.path,
  5487. self.repo.path,
  5488. self.repo.open_index(),
  5489. exclude_ignored=True,
  5490. )
  5491. ),
  5492. )
  5493. def test_get_untracked_paths_invalid_untracked_files(self) -> None:
  5494. with self.assertRaises(ValueError):
  5495. list(
  5496. porcelain.get_untracked_paths(
  5497. self.repo.path,
  5498. self.repo.path,
  5499. self.repo.open_index(),
  5500. untracked_files="invalid_value",
  5501. )
  5502. )
  5503. def test_get_untracked_paths_normal(self) -> None:
  5504. # Create an untracked directory with files
  5505. untracked_dir = os.path.join(self.repo.path, "untracked_dir")
  5506. os.mkdir(untracked_dir)
  5507. with open(os.path.join(untracked_dir, "file1.txt"), "w") as f:
  5508. f.write("untracked content")
  5509. with open(os.path.join(untracked_dir, "file2.txt"), "w") as f:
  5510. f.write("more untracked content")
  5511. # Test that "normal" mode works and returns only the directory
  5512. _, _, untracked = porcelain.status(
  5513. repo=self.repo.path, untracked_files="normal"
  5514. )
  5515. self.assertEqual(untracked, ["untracked_dir/"])
  5516. def test_get_untracked_paths_top_level_issue_1247(self) -> None:
  5517. """Test for issue #1247: ensure top-level untracked files are detected."""
  5518. # Create a single top-level untracked file
  5519. with open(os.path.join(self.repo.path, "sample.txt"), "w") as f:
  5520. f.write("test content")
  5521. # Test get_untracked_paths directly
  5522. untracked = list(
  5523. porcelain.get_untracked_paths(
  5524. self.repo.path, self.repo.path, self.repo.open_index()
  5525. )
  5526. )
  5527. self.assertIn(
  5528. "sample.txt",
  5529. untracked,
  5530. "Top-level file 'sample.txt' should be in untracked list",
  5531. )
  5532. # Test via status
  5533. status = porcelain.status(self.repo)
  5534. self.assertIn(
  5535. "sample.txt",
  5536. status.untracked,
  5537. "Top-level file 'sample.txt' should be in status.untracked",
  5538. )
  5539. # TODO(jelmer): Add test for dulwich.porcelain.daemon
  5540. class ShortlogTests(PorcelainTestCase):
  5541. def test_shortlog(self) -> None:
  5542. """Test porcelain.shortlog function with multiple authors and commits."""
  5543. # Create first file and commit
  5544. file_a = os.path.join(self.repo.path, "a.txt")
  5545. with open(file_a, "w") as f:
  5546. f.write("hello")
  5547. porcelain.add(self.repo.path, paths=[file_a])
  5548. porcelain.commit(
  5549. repo=self.repo.path,
  5550. message=b"Initial commit",
  5551. author=b"John <john@example.com>",
  5552. )
  5553. # Create second file and commit
  5554. file_b = os.path.join(self.repo.path, "b.txt")
  5555. with open(file_b, "w") as f:
  5556. f.write("update")
  5557. porcelain.add(self.repo.path, paths=[file_b])
  5558. porcelain.commit(
  5559. repo=self.repo.path,
  5560. message=b"Update file",
  5561. author=b"Doe <doe@example.com>",
  5562. )
  5563. # Call shortlog
  5564. output = porcelain.shortlog(self.repo.path)
  5565. expected = [
  5566. {"author": "John <john@example.com>", "messages": "Initial commit"},
  5567. {"author": "Doe <doe@example.com>", "messages": "Update file"},
  5568. ]
  5569. self.assertCountEqual(output, expected)
  5570. # Test summary output (count of messages)
  5571. output_summary = [
  5572. {"author": entry["author"], "count": len(entry["messages"].splitlines())}
  5573. for entry in output
  5574. ]
  5575. expected_summary = [
  5576. {"author": "John <john@example.com>", "count": 1},
  5577. {"author": "Doe <doe@example.com>", "count": 1},
  5578. ]
  5579. self.assertCountEqual(output_summary, expected_summary)
  5580. class UploadPackTests(PorcelainTestCase):
  5581. """Tests for upload_pack."""
  5582. def test_upload_pack(self) -> None:
  5583. outf = BytesIO()
  5584. exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf)
  5585. outlines = outf.getvalue().splitlines()
  5586. self.assertEqual([b"0000"], outlines)
  5587. self.assertEqual(0, exitcode)
  5588. class ReceivePackTests(PorcelainTestCase):
  5589. """Tests for receive_pack."""
  5590. def test_receive_pack(self) -> None:
  5591. filename = "foo"
  5592. fullpath = os.path.join(self.repo.path, filename)
  5593. with open(fullpath, "w") as f:
  5594. f.write("stuff")
  5595. porcelain.add(repo=self.repo.path, paths=fullpath)
  5596. self.repo.get_worktree().commit(
  5597. message=b"test status",
  5598. committer=b"committer <email>",
  5599. author=b"author <email>",
  5600. commit_timestamp=1402354300,
  5601. commit_timezone=0,
  5602. author_timestamp=1402354300,
  5603. author_timezone=0,
  5604. )
  5605. outf = BytesIO()
  5606. exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf)
  5607. outlines = outf.getvalue().splitlines()
  5608. self.assertEqual(
  5609. [
  5610. b"0091319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status "
  5611. b"delete-refs quiet ofs-delta side-band-64k "
  5612. b"no-done symref=HEAD:refs/heads/master",
  5613. b"003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master",
  5614. b"0000",
  5615. ],
  5616. outlines,
  5617. )
  5618. self.assertEqual(0, exitcode)
  5619. class BranchListTests(PorcelainTestCase):
  5620. def test_standard(self) -> None:
  5621. self.assertEqual(set(), set(porcelain.branch_list(self.repo)))
  5622. def test_new_branch(self) -> None:
  5623. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5624. self.repo[b"HEAD"] = c1.id
  5625. porcelain.branch_create(self.repo, b"foo")
  5626. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  5627. def test_sort_by_refname(self) -> None:
  5628. """Test branch.sort=refname (default alphabetical)."""
  5629. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5630. self.repo[b"HEAD"] = c1.id
  5631. # Create branches in non-alphabetical order
  5632. porcelain.branch_create(self.repo, b"zebra")
  5633. porcelain.branch_create(self.repo, b"alpha")
  5634. porcelain.branch_create(self.repo, b"beta")
  5635. # Set branch.sort to refname (though it's the default)
  5636. config = self.repo.get_config()
  5637. config.set((b"branch",), b"sort", b"refname")
  5638. config.write_to_path()
  5639. # Should be sorted alphabetically
  5640. branches = porcelain.branch_list(self.repo)
  5641. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5642. def test_sort_by_refname_reverse(self) -> None:
  5643. """Test branch.sort=-refname (reverse alphabetical)."""
  5644. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5645. self.repo[b"HEAD"] = c1.id
  5646. # Create branches
  5647. porcelain.branch_create(self.repo, b"zebra")
  5648. porcelain.branch_create(self.repo, b"alpha")
  5649. porcelain.branch_create(self.repo, b"beta")
  5650. # Set branch.sort to -refname
  5651. config = self.repo.get_config()
  5652. config.set((b"branch",), b"sort", b"-refname")
  5653. config.write_to_path()
  5654. # Should be sorted reverse alphabetically
  5655. branches = porcelain.branch_list(self.repo)
  5656. self.assertEqual([b"zebra", b"master", b"beta", b"alpha"], branches)
  5657. def test_sort_by_committerdate(self) -> None:
  5658. """Test branch.sort=committerdate."""
  5659. # Use build_commit_graph to create proper commits with specific times
  5660. c1, c2, c3 = build_commit_graph(
  5661. self.repo.object_store,
  5662. [[1], [2], [3]],
  5663. attrs={
  5664. 1: {"commit_time": 1000}, # oldest
  5665. 2: {"commit_time": 2000}, # newest
  5666. 3: {"commit_time": 1500}, # middle
  5667. },
  5668. )
  5669. self.repo[b"HEAD"] = c1.id
  5670. # Create branches pointing to different commits
  5671. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  5672. self.repo.refs[b"refs/heads/oldest"] = c1.id
  5673. self.repo.refs[b"refs/heads/newest"] = c2.id
  5674. self.repo.refs[b"refs/heads/middle"] = c3.id
  5675. # Set branch.sort to committerdate
  5676. config = self.repo.get_config()
  5677. config.set((b"branch",), b"sort", b"committerdate")
  5678. config.write_to_path()
  5679. # Should be sorted by commit time (oldest first)
  5680. branches = porcelain.branch_list(self.repo)
  5681. self.assertEqual([b"master", b"oldest", b"middle", b"newest"], branches)
  5682. def test_sort_by_committerdate_reverse(self) -> None:
  5683. """Test branch.sort=-committerdate."""
  5684. # Use build_commit_graph to create proper commits with specific times
  5685. c1, c2, c3 = build_commit_graph(
  5686. self.repo.object_store,
  5687. [[1], [2], [3]],
  5688. attrs={
  5689. 1: {"commit_time": 1000}, # oldest
  5690. 2: {"commit_time": 2000}, # newest
  5691. 3: {"commit_time": 1500}, # middle
  5692. },
  5693. )
  5694. self.repo[b"HEAD"] = c1.id
  5695. # Create branches pointing to different commits
  5696. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  5697. self.repo.refs[b"refs/heads/oldest"] = c1.id
  5698. self.repo.refs[b"refs/heads/newest"] = c2.id
  5699. self.repo.refs[b"refs/heads/middle"] = c3.id
  5700. # Set branch.sort to -committerdate
  5701. config = self.repo.get_config()
  5702. config.set((b"branch",), b"sort", b"-committerdate")
  5703. config.write_to_path()
  5704. # Should be sorted by commit time (newest first)
  5705. branches = porcelain.branch_list(self.repo)
  5706. self.assertEqual([b"newest", b"middle", b"master", b"oldest"], branches)
  5707. def test_sort_default(self) -> None:
  5708. """Test default sorting (no config)."""
  5709. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5710. self.repo[b"HEAD"] = c1.id
  5711. # Create branches in non-alphabetical order
  5712. porcelain.branch_create(self.repo, b"zebra")
  5713. porcelain.branch_create(self.repo, b"alpha")
  5714. porcelain.branch_create(self.repo, b"beta")
  5715. # No config set - should default to alphabetical
  5716. branches = porcelain.branch_list(self.repo)
  5717. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5718. class BranchRemoteListTests(PorcelainTestCase):
  5719. def test_no_remote_branches(self) -> None:
  5720. """Test with no remote branches."""
  5721. result = porcelain.branch_remotes_list(self.repo)
  5722. self.assertEqual([], result)
  5723. def test_remote_branches_refname_sort(self) -> None:
  5724. """Test remote branches sorting with refname (alphabetical)."""
  5725. # Create some remote branches
  5726. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5727. # Create remote branches is non-alphabetical order
  5728. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  5729. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  5730. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  5731. self.repo.refs[b"refs/remotes/origin/feature-4"] = c1.id
  5732. # Set branch.sort to refname
  5733. config = self.repo.get_config()
  5734. config.set((b"branch",), b"sort", b"refname")
  5735. config.write_to_path()
  5736. # Should return only branch names, sorted alphabetically
  5737. branches = porcelain.branch_remotes_list(self.repo)
  5738. expected = [
  5739. b"origin/feature-1",
  5740. b"origin/feature-2",
  5741. b"origin/feature-3",
  5742. b"origin/feature-4",
  5743. ]
  5744. self.assertEqual(expected, branches)
  5745. def test_remote_branches_refname_reverse_sort(self) -> None:
  5746. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5747. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  5748. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  5749. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  5750. self.repo.refs[b"refs/remotes/origin/feature-4"] = c1.id
  5751. # Set branch.sort to -refname
  5752. config = self.repo.get_config()
  5753. config.set((b"branch",), b"sort", b"-refname")
  5754. config.write_to_path()
  5755. branches = porcelain.branch_remotes_list(self.repo)
  5756. expected = [
  5757. b"origin/feature-4",
  5758. b"origin/feature-3",
  5759. b"origin/feature-2",
  5760. b"origin/feature-1",
  5761. ]
  5762. self.assertEqual(expected, branches)
  5763. def test_remote_branches_committerdate_sort(self) -> None:
  5764. """Test remote branches sorting with committerdate"""
  5765. # Create commits with different timestamps
  5766. c1, c2, c3 = build_commit_graph(
  5767. self.repo.object_store,
  5768. [[1], [2], [3]],
  5769. attrs={
  5770. 1: {"commit_time": 1000},
  5771. 2: {"commit_time": 2000},
  5772. 3: {"commit_time": 3000},
  5773. },
  5774. )
  5775. self.repo.refs[b"refs/remotes/origin/oldest"] = c1.id
  5776. self.repo.refs[b"refs/remotes/origin/middle"] = c2.id
  5777. self.repo.refs[b"refs/remotes/origin/newest"] = c3.id
  5778. # Set branch.sort to committerdate
  5779. config = self.repo.get_config()
  5780. config.set((b"branch",), b"sort", b"committerdate")
  5781. config.write_to_path()
  5782. branches = porcelain.branch_remotes_list(self.repo)
  5783. # Should be sorted by commit time (oldest first), then alphabetically for same time
  5784. expected = [b"origin/oldest", b"origin/middle", b"origin/newest"]
  5785. self.assertEqual(expected, branches)
  5786. def test_remote_branches_committerdate_reverse_sort(self) -> None:
  5787. """Test remote branches sorting with -committerdate."""
  5788. c1, c2, c3 = build_commit_graph(
  5789. self.repo.object_store,
  5790. [[1], [2], [3]],
  5791. attrs={
  5792. 1: {"commit_time": 1000},
  5793. 2: {"commit_time": 2000},
  5794. 3: {"commit_time": 1500},
  5795. },
  5796. )
  5797. self.repo.refs[b"refs/remotes/origin/oldest"] = c1.id
  5798. self.repo.refs[b"refs/remotes/origin/newest"] = c2.id
  5799. self.repo.refs[b"refs/remotes/origin/middle"] = c3.id
  5800. # Set branch.sort to -committerdate
  5801. config = self.repo.get_config()
  5802. config.set((b"branch",), b"sort", b"-committerdate")
  5803. config.write_to_path()
  5804. branches = porcelain.branch_remotes_list(self.repo)
  5805. # Should be sorted by commit time (newest first), then alphabetically for same time
  5806. expected = [b"origin/newest", b"origin/middle", b"origin/oldest"]
  5807. self.assertEqual(expected, branches)
  5808. def test_remote_branches_authordate_sort(self) -> None:
  5809. """Test remote branches sorting with authordate."""
  5810. c1, c2, c3 = build_commit_graph(
  5811. self.repo.object_store,
  5812. [[1], [2], [3]],
  5813. attrs={
  5814. 1: {"author_time": 1500},
  5815. 2: {"author_time": 2000},
  5816. 3: {"author_time": 1000},
  5817. },
  5818. )
  5819. self.repo.refs[b"refs/remotes/origin/middle"] = c1.id
  5820. self.repo.refs[b"refs/remotes/origin/newest"] = c2.id
  5821. self.repo.refs[b"refs/remotes/origin/oldest"] = c3.id
  5822. # Set branch.sort to authordate
  5823. config = self.repo.get_config()
  5824. config.set((b"branch",), b"sort", b"authordate")
  5825. config.write_to_path()
  5826. branches = porcelain.branch_remotes_list(self.repo)
  5827. expected = [b"origin/oldest", b"origin/middle", b"origin/newest"]
  5828. self.assertEqual(expected, branches)
  5829. def test_unknown_sort_key(self) -> None:
  5830. """Test that unknown sort key raises ValueError."""
  5831. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5832. self.repo.refs[b"refs/remotes/origin/master"] = c1.id
  5833. # Set branch.sort to unknown key
  5834. config = self.repo.get_config()
  5835. config.set((b"branch",), b"sort", b"unknown")
  5836. config.write_to_path()
  5837. with self.assertRaises(ValueError) as cm:
  5838. porcelain.branch_remotes_list(self.repo)
  5839. self.assertIn("Unknown sort key: unknown", str(cm.exception))
  5840. def test_default_sort_no_config(self) -> None:
  5841. """Test default sorting when no config is set."""
  5842. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5843. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  5844. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  5845. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  5846. # No config set - should default to alphabetical
  5847. branches = porcelain.branch_remotes_list(self.repo)
  5848. expected = [b"origin/feature-1", b"origin/feature-2", b"origin/feature-3"]
  5849. self.assertEqual(expected, branches)
  5850. class BranchMergedTests(PorcelainTestCase):
  5851. def test_no_merged_branches(self) -> None:
  5852. """Test with no merged branches."""
  5853. # Create complete graph: c1 → c2 (master), c1 → c3 (feature)
  5854. [_c1, c2, c3] = build_commit_graph(
  5855. self.repo.object_store,
  5856. [
  5857. [1], # c1
  5858. [2, 1], # c2 → c1 (master line)
  5859. [3, 1], # c3 → c1 (diverged feature branch)
  5860. ],
  5861. )
  5862. self.repo.refs[b"HEAD"] = c2.id
  5863. self.repo.refs[b"refs/heads/master"] = c2.id
  5864. self.repo.refs[b"refs/heads/feature"] = c3.id
  5865. result = list(porcelain.merged_branches(self.repo))
  5866. self.assertEqual([b"master"], result)
  5867. def test_all_branches_merged(self) -> None:
  5868. """Test when all branches are merged into current."""
  5869. # Create linear history: c1 → c2 → c3 (HEAD)
  5870. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  5871. self.repo.refs[b"HEAD"] = c3.id
  5872. self.repo.refs[b"refs/heads/master"] = c3.id
  5873. self.repo.refs[b"refs/heads/feature-1"] = c2.id # Merged (ancestor)
  5874. self.repo.refs[b"refs/heads/feature-2"] = c1.id # Merged (ancestor)
  5875. branches = list(porcelain.merged_branches(self.repo))
  5876. expected = [b"feature-1", b"master", b"feature-2"]
  5877. expected.sort()
  5878. branches.sort()
  5879. self.assertEqual(expected, branches)
  5880. def test_some_branches_merged(self) -> None:
  5881. """Test when some branches are merged, some are not."""
  5882. # c1 → c2 → c3 (HEAD/master)
  5883. # c1 → c4 → c5 (feature-1 - diverged)
  5884. [_c1, c2, c3, _c4, c5] = build_commit_graph(
  5885. self.repo.object_store,
  5886. [
  5887. [1], # c1
  5888. [2, 1], # c2 → c1 (master line)
  5889. [3, 2], # c3 → c2 (HEAD)
  5890. [4, 1], # c4 → c1 (feature branch)
  5891. [5, 4], # c5 → c4 (feature branch)
  5892. ],
  5893. )
  5894. self.repo.refs[b"HEAD"] = c3.id
  5895. self.repo.refs[b"refs/heads/master"] = c3.id
  5896. self.repo.refs[b"refs/heads/feature-1"] = c5.id # Not merged (diverged)
  5897. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Merged (ancestor)
  5898. branches = list(porcelain.merged_branches(self.repo))
  5899. expected = [b"feature-2", b"master"]
  5900. expected.sort()
  5901. branches.sort()
  5902. self.assertEqual(expected, branches)
  5903. def test_only_current_branch_merged(self) -> None:
  5904. """Test when only current branch exists."""
  5905. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5906. self.repo.refs[b"HEAD"] = c1.id
  5907. self.repo.refs[b"refs/heads/master"] = c1.id
  5908. result = list(porcelain.merged_branches(self.repo))
  5909. self.assertEqual([b"master"], result)
  5910. class BranchNoMergedTests(PorcelainTestCase):
  5911. def test_all_branches_merged(self) -> None:
  5912. """Test when all branches are merged - should return empty list."""
  5913. # Create linear history: c1 → c2 → c3 (HEAD)
  5914. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  5915. self.repo.refs[b"HEAD"] = c3.id
  5916. self.repo.refs[b"refs/heads/master"] = c3.id
  5917. self.repo.refs[b"refs/heads/feature-1"] = c2.id # Merged (ancestor)
  5918. self.repo.refs[b"refs/heads/feature-2"] = c1.id # Merged (ancestor)
  5919. result = list(porcelain.no_merged_branches(self.repo))
  5920. self.assertEqual([], result)
  5921. def test_no_merged_branches(self) -> None:
  5922. """Test with some non-merged branches."""
  5923. # Create complete graph: c1 → c2 (master), c1 → c3 (feature)
  5924. [_c1, c2, c3] = build_commit_graph(
  5925. self.repo.object_store,
  5926. [
  5927. [1], # c1
  5928. [2, 1], # c2 → c1 (master line)
  5929. [3, 1], # c3 → c1 (diverged feature branch)
  5930. ],
  5931. )
  5932. self.repo.refs[b"HEAD"] = c2.id
  5933. self.repo.refs[b"refs/heads/master"] = c2.id
  5934. self.repo.refs[b"refs/heads/feature"] = c3.id
  5935. result = list(porcelain.no_merged_branches(self.repo))
  5936. self.assertEqual([b"feature"], result)
  5937. def test_some_branches_not_merged(self) -> None:
  5938. """Test when some branches are merged, some are not."""
  5939. # c1 → c2 → c3 (HEAD/master)
  5940. # c1 → c4 → c5 (feature-1 - diverged)
  5941. [_c1, c2, c3, _c4, c5] = build_commit_graph(
  5942. self.repo.object_store,
  5943. [
  5944. [1], # c1
  5945. [2, 1], # c2 → c1 (master line)
  5946. [3, 2], # c3 → c2 (HEAD)
  5947. [4, 1], # c4 → c1 (feature branch)
  5948. [5, 4], # c5 → c4 (feature branch)
  5949. ],
  5950. )
  5951. self.repo.refs[b"HEAD"] = c3.id
  5952. self.repo.refs[b"refs/heads/master"] = c3.id
  5953. self.repo.refs[b"refs/heads/feature-1"] = c5.id # Not merged (diverged)
  5954. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Merged (ancestor)
  5955. result = list(porcelain.no_merged_branches(self.repo))
  5956. self.assertEqual([b"feature-1"], result)
  5957. def test_multiple_branches_not_merged(self) -> None:
  5958. """Test with multiple non-merged branches."""
  5959. # c1 → c2 (HEAD/master)
  5960. # c1 → c3 (feature-1 - diverged)
  5961. # c1 → c4 (feature-2 - diverged)
  5962. [_c1, c2, c3, c4] = build_commit_graph(
  5963. self.repo.object_store,
  5964. [
  5965. [1], # c1
  5966. [2, 1], # c2 → c1 (master line)
  5967. [3, 1], # c3 → c1 (feature-1 branch)
  5968. [4, 1], # c4 → c1 (feature-2 branch)
  5969. ],
  5970. )
  5971. self.repo.refs[b"HEAD"] = c2.id
  5972. self.repo.refs[b"refs/heads/master"] = c2.id
  5973. self.repo.refs[b"refs/heads/feature-1"] = c3.id # Not merged (diverged)
  5974. self.repo.refs[b"refs/heads/feature-2"] = c4.id # Not merged (diverged)
  5975. branches = list(porcelain.no_merged_branches(self.repo))
  5976. expected = [b"feature-1", b"feature-2"]
  5977. expected.sort()
  5978. branches.sort()
  5979. self.assertEqual(expected, branches)
  5980. def test_only_current_branch_exists(self) -> None:
  5981. """Test when only current branch exists - should return empty list."""
  5982. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5983. self.repo.refs[b"HEAD"] = c1.id
  5984. self.repo.refs[b"refs/heads/master"] = c1.id
  5985. result = list(porcelain.no_merged_branches(self.repo))
  5986. self.assertEqual([], result)
  5987. class BranchContainsTests(PorcelainTestCase):
  5988. def test_commit_in_single_branch(self) -> None:
  5989. """Test commit contained in only one branch."""
  5990. # Create: c1 → c2 (master), c1 → c3 (feature)
  5991. [_c1, c2, c3] = build_commit_graph(
  5992. self.repo.object_store,
  5993. [
  5994. [1], # c1
  5995. [2, 1], # c2 → c1 (master line)
  5996. [3, 1], # c3 → c1 (feature branch)
  5997. ],
  5998. )
  5999. self.repo.refs[b"HEAD"] = c2.id
  6000. self.repo.refs[b"refs/heads/master"] = c2.id
  6001. self.repo.refs[b"refs/heads/feature"] = c3.id
  6002. # c2 is only in master branch
  6003. result = list(porcelain.branches_containing(self.repo, c2.id.decode()))
  6004. self.assertEqual([b"master"], result)
  6005. # c3 is only in feature branch
  6006. result = list(porcelain.branches_containing(self.repo, c3.id.decode()))
  6007. self.assertEqual([b"feature"], result)
  6008. def test_commit_in_multiple_branches(self) -> None:
  6009. """Test commit contained in multiple branches."""
  6010. # Create: c1 → c2 → c3 (master), c2 → c4 (feature)
  6011. [c1, c2, c3, c4] = build_commit_graph(
  6012. self.repo.object_store,
  6013. [
  6014. [1], # c1
  6015. [2, 1], # c2 → c1
  6016. [3, 2], # c3 → c2 (master)
  6017. [4, 2], # c4 → c2 (feature)
  6018. ],
  6019. )
  6020. self.repo.refs[b"HEAD"] = c3.id
  6021. self.repo.refs[b"refs/heads/master"] = c3.id
  6022. self.repo.refs[b"refs/heads/feature"] = c4.id
  6023. # c2 is in both branches (common ancestor)
  6024. branches = list(porcelain.branches_containing(self.repo, c2.id.decode()))
  6025. expected = [b"master", b"feature"]
  6026. expected.sort()
  6027. branches.sort()
  6028. self.assertEqual(expected, branches)
  6029. # c1 is in both branches (older common ancestor)
  6030. branches = list(porcelain.branches_containing(self.repo, c1.id.decode()))
  6031. expected = [b"master", b"feature"]
  6032. expected.sort()
  6033. branches.sort()
  6034. self.assertEqual(expected, branches)
  6035. def test_commit_in_all_branches(self) -> None:
  6036. """Test commit contained in all branches."""
  6037. # Create linear history: c1 → c2 → c3 (HEAD/master)
  6038. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  6039. self.repo.refs[b"HEAD"] = c3.id
  6040. self.repo.refs[b"refs/heads/master"] = c3.id
  6041. self.repo.refs[b"refs/heads/feature-1"] = c3.id # Same as master
  6042. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Ancestor
  6043. # c1 is in all branches
  6044. branches = list(porcelain.branches_containing(self.repo, c1.id.decode()))
  6045. expected = [b"master", b"feature-1", b"feature-2"]
  6046. expected.sort()
  6047. branches.sort()
  6048. self.assertEqual(expected, branches)
  6049. def test_commit_in_no_branches(self) -> None:
  6050. """Test commit not contained in any branch."""
  6051. # Create: c1 → c2 (master), c1 → c3 (feature), orphan c4
  6052. [_c1, c2, c3, c4] = build_commit_graph(
  6053. self.repo.object_store,
  6054. [
  6055. [1], # c1
  6056. [2, 1], # c2 → c1 (master)
  6057. [3, 1], # c3 → c1 (feature)
  6058. [4], # c4 (orphan commit)
  6059. ],
  6060. )
  6061. self.repo.refs[b"HEAD"] = c2.id
  6062. self.repo.refs[b"refs/heads/master"] = c2.id
  6063. self.repo.refs[b"refs/heads/feature"] = c3.id
  6064. # c4 is not in any branch
  6065. result = list(porcelain.branches_containing(self.repo, c4.id.decode()))
  6066. self.assertEqual([], result)
  6067. def test_commit_ref_by_branch_name(self) -> None:
  6068. """Test using branch name as commit reference."""
  6069. # Create: c1 → c2 (master), c1 → c3 (feature)
  6070. [_c1, c2, c3] = build_commit_graph(
  6071. self.repo.object_store,
  6072. [
  6073. [1], # c1
  6074. [2, 1], # c2 → c1 (master)
  6075. [3, 1], # c3 → c1 (feature)
  6076. ],
  6077. )
  6078. self.repo.refs[b"HEAD"] = c2.id
  6079. self.repo.refs[b"refs/heads/master"] = c2.id
  6080. self.repo.refs[b"refs/heads/feature"] = c3.id
  6081. # Use "master" as commit reference - should find master branch
  6082. result = list(porcelain.branches_containing(self.repo, "master"))
  6083. self.assertEqual([b"master"], result)
  6084. # Use "feature" as commit reference - should find feature branch
  6085. result = list(porcelain.branches_containing(self.repo, "feature"))
  6086. self.assertEqual([b"feature"], result)
  6087. def test_commit_ref_by_head(self) -> None:
  6088. """Test using HEAD as commit reference."""
  6089. # Create: c1 → c2 → c3 (HEAD/master)
  6090. [_c1, c2, c3] = build_commit_graph(
  6091. self.repo.object_store, [[1], [2, 1], [3, 2]]
  6092. )
  6093. self.repo.refs[b"HEAD"] = c3.id
  6094. self.repo.refs[b"refs/heads/master"] = c3.id
  6095. self.repo.refs[b"refs/heads/feature"] = c2.id # Ancestor
  6096. # Use "HEAD" as commit reference
  6097. result = list(porcelain.branches_containing(self.repo, "HEAD"))
  6098. self.assertEqual([b"master"], result)
  6099. def test_invalid_commit_ref(self) -> None:
  6100. """Test with invalid commit reference."""
  6101. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6102. self.repo.refs[b"HEAD"] = c1.id
  6103. self.repo.refs[b"refs/heads/master"] = c1.id
  6104. # Test with non-existent commit
  6105. with self.assertRaises(KeyError) as cm:
  6106. list(porcelain.branches_containing(self.repo, "nonexistent"))
  6107. self.assertEqual(b"nonexistent", cm.exception.args[0])
  6108. # Test with invalid SHA
  6109. with self.assertRaises(KeyError) as cm:
  6110. list(porcelain.branches_containing(self.repo, "invalid-sha"))
  6111. self.assertEqual(b"invalid-sha", cm.exception.args[0])
  6112. def test_short_sha_reference(self) -> None:
  6113. """Test using short SHA as commit reference."""
  6114. # Create: c1 → c2 (master)
  6115. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2, 1]])
  6116. self.repo.refs[b"HEAD"] = c2.id
  6117. self.repo.refs[b"refs/heads/master"] = c2.id
  6118. # Use short SHA (first 7 characters)
  6119. short_sha = c1.id.decode()[:7]
  6120. result = list(porcelain.branches_containing(self.repo, short_sha))
  6121. self.assertEqual([b"master"], result)
  6122. class FilterBranchesByPatternTests(PorcelainTestCase):
  6123. """Tests for filter_branches_by_pattern function."""
  6124. def test_empty_branches(self) -> None:
  6125. """Test with empty branches list."""
  6126. result = porcelain.filter_branches_by_pattern([], "feature-*")
  6127. self.assertEqual([], result)
  6128. def test_star_pattern(self) -> None:
  6129. """Test wildcard pattern matching."""
  6130. branches = [b"main", b"feature-1", b"feature-2", b"develop", b"hotfix-bug"]
  6131. result = porcelain.filter_branches_by_pattern(branches, "feature-*")
  6132. expected = [b"feature-1", b"feature-2"]
  6133. self.assertEqual(expected, result)
  6134. def test_question_mark_pattern(self) -> None:
  6135. """Test single character wildcard pattern."""
  6136. branches = [b"main", b"feature-1", b"feature-2", b"feature-a", b"develop"]
  6137. result = porcelain.filter_branches_by_pattern(branches, "feature-?")
  6138. expected = [b"feature-1", b"feature-2", b"feature-a"]
  6139. self.assertEqual(expected, result)
  6140. def test_specific_pattern(self) -> None:
  6141. """Test exact match pattern."""
  6142. branches = [b"main", b"feature-1", b"feature-2", b"develop"]
  6143. result = porcelain.filter_branches_by_pattern(branches, "feature-1")
  6144. expected = [b"feature-1"]
  6145. self.assertEqual(expected, result)
  6146. def test_no_matches(self) -> None:
  6147. """Test pattern that matches no branches."""
  6148. branches = [b"main", b"feature-1", b"develop"]
  6149. result = porcelain.filter_branches_by_pattern(branches, "release-*")
  6150. self.assertEqual([], result)
  6151. def test_case_sensitive_pattern(self) -> None:
  6152. """Test case-sensitive pattern matching."""
  6153. branches = [b"Main", b"main", b"MAIN", b"develop"]
  6154. result = porcelain.filter_branches_by_pattern(branches, "main")
  6155. expected = [b"main"]
  6156. self.assertEqual(expected, result)
  6157. def test_multiple_patterns_behavior(self) -> None:
  6158. """Test that pattern works with multiple wildcards."""
  6159. branches = [
  6160. b"feature-login",
  6161. b"feature-signup",
  6162. b"bugfix-login",
  6163. b"hotfix-signup",
  6164. ]
  6165. result = porcelain.filter_branches_by_pattern(branches, "feature-*")
  6166. expected = [b"feature-login", b"feature-signup"]
  6167. self.assertEqual(expected, result)
  6168. def test_mixed_encoding_branches(self) -> None:
  6169. """Test with branches that have special characters."""
  6170. branches = [b"feature-1", b"feature/test", b"feature@prod", b"develop"]
  6171. result = porcelain.filter_branches_by_pattern(branches, "feature/*")
  6172. expected = [b"feature/test"]
  6173. self.assertEqual(expected, result)
  6174. def test_pattern_with_square_brackets(self) -> None:
  6175. """Test pattern with character classes."""
  6176. branches = [b"feature-1", b"feature-2", b"feature-a", b"feature-b", b"develop"]
  6177. result = porcelain.filter_branches_by_pattern(branches, "feature-[12]")
  6178. expected = [b"feature-1", b"feature-2"]
  6179. self.assertEqual(expected, result)
  6180. class BranchCreateTests(PorcelainTestCase):
  6181. def test_branch_exists(self) -> None:
  6182. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6183. self.repo[b"HEAD"] = c1.id
  6184. porcelain.branch_create(self.repo, b"foo")
  6185. self.assertRaises(porcelain.Error, porcelain.branch_create, self.repo, b"foo")
  6186. porcelain.branch_create(self.repo, b"foo", force=True)
  6187. def test_new_branch(self) -> None:
  6188. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6189. self.repo[b"HEAD"] = c1.id
  6190. porcelain.branch_create(self.repo, b"foo")
  6191. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  6192. def test_auto_setup_merge_true_from_remote_tracking(self) -> None:
  6193. """Test branch.autoSetupMerge=true sets up tracking from remote-tracking branch."""
  6194. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6195. self.repo[b"HEAD"] = c1.id
  6196. # Create a remote-tracking branch
  6197. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6198. # Set branch.autoSetupMerge to true (default)
  6199. config = self.repo.get_config()
  6200. config.set((b"branch",), b"autoSetupMerge", b"true")
  6201. config.write_to_path()
  6202. # Create branch from remote-tracking branch
  6203. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6204. # Verify tracking was set up
  6205. config = self.repo.get_config()
  6206. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6207. self.assertEqual(
  6208. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6209. )
  6210. def test_auto_setup_merge_false(self) -> None:
  6211. """Test branch.autoSetupMerge=false disables tracking setup."""
  6212. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6213. self.repo[b"HEAD"] = c1.id
  6214. # Create a remote-tracking branch
  6215. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6216. # Set branch.autoSetupMerge to false
  6217. config = self.repo.get_config()
  6218. config.set((b"branch",), b"autoSetupMerge", b"false")
  6219. config.write_to_path()
  6220. # Create branch from remote-tracking branch
  6221. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6222. # Verify tracking was NOT set up
  6223. config = self.repo.get_config()
  6224. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"remote")
  6225. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"merge")
  6226. def test_auto_setup_merge_always(self) -> None:
  6227. """Test branch.autoSetupMerge=always sets up tracking even from local branches."""
  6228. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6229. self.repo[b"HEAD"] = c1.id
  6230. self.repo.refs[b"refs/heads/main"] = c1.id
  6231. # Set branch.autoSetupMerge to always
  6232. config = self.repo.get_config()
  6233. config.set((b"branch",), b"autoSetupMerge", b"always")
  6234. config.write_to_path()
  6235. # Create branch from local branch - normally wouldn't set up tracking
  6236. porcelain.branch_create(self.repo, "feature", "main")
  6237. # With always, tracking should NOT be set up from local branches
  6238. # (Git only sets up tracking from remote-tracking branches even with always)
  6239. config = self.repo.get_config()
  6240. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"remote")
  6241. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"merge")
  6242. def test_auto_setup_merge_always_from_remote(self) -> None:
  6243. """Test branch.autoSetupMerge=always still sets up tracking from remote branches."""
  6244. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6245. self.repo[b"HEAD"] = c1.id
  6246. # Create a remote-tracking branch
  6247. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6248. # Set branch.autoSetupMerge to always
  6249. config = self.repo.get_config()
  6250. config.set((b"branch",), b"autoSetupMerge", b"always")
  6251. config.write_to_path()
  6252. # Create branch from remote-tracking branch
  6253. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6254. # Verify tracking was set up
  6255. config = self.repo.get_config()
  6256. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6257. self.assertEqual(
  6258. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6259. )
  6260. def test_auto_setup_merge_default(self) -> None:
  6261. """Test default behavior (no config) is same as true."""
  6262. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6263. self.repo[b"HEAD"] = c1.id
  6264. # Create a remote-tracking branch
  6265. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6266. # Don't set any config - should default to true
  6267. # Create branch from remote-tracking branch
  6268. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6269. # Verify tracking was set up
  6270. config = self.repo.get_config()
  6271. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6272. self.assertEqual(
  6273. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6274. )
  6275. class BranchDeleteTests(PorcelainTestCase):
  6276. def test_simple(self) -> None:
  6277. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6278. self.repo[b"HEAD"] = c1.id
  6279. porcelain.branch_create(self.repo, b"foo")
  6280. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  6281. porcelain.branch_delete(self.repo, b"foo")
  6282. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  6283. def test_simple_unicode(self) -> None:
  6284. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6285. self.repo[b"HEAD"] = c1.id
  6286. porcelain.branch_create(self.repo, "foo")
  6287. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  6288. porcelain.branch_delete(self.repo, "foo")
  6289. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  6290. class FetchTests(PorcelainTestCase):
  6291. def test_simple(self) -> None:
  6292. outstream = BytesIO()
  6293. errstream = BytesIO()
  6294. # create a file for initial commit
  6295. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6296. os.close(handle)
  6297. porcelain.add(repo=self.repo.path, paths=fullpath)
  6298. porcelain.commit(
  6299. repo=self.repo.path,
  6300. message=b"test",
  6301. author=b"test <email>",
  6302. committer=b"test <email>",
  6303. )
  6304. # Setup target repo
  6305. target_path = tempfile.mkdtemp()
  6306. self.addCleanup(shutil.rmtree, target_path)
  6307. target_repo = porcelain.clone(
  6308. self.repo.path, target=target_path, errstream=errstream
  6309. )
  6310. # create a second file to be pushed
  6311. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6312. os.close(handle)
  6313. porcelain.add(repo=self.repo.path, paths=fullpath)
  6314. porcelain.commit(
  6315. repo=self.repo.path,
  6316. message=b"test2",
  6317. author=b"test2 <email>",
  6318. committer=b"test2 <email>",
  6319. )
  6320. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  6321. target_repo.close()
  6322. # Fetch changes into the cloned repo
  6323. porcelain.fetch(target_path, "origin", outstream=outstream, errstream=errstream)
  6324. # Assert that fetch updated the local image of the remote
  6325. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  6326. # Check the target repo for pushed changes
  6327. with Repo(target_path) as r:
  6328. self.assertIn(self.repo[b"HEAD"].id, r)
  6329. def test_with_remote_name(self) -> None:
  6330. remote_name = "origin"
  6331. outstream = BytesIO()
  6332. errstream = BytesIO()
  6333. # create a file for initial commit
  6334. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6335. os.close(handle)
  6336. porcelain.add(repo=self.repo.path, paths=fullpath)
  6337. porcelain.commit(
  6338. repo=self.repo.path,
  6339. message=b"test",
  6340. author=b"test <email>",
  6341. committer=b"test <email>",
  6342. )
  6343. # Setup target repo
  6344. target_path = tempfile.mkdtemp()
  6345. self.addCleanup(shutil.rmtree, target_path)
  6346. target_repo = porcelain.clone(
  6347. self.repo.path, target=target_path, errstream=errstream
  6348. )
  6349. # Capture current refs
  6350. target_refs = target_repo.get_refs()
  6351. # create a second file to be pushed
  6352. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6353. os.close(handle)
  6354. porcelain.add(repo=self.repo.path, paths=fullpath)
  6355. porcelain.commit(
  6356. repo=self.repo.path,
  6357. message=b"test2",
  6358. author=b"test2 <email>",
  6359. committer=b"test2 <email>",
  6360. )
  6361. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  6362. target_config = target_repo.get_config()
  6363. target_config.set(
  6364. (b"remote", remote_name.encode()), b"url", self.repo.path.encode()
  6365. )
  6366. target_repo.close()
  6367. # Fetch changes into the cloned repo
  6368. porcelain.fetch(
  6369. target_path, remote_name, outstream=outstream, errstream=errstream
  6370. )
  6371. # Assert that fetch updated the local image of the remote
  6372. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  6373. # Check the target repo for pushed changes, as well as updates
  6374. # for the refs
  6375. with Repo(target_path) as r:
  6376. self.assertIn(self.repo[b"HEAD"].id, r)
  6377. self.assertNotEqual(self.repo.get_refs(), target_refs)
  6378. def assert_correct_remote_refs(
  6379. self, local_refs, remote_refs, remote_name=b"origin"
  6380. ) -> None:
  6381. """Assert that known remote refs corresponds to actual remote refs."""
  6382. local_ref_prefix = b"refs/heads"
  6383. remote_ref_prefix = b"refs/remotes/" + remote_name
  6384. locally_known_remote_refs = {
  6385. k[len(remote_ref_prefix) + 1 :]: v
  6386. for k, v in local_refs.items()
  6387. if k.startswith(remote_ref_prefix)
  6388. }
  6389. normalized_remote_refs = {
  6390. k[len(local_ref_prefix) + 1 :]: v
  6391. for k, v in remote_refs.items()
  6392. if k.startswith(local_ref_prefix)
  6393. }
  6394. if b"HEAD" in locally_known_remote_refs and b"HEAD" in remote_refs:
  6395. normalized_remote_refs[b"HEAD"] = remote_refs[b"HEAD"]
  6396. self.assertEqual(locally_known_remote_refs, normalized_remote_refs)
  6397. class RepackTests(PorcelainTestCase):
  6398. def test_empty(self) -> None:
  6399. porcelain.repack(self.repo)
  6400. def test_simple(self) -> None:
  6401. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6402. os.close(handle)
  6403. porcelain.add(repo=self.repo.path, paths=fullpath)
  6404. porcelain.repack(self.repo)
  6405. class LsTreeTests(PorcelainTestCase):
  6406. def test_empty(self) -> None:
  6407. porcelain.commit(
  6408. repo=self.repo.path,
  6409. message=b"test status",
  6410. author=b"author <email>",
  6411. committer=b"committer <email>",
  6412. )
  6413. f = StringIO()
  6414. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  6415. self.assertEqual(f.getvalue(), "")
  6416. def test_simple(self) -> None:
  6417. # Commit a dummy file then modify it
  6418. fullpath = os.path.join(self.repo.path, "foo")
  6419. with open(fullpath, "w") as f:
  6420. f.write("origstuff")
  6421. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6422. porcelain.commit(
  6423. repo=self.repo.path,
  6424. message=b"test status",
  6425. author=b"author <email>",
  6426. committer=b"committer <email>",
  6427. )
  6428. output = StringIO()
  6429. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  6430. self.assertEqual(
  6431. output.getvalue(),
  6432. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n",
  6433. )
  6434. def test_recursive(self) -> None:
  6435. # Create a directory then write a dummy file in it
  6436. dirpath = os.path.join(self.repo.path, "adir")
  6437. filepath = os.path.join(dirpath, "afile")
  6438. os.mkdir(dirpath)
  6439. with open(filepath, "w") as f:
  6440. f.write("origstuff")
  6441. porcelain.add(repo=self.repo.path, paths=[filepath])
  6442. porcelain.commit(
  6443. repo=self.repo.path,
  6444. message=b"test status",
  6445. author=b"author <email>",
  6446. committer=b"committer <email>",
  6447. )
  6448. output = StringIO()
  6449. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  6450. self.assertEqual(
  6451. output.getvalue(),
  6452. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n",
  6453. )
  6454. output2 = StringIO()
  6455. porcelain.ls_tree(self.repo, b"HEAD", outstream=output2, recursive=True)
  6456. self.assertEqual(
  6457. output2.getvalue(),
  6458. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n"
  6459. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir"
  6460. "/afile\n",
  6461. )
  6462. class LsRemoteTests(PorcelainTestCase):
  6463. def test_empty(self) -> None:
  6464. result = porcelain.ls_remote(self.repo.path)
  6465. self.assertEqual({}, result.refs)
  6466. self.assertEqual({}, result.symrefs)
  6467. def test_some(self) -> None:
  6468. cid = porcelain.commit(
  6469. repo=self.repo.path,
  6470. message=b"test status",
  6471. author=b"author <email>",
  6472. committer=b"committer <email>",
  6473. )
  6474. result = porcelain.ls_remote(self.repo.path)
  6475. self.assertEqual(
  6476. {b"refs/heads/master": cid, b"HEAD": cid},
  6477. result.refs,
  6478. )
  6479. # HEAD should be a symref to refs/heads/master
  6480. self.assertEqual({b"HEAD": b"refs/heads/master"}, result.symrefs)
  6481. class LsFilesTests(PorcelainTestCase):
  6482. def test_empty(self) -> None:
  6483. self.assertEqual([], list(porcelain.ls_files(self.repo)))
  6484. def test_simple(self) -> None:
  6485. # Commit a dummy file then modify it
  6486. fullpath = os.path.join(self.repo.path, "foo")
  6487. with open(fullpath, "w") as f:
  6488. f.write("origstuff")
  6489. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6490. self.assertEqual([b"foo"], list(porcelain.ls_files(self.repo)))
  6491. class RemoteAddTests(PorcelainTestCase):
  6492. def test_new(self) -> None:
  6493. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6494. c = self.repo.get_config()
  6495. self.assertEqual(
  6496. c.get((b"remote", b"jelmer"), b"url"),
  6497. b"git://jelmer.uk/code/dulwich",
  6498. )
  6499. def test_exists(self) -> None:
  6500. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6501. self.assertRaises(
  6502. porcelain.RemoteExists,
  6503. porcelain.remote_add,
  6504. self.repo,
  6505. "jelmer",
  6506. "git://jelmer.uk/code/dulwich",
  6507. )
  6508. class RemoteRemoveTests(PorcelainTestCase):
  6509. def test_remove(self) -> None:
  6510. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6511. c = self.repo.get_config()
  6512. self.assertEqual(
  6513. c.get((b"remote", b"jelmer"), b"url"),
  6514. b"git://jelmer.uk/code/dulwich",
  6515. )
  6516. porcelain.remote_remove(self.repo, "jelmer")
  6517. self.assertRaises(KeyError, porcelain.remote_remove, self.repo, "jelmer")
  6518. c = self.repo.get_config()
  6519. self.assertRaises(KeyError, c.get, (b"remote", b"jelmer"), b"url")
  6520. class CheckIgnoreTests(PorcelainTestCase):
  6521. def test_check_ignored(self) -> None:
  6522. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6523. f.write("foo")
  6524. foo_path = os.path.join(self.repo.path, "foo")
  6525. with open(foo_path, "w") as f:
  6526. f.write("BAR")
  6527. bar_path = os.path.join(self.repo.path, "bar")
  6528. with open(bar_path, "w") as f:
  6529. f.write("BAR")
  6530. self.assertEqual(["foo"], list(porcelain.check_ignore(self.repo, [foo_path])))
  6531. self.assertEqual([], list(porcelain.check_ignore(self.repo, [bar_path])))
  6532. def test_check_added_abs(self) -> None:
  6533. path = os.path.join(self.repo.path, "foo")
  6534. with open(path, "w") as f:
  6535. f.write("BAR")
  6536. self.repo.get_worktree().stage(["foo"])
  6537. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6538. f.write("foo\n")
  6539. self.assertEqual([], list(porcelain.check_ignore(self.repo, [path])))
  6540. self.assertEqual(
  6541. ["foo"],
  6542. list(porcelain.check_ignore(self.repo, [path], no_index=True)),
  6543. )
  6544. def test_check_added_rel(self) -> None:
  6545. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  6546. f.write("BAR")
  6547. self.repo.get_worktree().stage(["foo"])
  6548. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6549. f.write("foo\n")
  6550. cwd = os.getcwd()
  6551. self.addCleanup(os.chdir, cwd)
  6552. os.mkdir(os.path.join(self.repo.path, "bar"))
  6553. os.chdir(os.path.join(self.repo.path, "bar"))
  6554. self.assertEqual(list(porcelain.check_ignore(self.repo, ["../foo"])), [])
  6555. self.assertEqual(
  6556. ["../foo"],
  6557. list(porcelain.check_ignore(self.repo, ["../foo"], no_index=True)),
  6558. )
  6559. class UpdateHeadTests(PorcelainTestCase):
  6560. def test_set_to_branch(self) -> None:
  6561. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6562. self.repo.refs[b"refs/heads/blah"] = c1.id
  6563. porcelain.update_head(self.repo, "blah")
  6564. self.assertEqual(c1.id, self.repo.head())
  6565. self.assertEqual(b"ref: refs/heads/blah", self.repo.refs.read_ref(b"HEAD"))
  6566. def test_set_to_branch_detached(self) -> None:
  6567. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6568. self.repo.refs[b"refs/heads/blah"] = c1.id
  6569. porcelain.update_head(self.repo, "blah", detached=True)
  6570. self.assertEqual(c1.id, self.repo.head())
  6571. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  6572. def test_set_to_commit_detached(self) -> None:
  6573. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6574. self.repo.refs[b"refs/heads/blah"] = c1.id
  6575. porcelain.update_head(self.repo, c1.id, detached=True)
  6576. self.assertEqual(c1.id, self.repo.head())
  6577. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  6578. def test_set_new_branch(self) -> None:
  6579. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6580. self.repo.refs[b"refs/heads/blah"] = c1.id
  6581. porcelain.update_head(self.repo, "blah", new_branch="bar")
  6582. self.assertEqual(c1.id, self.repo.head())
  6583. self.assertEqual(b"ref: refs/heads/bar", self.repo.refs.read_ref(b"HEAD"))
  6584. class MailmapTests(PorcelainTestCase):
  6585. def test_no_mailmap(self) -> None:
  6586. self.assertEqual(
  6587. b"Jelmer Vernooij <jelmer@samba.org>",
  6588. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  6589. )
  6590. def test_mailmap_lookup(self) -> None:
  6591. with open(os.path.join(self.repo.path, ".mailmap"), "wb") as f:
  6592. f.write(
  6593. b"""\
  6594. Jelmer Vernooij <jelmer@debian.org>
  6595. """
  6596. )
  6597. self.assertEqual(
  6598. b"Jelmer Vernooij <jelmer@debian.org>",
  6599. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  6600. )
  6601. class FsckTests(PorcelainTestCase):
  6602. def test_none(self) -> None:
  6603. self.assertEqual([], list(porcelain.fsck(self.repo)))
  6604. def test_git_dir(self) -> None:
  6605. obj = Tree()
  6606. a = Blob()
  6607. a.data = b"foo"
  6608. obj.add(b".git", 0o100644, a.id)
  6609. self.repo.object_store.add_objects([(a, None), (obj, None)])
  6610. self.assertEqual(
  6611. [(obj.id, "invalid name .git")],
  6612. [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)],
  6613. )
  6614. class DescribeTests(PorcelainTestCase):
  6615. def test_no_commits(self) -> None:
  6616. self.assertRaises(KeyError, porcelain.describe, self.repo.path)
  6617. def test_single_commit(self) -> None:
  6618. fullpath = os.path.join(self.repo.path, "foo")
  6619. with open(fullpath, "w") as f:
  6620. f.write("BAR")
  6621. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6622. sha = porcelain.commit(
  6623. self.repo.path,
  6624. message=b"Some message",
  6625. author=b"Joe <joe@example.com>",
  6626. committer=b"Bob <bob@example.com>",
  6627. )
  6628. self.assertEqual(
  6629. "g{}".format(sha[:7].decode("ascii")),
  6630. porcelain.describe(self.repo.path),
  6631. )
  6632. def test_tag(self) -> None:
  6633. fullpath = os.path.join(self.repo.path, "foo")
  6634. with open(fullpath, "w") as f:
  6635. f.write("BAR")
  6636. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6637. porcelain.commit(
  6638. self.repo.path,
  6639. message=b"Some message",
  6640. author=b"Joe <joe@example.com>",
  6641. committer=b"Bob <bob@example.com>",
  6642. )
  6643. porcelain.tag_create(
  6644. self.repo.path,
  6645. b"tryme",
  6646. b"foo <foo@bar.com>",
  6647. b"bar",
  6648. annotated=True,
  6649. )
  6650. self.assertEqual("tryme", porcelain.describe(self.repo.path))
  6651. def test_tag_and_commit(self) -> None:
  6652. fullpath = os.path.join(self.repo.path, "foo")
  6653. with open(fullpath, "w") as f:
  6654. f.write("BAR")
  6655. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6656. porcelain.commit(
  6657. self.repo.path,
  6658. message=b"Some message",
  6659. author=b"Joe <joe@example.com>",
  6660. committer=b"Bob <bob@example.com>",
  6661. )
  6662. porcelain.tag_create(
  6663. self.repo.path,
  6664. b"tryme",
  6665. b"foo <foo@bar.com>",
  6666. b"bar",
  6667. annotated=True,
  6668. )
  6669. with open(fullpath, "w") as f:
  6670. f.write("BAR2")
  6671. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6672. sha = porcelain.commit(
  6673. self.repo.path,
  6674. message=b"Some message",
  6675. author=b"Joe <joe@example.com>",
  6676. committer=b"Bob <bob@example.com>",
  6677. )
  6678. self.assertEqual(
  6679. "tryme-1-g{}".format(sha[:7].decode("ascii")),
  6680. porcelain.describe(self.repo.path),
  6681. )
  6682. def test_tag_and_commit_full(self) -> None:
  6683. fullpath = os.path.join(self.repo.path, "foo")
  6684. with open(fullpath, "w") as f:
  6685. f.write("BAR")
  6686. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6687. porcelain.commit(
  6688. self.repo.path,
  6689. message=b"Some message",
  6690. author=b"Joe <joe@example.com>",
  6691. committer=b"Bob <bob@example.com>",
  6692. )
  6693. porcelain.tag_create(
  6694. self.repo.path,
  6695. b"tryme",
  6696. b"foo <foo@bar.com>",
  6697. b"bar",
  6698. annotated=True,
  6699. )
  6700. with open(fullpath, "w") as f:
  6701. f.write("BAR2")
  6702. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6703. sha = porcelain.commit(
  6704. self.repo.path,
  6705. message=b"Some message",
  6706. author=b"Joe <joe@example.com>",
  6707. committer=b"Bob <bob@example.com>",
  6708. )
  6709. self.assertEqual(
  6710. "tryme-1-g{}".format(sha.decode("ascii")),
  6711. porcelain.describe(self.repo.path, abbrev=40),
  6712. )
  6713. def test_untagged_commit_abbreviation(self) -> None:
  6714. _, _, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]])
  6715. self.repo.refs[b"HEAD"] = c3.id
  6716. brief_description, complete_description = (
  6717. porcelain.describe(self.repo),
  6718. porcelain.describe(self.repo, abbrev=40),
  6719. )
  6720. self.assertTrue(complete_description.startswith(brief_description))
  6721. self.assertEqual(
  6722. "g{}".format(c3.id.decode("ascii")),
  6723. complete_description,
  6724. )
  6725. def test_hash_length_dynamic(self) -> None:
  6726. """Test that hash length adjusts based on uniqueness."""
  6727. fullpath = os.path.join(self.repo.path, "foo")
  6728. with open(fullpath, "w") as f:
  6729. f.write("content")
  6730. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6731. sha = porcelain.commit(
  6732. self.repo.path,
  6733. message=b"commit",
  6734. author=b"Joe <joe@example.com>",
  6735. committer=b"Bob <bob@example.com>",
  6736. )
  6737. # When abbrev is None, it should use find_unique_abbrev
  6738. result = porcelain.describe(self.repo.path)
  6739. # Should start with 'g' and have at least 7 characters
  6740. self.assertTrue(result.startswith("g"))
  6741. self.assertGreaterEqual(len(result[1:]), 7)
  6742. # Should be a prefix of the full SHA
  6743. self.assertTrue(sha.decode("ascii").startswith(result[1:]))
  6744. class PathToTreeTests(PorcelainTestCase):
  6745. def setUp(self) -> None:
  6746. super().setUp()
  6747. self.fp = os.path.join(self.test_dir, "bar")
  6748. with open(self.fp, "w") as f:
  6749. f.write("something")
  6750. oldcwd = os.getcwd()
  6751. self.addCleanup(os.chdir, oldcwd)
  6752. os.chdir(self.test_dir)
  6753. def test_path_to_tree_path_base(self) -> None:
  6754. self.assertEqual(b"bar", porcelain.path_to_tree_path(self.test_dir, self.fp))
  6755. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  6756. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "bar"))
  6757. cwd = os.getcwd()
  6758. self.assertEqual(
  6759. b"bar", porcelain.path_to_tree_path(".", os.path.join(cwd, "bar"))
  6760. )
  6761. self.assertEqual(b"bar", porcelain.path_to_tree_path(cwd, "bar"))
  6762. def test_path_to_tree_path_syntax(self) -> None:
  6763. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  6764. def test_path_to_tree_path_error(self) -> None:
  6765. with self.assertRaises(ValueError):
  6766. with tempfile.TemporaryDirectory() as od:
  6767. porcelain.path_to_tree_path(od, self.fp)
  6768. def test_path_to_tree_path_rel(self) -> None:
  6769. cwd = os.getcwd()
  6770. self.addCleanup(os.chdir, cwd)
  6771. os.mkdir(os.path.join(self.repo.path, "foo"))
  6772. os.mkdir(os.path.join(self.repo.path, "foo/bar"))
  6773. os.chdir(os.path.join(self.repo.path, "foo/bar"))
  6774. with open("baz", "w") as f:
  6775. f.write("contents")
  6776. self.assertEqual(b"bar/baz", porcelain.path_to_tree_path("..", "baz"))
  6777. self.assertEqual(
  6778. b"bar/baz",
  6779. porcelain.path_to_tree_path(
  6780. os.path.join(os.getcwd(), ".."),
  6781. os.path.join(os.getcwd(), "baz"),
  6782. ),
  6783. )
  6784. self.assertEqual(
  6785. b"bar/baz",
  6786. porcelain.path_to_tree_path("..", os.path.join(os.getcwd(), "baz")),
  6787. )
  6788. self.assertEqual(
  6789. b"bar/baz",
  6790. porcelain.path_to_tree_path(os.path.join(os.getcwd(), ".."), "baz"),
  6791. )
  6792. class GetObjectByPathTests(PorcelainTestCase):
  6793. def test_simple(self) -> None:
  6794. fullpath = os.path.join(self.repo.path, "foo")
  6795. with open(fullpath, "w") as f:
  6796. f.write("BAR")
  6797. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6798. porcelain.commit(
  6799. self.repo.path,
  6800. message=b"Some message",
  6801. author=b"Joe <joe@example.com>",
  6802. committer=b"Bob <bob@example.com>",
  6803. )
  6804. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  6805. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  6806. def test_encoding(self) -> None:
  6807. fullpath = os.path.join(self.repo.path, "foo")
  6808. with open(fullpath, "w") as f:
  6809. f.write("BAR")
  6810. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6811. porcelain.commit(
  6812. self.repo.path,
  6813. message=b"Some message",
  6814. author=b"Joe <joe@example.com>",
  6815. committer=b"Bob <bob@example.com>",
  6816. encoding=b"utf-8",
  6817. )
  6818. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  6819. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  6820. def test_missing(self) -> None:
  6821. self.assertRaises(KeyError, porcelain.get_object_by_path, self.repo, "foo")
  6822. class WriteTreeTests(PorcelainTestCase):
  6823. def test_simple(self) -> None:
  6824. fullpath = os.path.join(self.repo.path, "foo")
  6825. with open(fullpath, "w") as f:
  6826. f.write("BAR")
  6827. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6828. self.assertEqual(
  6829. b"d2092c8a9f311f0311083bf8d177f2ca0ab5b241",
  6830. porcelain.write_tree(self.repo),
  6831. )
  6832. class ActiveBranchTests(PorcelainTestCase):
  6833. def test_simple(self) -> None:
  6834. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  6835. class BranchTrackingTests(PorcelainTestCase):
  6836. def test_get_branch_merge(self) -> None:
  6837. # Set up branch tracking configuration
  6838. config = self.repo.get_config()
  6839. config.set((b"branch", b"master"), b"remote", b"origin")
  6840. config.set((b"branch", b"master"), b"merge", b"refs/heads/main")
  6841. config.write_to_path()
  6842. # Test getting merge ref for current branch
  6843. merge_ref = porcelain.get_branch_merge(self.repo)
  6844. self.assertEqual(b"refs/heads/main", merge_ref)
  6845. # Test getting merge ref for specific branch
  6846. merge_ref = porcelain.get_branch_merge(self.repo, b"master")
  6847. self.assertEqual(b"refs/heads/main", merge_ref)
  6848. # Test branch without merge config
  6849. with self.assertRaises(KeyError):
  6850. porcelain.get_branch_merge(self.repo, b"nonexistent")
  6851. def test_set_branch_tracking(self) -> None:
  6852. # Create a new branch
  6853. _sha, _ = _commit_file_with_content(self.repo, "foo", "content\n")
  6854. porcelain.branch_create(self.repo, "feature")
  6855. # Set up tracking
  6856. porcelain.set_branch_tracking(
  6857. self.repo, b"feature", b"upstream", b"refs/heads/main"
  6858. )
  6859. # Verify configuration was written
  6860. config = self.repo.get_config()
  6861. self.assertEqual(b"upstream", config.get((b"branch", b"feature"), b"remote"))
  6862. self.assertEqual(
  6863. b"refs/heads/main", config.get((b"branch", b"feature"), b"merge")
  6864. )
  6865. class FindUniqueAbbrevTests(PorcelainTestCase):
  6866. def test_simple(self) -> None:
  6867. c1, _c2, c3 = build_commit_graph(
  6868. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  6869. )
  6870. self.repo.refs[b"HEAD"] = c3.id
  6871. self.assertEqual(
  6872. c1.id.decode("ascii")[:7],
  6873. porcelain.find_unique_abbrev(self.repo.object_store, c1.id),
  6874. )
  6875. class PackRefsTests(PorcelainTestCase):
  6876. def test_all(self) -> None:
  6877. c1, c2, c3 = build_commit_graph(
  6878. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  6879. )
  6880. self.repo.refs[b"HEAD"] = c3.id
  6881. self.repo.refs[b"refs/heads/master"] = c2.id
  6882. self.repo.refs[b"refs/tags/foo"] = c1.id
  6883. porcelain.pack_refs(self.repo, all=True)
  6884. self.assertEqual(
  6885. self.repo.refs.get_packed_refs(),
  6886. {
  6887. b"refs/heads/master": c2.id,
  6888. b"refs/tags/foo": c1.id,
  6889. },
  6890. )
  6891. def test_not_all(self) -> None:
  6892. c1, c2, c3 = build_commit_graph(
  6893. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  6894. )
  6895. self.repo.refs[b"HEAD"] = c3.id
  6896. self.repo.refs[b"refs/heads/master"] = c2.id
  6897. self.repo.refs[b"refs/tags/foo"] = c1.id
  6898. porcelain.pack_refs(self.repo)
  6899. self.assertEqual(
  6900. self.repo.refs.get_packed_refs(),
  6901. {
  6902. b"refs/tags/foo": c1.id,
  6903. },
  6904. )
  6905. class ServerTests(PorcelainTestCase):
  6906. @contextlib.contextmanager
  6907. def _serving(self):
  6908. with make_server("localhost", 0, self.app) as server:
  6909. thread = threading.Thread(target=server.serve_forever, daemon=True)
  6910. thread.start()
  6911. try:
  6912. yield f"http://localhost:{server.server_port}"
  6913. finally:
  6914. server.shutdown()
  6915. thread.join(10)
  6916. def setUp(self) -> None:
  6917. super().setUp()
  6918. self.served_repo_path = os.path.join(self.test_dir, "served_repo.git")
  6919. self.served_repo = Repo.init_bare(self.served_repo_path, mkdir=True)
  6920. self.addCleanup(self.served_repo.close)
  6921. backend = DictBackend({"/": self.served_repo})
  6922. self.app = make_wsgi_chain(backend)
  6923. def test_pull(self) -> None:
  6924. (c1,) = build_commit_graph(self.served_repo.object_store, [[1]])
  6925. self.served_repo.refs[b"refs/heads/master"] = c1.id
  6926. with self._serving() as url:
  6927. porcelain.pull(self.repo, url, "master")
  6928. def test_push(self) -> None:
  6929. (c1,) = build_commit_graph(self.repo.object_store, [[1]])
  6930. self.repo.refs[b"refs/heads/master"] = c1.id
  6931. with self._serving() as url:
  6932. porcelain.push(self.repo, url, "master")
  6933. class ForEachTests(PorcelainTestCase):
  6934. def setUp(self) -> None:
  6935. super().setUp()
  6936. c1, c2, c3, c4 = build_commit_graph(
  6937. self.repo.object_store, [[1], [2, 1], [3, 1, 2], [4]]
  6938. )
  6939. porcelain.tag_create(
  6940. self.repo.path,
  6941. b"v0.1",
  6942. objectish=c1.id,
  6943. annotated=True,
  6944. message=b"0.1",
  6945. )
  6946. porcelain.tag_create(
  6947. self.repo.path,
  6948. b"v1.0",
  6949. objectish=c2.id,
  6950. annotated=True,
  6951. message=b"1.0",
  6952. )
  6953. porcelain.tag_create(self.repo.path, b"simple-tag", objectish=c3.id)
  6954. porcelain.tag_create(
  6955. self.repo.path,
  6956. b"v1.1",
  6957. objectish=c4.id,
  6958. annotated=True,
  6959. message=b"1.1",
  6960. )
  6961. porcelain.branch_create(
  6962. self.repo.path, b"feat", objectish=c2.id.decode("ascii")
  6963. )
  6964. self.repo.refs[b"HEAD"] = c4.id
  6965. def test_for_each_ref(self) -> None:
  6966. refs = porcelain.for_each_ref(self.repo)
  6967. self.assertEqual(
  6968. [(object_type, tag) for _, object_type, tag in refs],
  6969. [
  6970. (b"commit", b"refs/heads/feat"),
  6971. (b"commit", b"refs/heads/master"),
  6972. (b"commit", b"refs/tags/simple-tag"),
  6973. (b"tag", b"refs/tags/v0.1"),
  6974. (b"tag", b"refs/tags/v1.0"),
  6975. (b"tag", b"refs/tags/v1.1"),
  6976. ],
  6977. )
  6978. def test_for_each_ref_pattern(self) -> None:
  6979. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v*")
  6980. self.assertEqual(
  6981. [(object_type, tag) for _, object_type, tag in versions],
  6982. [
  6983. (b"tag", b"refs/tags/v0.1"),
  6984. (b"tag", b"refs/tags/v1.0"),
  6985. (b"tag", b"refs/tags/v1.1"),
  6986. ],
  6987. )
  6988. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v1.?")
  6989. self.assertEqual(
  6990. [(object_type, tag) for _, object_type, tag in versions],
  6991. [
  6992. (b"tag", b"refs/tags/v1.0"),
  6993. (b"tag", b"refs/tags/v1.1"),
  6994. ],
  6995. )
  6996. class SparseCheckoutTests(PorcelainTestCase):
  6997. """Integration tests for Dulwich's sparse checkout feature."""
  6998. # NOTE: We do NOT override `setUp()` here because the parent class
  6999. # (PorcelainTestCase) already:
  7000. # 1) Creates self.test_dir = a unique temp dir
  7001. # 2) Creates a subdir named "repo"
  7002. # 3) Calls Repo.init() on that path
  7003. # Re-initializing again caused FileExistsError.
  7004. #
  7005. # Utility/Placeholder
  7006. #
  7007. def sparse_checkout(self, repo, patterns, force=False):
  7008. """Wrapper around the actual porcelain.sparse_checkout function
  7009. to handle any test-specific setup or logging.
  7010. """
  7011. return porcelain.sparse_checkout(repo, patterns, force=force)
  7012. def _write_file(self, rel_path, content):
  7013. """Helper to write a file in the repository working tree."""
  7014. abs_path = os.path.join(self.repo_path, rel_path)
  7015. os.makedirs(os.path.dirname(abs_path), exist_ok=True)
  7016. with open(abs_path, "w") as f:
  7017. f.write(content)
  7018. return abs_path
  7019. def _commit_file(self, rel_path, content):
  7020. """Helper to write, add, and commit a file."""
  7021. abs_path = self._write_file(rel_path, content)
  7022. add(self.repo_path, paths=[abs_path])
  7023. commit(self.repo_path, message=b"Added " + rel_path.encode("utf-8"))
  7024. def _list_wtree_files(self):
  7025. """Return a set of all files (not dirs) present
  7026. in the working tree, ignoring .git/.
  7027. """
  7028. found_files = set()
  7029. for root, dirs, files in os.walk(self.repo_path):
  7030. # Skip .git in the walk
  7031. if ".git" in dirs:
  7032. dirs.remove(".git")
  7033. for filename in files:
  7034. file_rel = os.path.relpath(os.path.join(root, filename), self.repo_path)
  7035. found_files.add(file_rel)
  7036. return found_files
  7037. def test_only_included_paths_appear_in_wtree(self):
  7038. """Only included paths remain in the working tree, excluded paths are removed.
  7039. Commits two files, "keep_me.txt" and "exclude_me.txt". Then applies a
  7040. sparse-checkout pattern containing only "keep_me.txt". Ensures that
  7041. the latter remains in the working tree, while "exclude_me.txt" is
  7042. removed. This verifies correct application of sparse-checkout patterns
  7043. to remove files not listed.
  7044. """
  7045. self._commit_file("keep_me.txt", "I'll stay\n")
  7046. self._commit_file("exclude_me.txt", "I'll be excluded\n")
  7047. patterns = ["keep_me.txt"]
  7048. self.sparse_checkout(self.repo, patterns)
  7049. actual_files = self._list_wtree_files()
  7050. expected_files = {"keep_me.txt"}
  7051. self.assertEqual(
  7052. expected_files,
  7053. actual_files,
  7054. f"Expected only {expected_files}, but found {actual_files}",
  7055. )
  7056. def test_previously_included_paths_become_excluded(self):
  7057. """Previously included files become excluded after pattern changes.
  7058. Verifies that files initially brought into the working tree (e.g.,
  7059. by including `data/`) can later be excluded by narrowing the
  7060. sparse-checkout pattern to just `data/included_1.txt`. Confirms that
  7061. the file `data/included_2.txt` remains in the index with
  7062. skip-worktree set (rather than being removed entirely), ensuring
  7063. data is not lost and Dulwich correctly updates the index flags.
  7064. """
  7065. self._commit_file("data/included_1.txt", "some content\n")
  7066. self._commit_file("data/included_2.txt", "other content\n")
  7067. initial_patterns = ["data/"]
  7068. self.sparse_checkout(self.repo, initial_patterns)
  7069. updated_patterns = ["data/included_1.txt"]
  7070. self.sparse_checkout(self.repo, updated_patterns)
  7071. actual_files = self._list_wtree_files()
  7072. expected_files = {os.path.join("data", "included_1.txt")}
  7073. self.assertEqual(expected_files, actual_files)
  7074. idx = self.repo.open_index()
  7075. self.assertIn(b"data/included_2.txt", idx)
  7076. entry = idx[b"data/included_2.txt"]
  7077. self.assertTrue(entry.skip_worktree)
  7078. def test_force_removes_local_changes_for_excluded_paths(self):
  7079. """Forced sparse checkout removes local modifications for newly excluded paths.
  7080. Verifies that specifying force=True allows destructive operations
  7081. which discard uncommitted changes. First, we commit "file1.txt" and
  7082. then modify it. Next, we apply a pattern that excludes the file,
  7083. using force=True. The local modifications (and the file) should
  7084. be removed, leaving the working tree empty.
  7085. """
  7086. self._commit_file("file1.txt", "original content\n")
  7087. file1_path = os.path.join(self.repo_path, "file1.txt")
  7088. with open(file1_path, "a") as f:
  7089. f.write("local changes!\n")
  7090. new_patterns = ["some_other_file.txt"]
  7091. self.sparse_checkout(self.repo, new_patterns, force=True)
  7092. actual_files = self._list_wtree_files()
  7093. self.assertEqual(
  7094. set(),
  7095. actual_files,
  7096. "Force-sparse-checkout did not remove file with local changes.",
  7097. )
  7098. def test_destructive_refuse_uncommitted_changes_without_force(self):
  7099. """Fail on uncommitted changes for newly excluded paths without force.
  7100. Ensures that a sparse checkout is blocked if it would remove local
  7101. modifications from the working tree. We commit 'config.yaml', then
  7102. modify it, and finally attempt to exclude it via new patterns without
  7103. using force=True. This should raise a CheckoutError rather than
  7104. discarding the local changes.
  7105. """
  7106. self._commit_file("config.yaml", "initial\n")
  7107. cfg_path = os.path.join(self.repo_path, "config.yaml")
  7108. with open(cfg_path, "a") as f:
  7109. f.write("local modifications\n")
  7110. exclude_patterns = ["docs/"]
  7111. with self.assertRaises(CheckoutError):
  7112. self.sparse_checkout(self.repo, exclude_patterns, force=False)
  7113. def test_fnmatch_gitignore_pattern_expansion(self):
  7114. """Reading/writing patterns align with gitignore/fnmatch expansions.
  7115. Ensures that `sparse_checkout` interprets wildcard patterns (like `*.py`)
  7116. in the same way Git's sparse-checkout would. Multiple files are committed
  7117. to `src/` (e.g. `foo.py`, `foo_test.py`, `foo_helper.py`) and to `docs/`.
  7118. Then the pattern `src/foo*.py` is applied, confirming that only the
  7119. matching Python files remain in the working tree while the Markdown file
  7120. under `docs/` is excluded.
  7121. Finally, verifies that the `.git/info/sparse-checkout` file contains the
  7122. specified wildcard pattern (`src/foo*.py`), ensuring correct round-trip
  7123. of user-supplied patterns.
  7124. """
  7125. self._commit_file("src/foo.py", "print('hello')\n")
  7126. self._commit_file("src/foo_test.py", "print('test')\n")
  7127. self._commit_file("docs/readme.md", "# docs\n")
  7128. self._commit_file("src/foo_helper.py", "print('helper')\n")
  7129. patterns = ["src/foo*.py"]
  7130. self.sparse_checkout(self.repo, patterns)
  7131. actual_files = self._list_wtree_files()
  7132. expected_files = {
  7133. os.path.join("src", "foo.py"),
  7134. os.path.join("src", "foo_test.py"),
  7135. os.path.join("src", "foo_helper.py"),
  7136. }
  7137. self.assertEqual(
  7138. expected_files,
  7139. actual_files,
  7140. "Wildcard pattern not matched as expected. Either too strict or too broad.",
  7141. )
  7142. sc_file = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7143. self.assertTrue(os.path.isfile(sc_file))
  7144. with open(sc_file) as f:
  7145. lines = f.read().strip().split()
  7146. self.assertIn("src/foo*.py", lines)
  7147. class ConeModeTests(PorcelainTestCase):
  7148. """Provide integration tests for Dulwich's cone mode sparse checkout.
  7149. This test suite verifies the expected behavior for:
  7150. * cone_mode_init
  7151. * cone_mode_set
  7152. * cone_mode_add
  7153. Although Dulwich does not yet implement cone mode, these tests are
  7154. prepared in advance to guide future development.
  7155. """
  7156. def setUp(self):
  7157. """Set up a fresh repository for each test.
  7158. This method creates a new empty repo_path and Repo object
  7159. as provided by the PorcelainTestCase base class.
  7160. """
  7161. super().setUp()
  7162. def _commit_file(self, rel_path, content=b"contents"):
  7163. """Add a file at the given relative path and commit it.
  7164. Creates necessary directories, writes the file content,
  7165. stages, and commits. The commit message and author/committer
  7166. are also provided.
  7167. """
  7168. full_path = os.path.join(self.repo_path, rel_path)
  7169. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  7170. with open(full_path, "wb") as f:
  7171. f.write(content)
  7172. porcelain.add(self.repo_path, paths=[full_path])
  7173. porcelain.commit(
  7174. self.repo_path,
  7175. message=b"Adding " + rel_path.encode("utf-8"),
  7176. author=b"Test Author <author@example.com>",
  7177. committer=b"Test Committer <committer@example.com>",
  7178. )
  7179. def _list_wtree_files(self):
  7180. """Return a set of all file paths relative to the repository root.
  7181. Walks the working tree, skipping the .git directory.
  7182. """
  7183. found_files = set()
  7184. for root, dirs, files in os.walk(self.repo_path):
  7185. if ".git" in dirs:
  7186. dirs.remove(".git")
  7187. for fn in files:
  7188. relp = os.path.relpath(os.path.join(root, fn), self.repo_path)
  7189. found_files.add(relp)
  7190. return found_files
  7191. def test_init_excludes_everything(self):
  7192. """Verify that cone_mode_init writes minimal patterns and empties the working tree.
  7193. Make some dummy files, commit them, then call cone_mode_init. Confirm
  7194. that the working tree is empty, the sparse-checkout file has the
  7195. minimal patterns (/*, !/*/), and the relevant config values are set.
  7196. """
  7197. self._commit_file("docs/readme.md", b"# doc\n")
  7198. self._commit_file("src/main.py", b"print('hello')\n")
  7199. porcelain.cone_mode_init(self.repo)
  7200. actual_files = self._list_wtree_files()
  7201. self.assertEqual(
  7202. set(),
  7203. actual_files,
  7204. "cone_mode_init did not exclude all files from the working tree.",
  7205. )
  7206. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7207. with open(sp_path) as f:
  7208. lines = [ln.strip() for ln in f if ln.strip()]
  7209. self.assertIn("/*", lines)
  7210. self.assertIn("!/*/", lines)
  7211. config = self.repo.get_config()
  7212. self.assertEqual(config.get((b"core",), b"sparseCheckout"), b"true")
  7213. self.assertEqual(config.get((b"core",), b"sparseCheckoutCone"), b"true")
  7214. def test_set_specific_dirs(self):
  7215. """Verify that cone_mode_set overwrites the included directories to only the specified ones.
  7216. Initializes cone mode, commits some files, then calls cone_mode_set with
  7217. a list of directories. Expects that only those directories remain in the
  7218. working tree.
  7219. """
  7220. porcelain.cone_mode_init(self.repo)
  7221. self._commit_file("docs/readme.md", b"# doc\n")
  7222. self._commit_file("src/main.py", b"print('hello')\n")
  7223. self._commit_file("tests/test_foo.py", b"# tests\n")
  7224. # Everything is still excluded initially by init.
  7225. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  7226. actual_files = self._list_wtree_files()
  7227. expected_files = {
  7228. os.path.join("docs", "readme.md"),
  7229. os.path.join("src", "main.py"),
  7230. }
  7231. self.assertEqual(
  7232. expected_files,
  7233. actual_files,
  7234. "Did not see only the 'docs/' and 'src/' dirs in the working tree.",
  7235. )
  7236. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7237. with open(sp_path) as f:
  7238. lines = [ln.strip() for ln in f if ln.strip()]
  7239. # For standard cone mode, we'd expect lines like:
  7240. # /* (include top-level files)
  7241. # !/*/ (exclude subdirectories)
  7242. # !/docs/ (re-include docs)
  7243. # !/src/ (re-include src)
  7244. # Instead of the wildcard-based lines the old test used.
  7245. self.assertIn("/*", lines)
  7246. self.assertIn("!/*/", lines)
  7247. self.assertIn("/docs/", lines)
  7248. self.assertIn("/src/", lines)
  7249. self.assertNotIn("/tests/", lines)
  7250. def test_set_overwrites_old_dirs(self):
  7251. """Ensure that calling cone_mode_set again overwrites old includes.
  7252. Initializes cone mode, includes two directories, then calls
  7253. cone_mode_set again with a different directory to confirm the
  7254. new set of includes replaces the old.
  7255. """
  7256. porcelain.cone_mode_init(self.repo)
  7257. self._commit_file("docs/readme.md")
  7258. self._commit_file("src/main.py")
  7259. self._commit_file("tests/test_bar.py")
  7260. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  7261. self.assertEqual(
  7262. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  7263. self._list_wtree_files(),
  7264. )
  7265. # Overwrite includes, now only 'tests'
  7266. porcelain.cone_mode_set(self.repo, dirs=["tests"], force=True)
  7267. actual_files = self._list_wtree_files()
  7268. expected_files = {os.path.join("tests", "test_bar.py")}
  7269. self.assertEqual(expected_files, actual_files)
  7270. def test_force_removal_of_local_mods(self):
  7271. """Confirm that force=True removes local changes in excluded paths.
  7272. cone_mode_init and cone_mode_set are called, a file is locally modified,
  7273. and then cone_mode_set is called again with force=True to exclude that path.
  7274. The excluded file should be removed with no CheckoutError.
  7275. """
  7276. porcelain.cone_mode_init(self.repo)
  7277. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  7278. self._commit_file("docs/readme.md", b"Docs stuff\n")
  7279. self._commit_file("src/main.py", b"print('hello')\n")
  7280. # Modify src/main.py
  7281. with open(os.path.join(self.repo_path, "src/main.py"), "ab") as f:
  7282. f.write(b"extra line\n")
  7283. # Exclude src/ with force=True
  7284. porcelain.cone_mode_set(self.repo, dirs=["docs"], force=True)
  7285. actual_files = self._list_wtree_files()
  7286. expected_files = {os.path.join("docs", "readme.md")}
  7287. self.assertEqual(expected_files, actual_files)
  7288. def test_add_and_merge_dirs(self):
  7289. """Verify that cone_mode_add merges new directories instead of overwriting them.
  7290. After initializing cone mode and including a single directory, call
  7291. cone_mode_add with a new directory. Confirm that both directories
  7292. remain included. Repeat for an additional directory to ensure it
  7293. is merged, not overwritten.
  7294. """
  7295. porcelain.cone_mode_init(self.repo)
  7296. self._commit_file("docs/readme.md", b"# doc\n")
  7297. self._commit_file("src/main.py", b"print('hello')\n")
  7298. self._commit_file("tests/test_bar.py", b"# tests\n")
  7299. # Include "docs" only
  7300. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  7301. self.assertEqual({os.path.join("docs", "readme.md")}, self._list_wtree_files())
  7302. # Add "src"
  7303. porcelain.cone_mode_add(self.repo, dirs=["src"])
  7304. actual_files = self._list_wtree_files()
  7305. self.assertEqual(
  7306. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  7307. actual_files,
  7308. )
  7309. # Add "tests" as well
  7310. porcelain.cone_mode_add(self.repo, dirs=["tests"])
  7311. actual_files = self._list_wtree_files()
  7312. expected_files = {
  7313. os.path.join("docs", "readme.md"),
  7314. os.path.join("src", "main.py"),
  7315. os.path.join("tests", "test_bar.py"),
  7316. }
  7317. self.assertEqual(expected_files, actual_files)
  7318. # Check .git/info/sparse-checkout
  7319. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7320. with open(sp_path) as f:
  7321. lines = [ln.strip() for ln in f if ln.strip()]
  7322. # Standard cone mode lines:
  7323. # "/*" -> include top-level
  7324. # "!/*/" -> exclude subdirectories
  7325. # "!/docs/", "!/src/", "!/tests/" -> re-include the directories we added
  7326. self.assertIn("/*", lines)
  7327. self.assertIn("!/*/", lines)
  7328. self.assertIn("/docs/", lines)
  7329. self.assertIn("/src/", lines)
  7330. self.assertIn("/tests/", lines)
  7331. class UnpackObjectsTest(PorcelainTestCase):
  7332. def test_unpack_objects(self):
  7333. """Test unpacking objects from a pack file."""
  7334. # Create a test repository with some objects
  7335. b1 = Blob()
  7336. b1.data = b"test content 1"
  7337. b2 = Blob()
  7338. b2.data = b"test content 2"
  7339. # Add objects to the repo
  7340. self.repo.object_store.add_object(b1)
  7341. self.repo.object_store.add_object(b2)
  7342. # Create a pack file with these objects
  7343. pack_path = os.path.join(self.test_dir, "test_pack")
  7344. with (
  7345. open(pack_path + ".pack", "wb") as pack_f,
  7346. open(pack_path + ".idx", "wb") as idx_f,
  7347. ):
  7348. porcelain.pack_objects(
  7349. self.repo,
  7350. [b1.id, b2.id],
  7351. pack_f,
  7352. idx_f,
  7353. )
  7354. # Create a new repository to unpack into
  7355. target_repo_path = os.path.join(self.test_dir, "target_repo")
  7356. target_repo = Repo.init(target_repo_path, mkdir=True)
  7357. self.addCleanup(target_repo.close)
  7358. # Unpack the objects
  7359. count = porcelain.unpack_objects(pack_path + ".pack", target_repo_path)
  7360. # Verify the objects were unpacked
  7361. self.assertEqual(2, count)
  7362. self.assertIn(b1.id, target_repo.object_store)
  7363. self.assertIn(b2.id, target_repo.object_store)
  7364. # Verify the content is correct
  7365. unpacked_b1 = target_repo.object_store[b1.id]
  7366. unpacked_b2 = target_repo.object_store[b2.id]
  7367. self.assertEqual(b1.data, unpacked_b1.data)
  7368. self.assertEqual(b2.data, unpacked_b2.data)
  7369. class CountObjectsTests(PorcelainTestCase):
  7370. def test_count_objects_empty_repo(self):
  7371. """Test counting objects in an empty repository."""
  7372. stats = porcelain.count_objects(self.repo)
  7373. self.assertEqual(0, stats.count)
  7374. self.assertEqual(0, stats.size)
  7375. def test_count_objects_verbose_empty_repo(self):
  7376. """Test verbose counting in an empty repository."""
  7377. stats = porcelain.count_objects(self.repo, verbose=True)
  7378. self.assertEqual(0, stats.count)
  7379. self.assertEqual(0, stats.size)
  7380. self.assertEqual(0, stats.in_pack)
  7381. self.assertEqual(0, stats.packs)
  7382. self.assertEqual(0, stats.size_pack)
  7383. def test_count_objects_with_loose_objects(self):
  7384. """Test counting loose objects."""
  7385. # Create some loose objects
  7386. blob1 = make_object(Blob, data=b"data1")
  7387. blob2 = make_object(Blob, data=b"data2")
  7388. self.repo.object_store.add_object(blob1)
  7389. self.repo.object_store.add_object(blob2)
  7390. stats = porcelain.count_objects(self.repo)
  7391. self.assertEqual(2, stats.count)
  7392. self.assertGreater(stats.size, 0)
  7393. def test_count_objects_verbose_with_objects(self):
  7394. """Test verbose counting with both loose and packed objects."""
  7395. # Add some loose objects
  7396. for i in range(3):
  7397. blob = make_object(Blob, data=f"data{i}".encode())
  7398. self.repo.object_store.add_object(blob)
  7399. # Create a simple commit to have some objects in a pack
  7400. tree = Tree()
  7401. c1 = make_commit(tree=tree.id, message=b"Test commit")
  7402. self.repo.object_store.add_objects([(tree, None), (c1, None)])
  7403. self.repo.refs[b"HEAD"] = c1.id
  7404. # Repack to create a pack file
  7405. porcelain.repack(self.repo)
  7406. stats = porcelain.count_objects(self.repo, verbose=True)
  7407. # After repacking, loose objects might be cleaned up
  7408. self.assertIsInstance(stats.count, int)
  7409. self.assertIsInstance(stats.size, int)
  7410. self.assertGreater(stats.in_pack, 0) # Should have packed objects
  7411. self.assertGreater(stats.packs, 0) # Should have at least one pack
  7412. self.assertGreater(stats.size_pack, 0) # Pack should have size
  7413. # Verify it's the correct dataclass type
  7414. self.assertIsInstance(stats, CountObjectsResult)
  7415. class PruneTests(PorcelainTestCase):
  7416. def test_prune_removes_old_tempfiles(self):
  7417. """Test that prune removes old temporary files."""
  7418. # Create an old temporary file in the objects directory
  7419. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7420. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_test")
  7421. with open(tmp_pack_path, "wb") as f:
  7422. f.write(b"old temporary data")
  7423. # Make it old
  7424. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  7425. os.utime(tmp_pack_path, (old_time, old_time))
  7426. # Run prune
  7427. porcelain.prune(self.repo.path)
  7428. # Verify the file was removed
  7429. self.assertFalse(os.path.exists(tmp_pack_path))
  7430. def test_prune_keeps_recent_tempfiles(self):
  7431. """Test that prune keeps recent temporary files."""
  7432. # Create a recent temporary file
  7433. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7434. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_recent")
  7435. with open(tmp_pack_path, "wb") as f:
  7436. f.write(b"recent temporary data")
  7437. self.addCleanup(os.remove, tmp_pack_path)
  7438. # Run prune
  7439. porcelain.prune(self.repo.path)
  7440. # Verify the file was NOT removed
  7441. self.assertTrue(os.path.exists(tmp_pack_path))
  7442. def test_prune_with_custom_grace_period(self):
  7443. """Test prune with custom grace period."""
  7444. # Create a 1-hour-old temporary file
  7445. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7446. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_1hour")
  7447. with open(tmp_pack_path, "wb") as f:
  7448. f.write(b"1 hour old data")
  7449. # Make it 1 hour old
  7450. old_time = time.time() - 3600
  7451. os.utime(tmp_pack_path, (old_time, old_time))
  7452. # Prune with 30-minute grace period should remove it
  7453. porcelain.prune(self.repo.path, grace_period=1800)
  7454. # Verify the file was removed
  7455. self.assertFalse(os.path.exists(tmp_pack_path))
  7456. def test_prune_dry_run(self):
  7457. """Test prune in dry-run mode."""
  7458. # Create an old temporary file
  7459. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7460. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_dryrun")
  7461. with open(tmp_pack_path, "wb") as f:
  7462. f.write(b"old temporary data")
  7463. self.addCleanup(os.remove, tmp_pack_path)
  7464. # Make it old
  7465. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  7466. os.utime(tmp_pack_path, (old_time, old_time))
  7467. # Run prune in dry-run mode
  7468. porcelain.prune(self.repo.path, dry_run=True)
  7469. # Verify the file was NOT removed (dry run)
  7470. self.assertTrue(os.path.exists(tmp_pack_path))
  7471. class FilterBranchTests(PorcelainTestCase):
  7472. def setUp(self):
  7473. super().setUp()
  7474. # Create initial commits with different authors
  7475. from dulwich.objects import Commit, Tree
  7476. # Create actual tree and blob objects
  7477. tree = Tree()
  7478. self.repo.object_store.add_object(tree)
  7479. c1 = Commit()
  7480. c1.tree = tree.id
  7481. c1.parents = []
  7482. c1.author = b"Old Author <old@example.com>"
  7483. c1.author_time = 1000
  7484. c1.author_timezone = 0
  7485. c1.committer = b"Old Committer <old@example.com>"
  7486. c1.commit_time = 1000
  7487. c1.commit_timezone = 0
  7488. c1.message = b"Initial commit"
  7489. self.repo.object_store.add_object(c1)
  7490. c2 = Commit()
  7491. c2.tree = tree.id
  7492. c2.parents = [c1.id]
  7493. c2.author = b"Another Author <another@example.com>"
  7494. c2.author_time = 2000
  7495. c2.author_timezone = 0
  7496. c2.committer = b"Another Committer <another@example.com>"
  7497. c2.commit_time = 2000
  7498. c2.commit_timezone = 0
  7499. c2.message = b"Second commit\n\nWith body"
  7500. self.repo.object_store.add_object(c2)
  7501. c3 = Commit()
  7502. c3.tree = tree.id
  7503. c3.parents = [c2.id]
  7504. c3.author = b"Third Author <third@example.com>"
  7505. c3.author_time = 3000
  7506. c3.author_timezone = 0
  7507. c3.committer = b"Third Committer <third@example.com>"
  7508. c3.commit_time = 3000
  7509. c3.commit_timezone = 0
  7510. c3.message = b"Third commit"
  7511. self.repo.object_store.add_object(c3)
  7512. self.repo.refs[b"refs/heads/master"] = c3.id
  7513. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  7514. # Store IDs for test assertions
  7515. self.c1_id = c1.id
  7516. self.c2_id = c2.id
  7517. self.c3_id = c3.id
  7518. def test_filter_branch_author(self):
  7519. """Test filtering branch with author changes."""
  7520. def filter_author(author):
  7521. # Change all authors to "New Author"
  7522. return b"New Author <new@example.com>"
  7523. result = porcelain.filter_branch(
  7524. self.repo_path, "master", filter_author=filter_author
  7525. )
  7526. # Check that we have mappings for all commits
  7527. self.assertEqual(len(result), 3)
  7528. # Verify the branch ref was updated
  7529. new_head = self.repo.refs[b"refs/heads/master"]
  7530. self.assertNotEqual(new_head, self.c3_id)
  7531. # Verify the original ref was saved
  7532. original_ref = self.repo.refs[b"refs/original/refs/heads/master"]
  7533. self.assertEqual(original_ref, self.c3_id)
  7534. # Check that authors were updated
  7535. new_commit = self.repo[new_head]
  7536. self.assertEqual(new_commit.author, b"New Author <new@example.com>")
  7537. # Check parent chain
  7538. parent = self.repo[new_commit.parents[0]]
  7539. self.assertEqual(parent.author, b"New Author <new@example.com>")
  7540. def test_filter_branch_message(self):
  7541. """Test filtering branch with message changes."""
  7542. def filter_message(message):
  7543. # Add prefix to all messages
  7544. return b"[FILTERED] " + message
  7545. porcelain.filter_branch(self.repo_path, "master", filter_message=filter_message)
  7546. # Verify messages were updated
  7547. new_head = self.repo.refs[b"refs/heads/master"]
  7548. new_commit = self.repo[new_head]
  7549. self.assertTrue(new_commit.message.startswith(b"[FILTERED] "))
  7550. def test_filter_branch_custom_filter(self):
  7551. """Test filtering branch with custom filter function."""
  7552. def custom_filter(commit):
  7553. # Change both author and message
  7554. return {
  7555. "author": b"Custom Author <custom@example.com>",
  7556. "message": b"Custom: " + commit.message,
  7557. }
  7558. porcelain.filter_branch(self.repo_path, "master", filter_fn=custom_filter)
  7559. # Verify custom filter was applied
  7560. new_head = self.repo.refs[b"refs/heads/master"]
  7561. new_commit = self.repo[new_head]
  7562. self.assertEqual(new_commit.author, b"Custom Author <custom@example.com>")
  7563. self.assertTrue(new_commit.message.startswith(b"Custom: "))
  7564. def test_filter_branch_no_changes(self):
  7565. """Test filtering branch with no changes."""
  7566. result = porcelain.filter_branch(self.repo_path, "master")
  7567. # All commits should map to themselves
  7568. for old_sha, new_sha in result.items():
  7569. self.assertEqual(old_sha, new_sha)
  7570. # HEAD should be unchanged
  7571. self.assertEqual(self.repo.refs[b"refs/heads/master"], self.c3_id)
  7572. def test_filter_branch_force(self):
  7573. """Test force filtering a previously filtered branch."""
  7574. # First filter
  7575. porcelain.filter_branch(
  7576. self.repo_path, "master", filter_message=lambda m: b"First: " + m
  7577. )
  7578. # Try again without force - should fail
  7579. with self.assertRaises(porcelain.Error):
  7580. porcelain.filter_branch(
  7581. self.repo_path, "master", filter_message=lambda m: b"Second: " + m
  7582. )
  7583. # Try again with force - should succeed
  7584. porcelain.filter_branch(
  7585. self.repo_path,
  7586. "master",
  7587. filter_message=lambda m: b"Second: " + m,
  7588. force=True,
  7589. )
  7590. # Verify second filter was applied
  7591. new_head = self.repo.refs[b"refs/heads/master"]
  7592. new_commit = self.repo[new_head]
  7593. self.assertTrue(new_commit.message.startswith(b"Second: First: "))
  7594. class StashTests(PorcelainTestCase):
  7595. def setUp(self) -> None:
  7596. super().setUp()
  7597. # Create initial commit
  7598. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  7599. f.write(b"initial content")
  7600. porcelain.add(repo=self.repo.path, paths=["initial.txt"])
  7601. porcelain.commit(
  7602. repo=self.repo.path,
  7603. message=b"Initial commit",
  7604. author=b"Test Author <test@example.com>",
  7605. committer=b"Test Committer <test@example.com>",
  7606. )
  7607. def test_stash_push_and_pop(self) -> None:
  7608. # Create a new file and stage it
  7609. new_file = os.path.join(self.repo.path, "new.txt")
  7610. with open(new_file, "wb") as f:
  7611. f.write(b"new file content")
  7612. porcelain.add(repo=self.repo.path, paths=["new.txt"])
  7613. # Modify existing file
  7614. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  7615. f.write(b"modified content")
  7616. # Push to stash
  7617. porcelain.stash_push(self.repo.path)
  7618. # Verify files are reset
  7619. self.assertFalse(os.path.exists(new_file))
  7620. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  7621. self.assertEqual(b"initial content", f.read())
  7622. # Pop the stash
  7623. porcelain.stash_pop(self.repo.path)
  7624. # Verify files are restored
  7625. self.assertTrue(os.path.exists(new_file))
  7626. with open(new_file, "rb") as f:
  7627. self.assertEqual(b"new file content", f.read())
  7628. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  7629. self.assertEqual(b"modified content", f.read())
  7630. # Verify new file is in the index
  7631. from dulwich.index import Index
  7632. index = Index(os.path.join(self.repo.path, ".git", "index"))
  7633. self.assertIn(b"new.txt", index)
  7634. def test_stash_list(self) -> None:
  7635. # Initially no stashes
  7636. stashes = list(porcelain.stash_list(self.repo.path))
  7637. self.assertEqual(0, len(stashes))
  7638. # Create a file and stash it
  7639. test_file = os.path.join(self.repo.path, "test.txt")
  7640. with open(test_file, "wb") as f:
  7641. f.write(b"test content")
  7642. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  7643. # Push first stash
  7644. porcelain.stash_push(self.repo.path)
  7645. # Create another file and stash it
  7646. test_file2 = os.path.join(self.repo.path, "test2.txt")
  7647. with open(test_file2, "wb") as f:
  7648. f.write(b"test content 2")
  7649. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  7650. # Push second stash
  7651. porcelain.stash_push(self.repo.path)
  7652. # Check stash list
  7653. stashes = list(porcelain.stash_list(self.repo.path))
  7654. self.assertEqual(2, len(stashes))
  7655. # Stashes are returned in order (most recent first)
  7656. self.assertEqual(0, stashes[0][0])
  7657. self.assertEqual(1, stashes[1][0])
  7658. def test_stash_drop(self) -> None:
  7659. # Create and stash some changes
  7660. test_file = os.path.join(self.repo.path, "test.txt")
  7661. with open(test_file, "wb") as f:
  7662. f.write(b"test content")
  7663. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  7664. porcelain.stash_push(self.repo.path)
  7665. # Create another stash
  7666. test_file2 = os.path.join(self.repo.path, "test2.txt")
  7667. with open(test_file2, "wb") as f:
  7668. f.write(b"test content 2")
  7669. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  7670. porcelain.stash_push(self.repo.path)
  7671. # Verify we have 2 stashes
  7672. stashes = list(porcelain.stash_list(self.repo.path))
  7673. self.assertEqual(2, len(stashes))
  7674. # Drop the first stash (index 0)
  7675. porcelain.stash_drop(self.repo.path, 0)
  7676. # Verify we have 1 stash left
  7677. stashes = list(porcelain.stash_list(self.repo.path))
  7678. self.assertEqual(1, len(stashes))
  7679. # The remaining stash should be the one we created first
  7680. # Pop it and verify it's the first file
  7681. porcelain.stash_pop(self.repo.path)
  7682. self.assertTrue(os.path.exists(test_file))
  7683. self.assertFalse(os.path.exists(test_file2))
  7684. def test_stash_pop_empty(self) -> None:
  7685. # Attempting to pop from empty stash should raise an error
  7686. with self.assertRaises(IndexError):
  7687. porcelain.stash_pop(self.repo.path)
  7688. def test_stash_with_untracked_files(self) -> None:
  7689. # Create an untracked file
  7690. untracked_file = os.path.join(self.repo.path, "untracked.txt")
  7691. with open(untracked_file, "wb") as f:
  7692. f.write(b"untracked content")
  7693. # Create a tracked change
  7694. tracked_file = os.path.join(self.repo.path, "tracked.txt")
  7695. with open(tracked_file, "wb") as f:
  7696. f.write(b"tracked content")
  7697. porcelain.add(repo=self.repo.path, paths=["tracked.txt"])
  7698. # Stash (by default, untracked files are not included)
  7699. porcelain.stash_push(self.repo.path)
  7700. # Untracked file should still exist
  7701. self.assertTrue(os.path.exists(untracked_file))
  7702. # Tracked file should be gone
  7703. self.assertFalse(os.path.exists(tracked_file))
  7704. # Pop the stash
  7705. porcelain.stash_pop(self.repo.path)
  7706. # Tracked file should be restored
  7707. self.assertTrue(os.path.exists(tracked_file))
  7708. class BisectTests(PorcelainTestCase):
  7709. """Tests for bisect porcelain functions."""
  7710. def test_bisect_start(self):
  7711. """Test starting a bisect session."""
  7712. # Create some commits
  7713. _c1, _c2, c3 = build_commit_graph(
  7714. self.repo.object_store,
  7715. [[1], [2, 1], [3, 2]],
  7716. attrs={
  7717. 1: {"message": b"initial"},
  7718. 2: {"message": b"second"},
  7719. 3: {"message": b"third"},
  7720. },
  7721. )
  7722. self.repo.refs[b"refs/heads/master"] = c3.id
  7723. self.repo.refs[b"HEAD"] = c3.id
  7724. # Start bisect
  7725. porcelain.bisect_start(self.repo_path)
  7726. # Check that bisect state files exist
  7727. self.assertTrue(
  7728. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  7729. )
  7730. self.assertTrue(
  7731. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_TERMS"))
  7732. )
  7733. self.assertTrue(
  7734. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_NAMES"))
  7735. )
  7736. self.assertTrue(
  7737. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_LOG"))
  7738. )
  7739. def test_bisect_workflow(self):
  7740. """Test a complete bisect workflow."""
  7741. # Create some commits
  7742. c1, c2, c3, c4 = build_commit_graph(
  7743. self.repo.object_store,
  7744. [[1], [2, 1], [3, 2], [4, 3]],
  7745. attrs={
  7746. 1: {"message": b"good commit 1"},
  7747. 2: {"message": b"good commit 2"},
  7748. 3: {"message": b"bad commit"},
  7749. 4: {"message": b"bad commit 2"},
  7750. },
  7751. )
  7752. self.repo.refs[b"refs/heads/master"] = c4.id
  7753. self.repo.refs[b"HEAD"] = c4.id
  7754. # Start bisect with bad and good
  7755. next_sha = porcelain.bisect_start(self.repo_path, bad=c4.id, good=c1.id)
  7756. # Should return the middle commit
  7757. self.assertIsNotNone(next_sha)
  7758. self.assertIn(next_sha, [c2.id, c3.id])
  7759. # Mark the middle commit as good or bad
  7760. if next_sha == c2.id:
  7761. # c2 is good, next should be c3
  7762. next_sha = porcelain.bisect_good(self.repo_path)
  7763. self.assertEqual(next_sha, c3.id)
  7764. # Mark c3 as bad - bisect complete
  7765. next_sha = porcelain.bisect_bad(self.repo_path)
  7766. self.assertIsNone(next_sha)
  7767. else:
  7768. # c3 is bad, next should be c2
  7769. next_sha = porcelain.bisect_bad(self.repo_path)
  7770. self.assertEqual(next_sha, c2.id)
  7771. # Mark c2 as good - bisect complete
  7772. next_sha = porcelain.bisect_good(self.repo_path)
  7773. self.assertIsNone(next_sha)
  7774. def test_bisect_log(self):
  7775. """Test getting bisect log."""
  7776. # Create some commits
  7777. c1, _c2, c3 = build_commit_graph(
  7778. self.repo.object_store,
  7779. [[1], [2, 1], [3, 2]],
  7780. attrs={
  7781. 1: {"message": b"initial"},
  7782. 2: {"message": b"second"},
  7783. 3: {"message": b"third"},
  7784. },
  7785. )
  7786. self.repo.refs[b"refs/heads/master"] = c3.id
  7787. self.repo.refs[b"HEAD"] = c3.id
  7788. # Start bisect and mark commits
  7789. porcelain.bisect_start(self.repo_path)
  7790. porcelain.bisect_bad(self.repo_path, c3.id)
  7791. porcelain.bisect_good(self.repo_path, c1.id)
  7792. # Get log
  7793. log = porcelain.bisect_log(self.repo_path)
  7794. self.assertIn("git bisect start", log)
  7795. self.assertIn("git bisect bad", log)
  7796. self.assertIn("git bisect good", log)
  7797. def test_bisect_reset(self):
  7798. """Test resetting bisect state."""
  7799. # Create some commits
  7800. c1, _c2, c3 = build_commit_graph(
  7801. self.repo.object_store,
  7802. [[1], [2, 1], [3, 2]],
  7803. attrs={
  7804. 1: {"message": b"initial"},
  7805. 2: {"message": b"second"},
  7806. 3: {"message": b"third"},
  7807. },
  7808. )
  7809. self.repo.refs[b"refs/heads/master"] = c3.id
  7810. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  7811. # Start bisect
  7812. porcelain.bisect_start(self.repo_path)
  7813. porcelain.bisect_bad(self.repo_path)
  7814. porcelain.bisect_good(self.repo_path, c1.id)
  7815. # Reset
  7816. porcelain.bisect_reset(self.repo_path)
  7817. # Check that bisect state files are removed
  7818. self.assertFalse(
  7819. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  7820. )
  7821. self.assertFalse(
  7822. os.path.exists(os.path.join(self.repo.controldir(), "refs", "bisect"))
  7823. )
  7824. # HEAD should be back to being a symbolic ref to master
  7825. head_target, _ = self.repo.refs.follow(b"HEAD")
  7826. self.assertEqual(head_target[-1], b"refs/heads/master")
  7827. def test_bisect_skip(self):
  7828. """Test skipping commits during bisect."""
  7829. # Create some commits
  7830. c1, c2, _c3, _c4, c5 = build_commit_graph(
  7831. self.repo.object_store,
  7832. [[1], [2, 1], [3, 2], [4, 3], [5, 4]],
  7833. attrs={
  7834. 1: {"message": b"good"},
  7835. 2: {"message": b"skip this"},
  7836. 3: {"message": b"bad"},
  7837. 4: {"message": b"bad"},
  7838. 5: {"message": b"bad"},
  7839. },
  7840. )
  7841. self.repo.refs[b"refs/heads/master"] = c5.id
  7842. self.repo.refs[b"HEAD"] = c5.id
  7843. # Start bisect
  7844. porcelain.bisect_start(self.repo_path, bad=c5.id, good=c1.id)
  7845. # Skip c2 if it's selected
  7846. next_sha = porcelain.bisect_skip(self.repo_path, [c2.id])
  7847. self.assertIsNotNone(next_sha)
  7848. class ReflogTest(PorcelainTestCase):
  7849. def test_reflog_head(self):
  7850. """Test reading HEAD reflog."""
  7851. # Create a commit
  7852. blob = Blob.from_string(b"test content")
  7853. self.repo.object_store.add_object(blob)
  7854. tree = Tree()
  7855. tree.add(b"test", 0o100644, blob.id)
  7856. self.repo.object_store.add_object(tree)
  7857. commit = Commit()
  7858. commit.tree = tree.id
  7859. commit.author = b"Test Author <test@example.com>"
  7860. commit.committer = b"Test Author <test@example.com>"
  7861. commit.commit_time = 1234567890
  7862. commit.commit_timezone = 0
  7863. commit.author_time = 1234567890
  7864. commit.author_timezone = 0
  7865. commit.message = b"Initial commit"
  7866. self.repo.object_store.add_object(commit)
  7867. # Write a reflog entry
  7868. self.repo._write_reflog(
  7869. b"HEAD",
  7870. ZERO_SHA,
  7871. commit.id,
  7872. b"Test Author <test@example.com>",
  7873. 1234567890,
  7874. 0,
  7875. b"commit (initial): Initial commit",
  7876. )
  7877. # Read reflog using porcelain
  7878. entries = list(porcelain.reflog(self.repo_path))
  7879. self.assertEqual(1, len(entries))
  7880. self.assertEqual(ZERO_SHA, entries[0].old_sha)
  7881. self.assertEqual(commit.id, entries[0].new_sha)
  7882. self.assertEqual(b"Test Author <test@example.com>", entries[0].committer)
  7883. self.assertEqual(1234567890, entries[0].timestamp)
  7884. self.assertEqual(0, entries[0].timezone)
  7885. self.assertEqual(b"commit (initial): Initial commit", entries[0].message)
  7886. def test_reflog_with_string_ref(self):
  7887. """Test reading reflog with string reference."""
  7888. # Create a commit
  7889. blob = Blob.from_string(b"test content")
  7890. self.repo.object_store.add_object(blob)
  7891. tree = Tree()
  7892. tree.add(b"test", 0o100644, blob.id)
  7893. self.repo.object_store.add_object(tree)
  7894. commit = Commit()
  7895. commit.tree = tree.id
  7896. commit.author = b"Test Author <test@example.com>"
  7897. commit.committer = b"Test Author <test@example.com>"
  7898. commit.commit_time = 1234567890
  7899. commit.commit_timezone = 0
  7900. commit.author_time = 1234567890
  7901. commit.author_timezone = 0
  7902. commit.message = b"Initial commit"
  7903. self.repo.object_store.add_object(commit)
  7904. # Write a reflog entry
  7905. self.repo._write_reflog(
  7906. b"refs/heads/master",
  7907. ZERO_SHA,
  7908. commit.id,
  7909. b"Test Author <test@example.com>",
  7910. 1234567890,
  7911. 0,
  7912. b"commit (initial): Initial commit",
  7913. )
  7914. # Read reflog using porcelain with string ref
  7915. entries = list(porcelain.reflog(self.repo_path, "refs/heads/master"))
  7916. self.assertEqual(1, len(entries))
  7917. self.assertEqual(commit.id, entries[0].new_sha)
  7918. def test_reflog_all(self):
  7919. """Test reading all reflogs."""
  7920. # Create a commit
  7921. blob = Blob.from_string(b"test content")
  7922. self.repo.object_store.add_object(blob)
  7923. tree = Tree()
  7924. tree.add(b"test", 0o100644, blob.id)
  7925. self.repo.object_store.add_object(tree)
  7926. commit = Commit()
  7927. commit.tree = tree.id
  7928. commit.author = b"Test Author <test@example.com>"
  7929. commit.committer = b"Test Author <test@example.com>"
  7930. commit.commit_time = 1234567890
  7931. commit.commit_timezone = 0
  7932. commit.author_time = 1234567890
  7933. commit.author_timezone = 0
  7934. commit.message = b"Initial commit"
  7935. self.repo.object_store.add_object(commit)
  7936. # Write reflog entries for HEAD and master
  7937. self.repo._write_reflog(
  7938. b"HEAD",
  7939. ZERO_SHA,
  7940. commit.id,
  7941. b"Test Author <test@example.com>",
  7942. 1234567890,
  7943. 0,
  7944. b"commit (initial): Initial commit",
  7945. )
  7946. self.repo._write_reflog(
  7947. b"refs/heads/master",
  7948. ZERO_SHA,
  7949. commit.id,
  7950. b"Test Author <test@example.com>",
  7951. 1234567891,
  7952. 0,
  7953. b"branch: Created from HEAD",
  7954. )
  7955. # Read all reflogs using porcelain
  7956. entries = list(porcelain.reflog(self.repo_path, all=True))
  7957. # Should have at least 2 entries (HEAD and refs/heads/master)
  7958. self.assertGreaterEqual(len(entries), 2)
  7959. # Check that we got entries from different refs
  7960. refs_seen = set()
  7961. for ref, entry in entries:
  7962. refs_seen.add(ref)
  7963. self.assertEqual(commit.id, entry.new_sha)
  7964. # Should have seen at least HEAD and refs/heads/master
  7965. self.assertIn(b"HEAD", refs_seen)
  7966. self.assertIn(b"refs/heads/master", refs_seen)
  7967. class WriteCommitGraphTests(PorcelainTestCase):
  7968. """Tests for the write_commit_graph porcelain function."""
  7969. def test_write_commit_graph_empty_repo(self):
  7970. """Test writing commit graph on empty repository."""
  7971. # Should not fail on empty repo
  7972. porcelain.write_commit_graph(self.repo_path)
  7973. # No commit graph should be created for empty repo
  7974. graph_path = os.path.join(
  7975. self.repo_path, ".git", "objects", "info", "commit-graph"
  7976. )
  7977. self.assertFalse(os.path.exists(graph_path))
  7978. def test_write_commit_graph_with_commits(self):
  7979. """Test writing commit graph with commits."""
  7980. # Create some commits
  7981. c1, c2, c3 = build_commit_graph(
  7982. self.repo.object_store,
  7983. [[1], [2, 1], [3, 1, 2]],
  7984. attrs={
  7985. 1: {"message": b"First commit"},
  7986. 2: {"message": b"Second commit"},
  7987. 3: {"message": b"Merge commit"},
  7988. },
  7989. )
  7990. self.repo.refs[b"refs/heads/master"] = c3.id
  7991. self.repo.refs[b"refs/heads/branch"] = c2.id
  7992. # Write commit graph
  7993. porcelain.write_commit_graph(self.repo_path)
  7994. # Verify commit graph was created
  7995. graph_path = os.path.join(
  7996. self.repo_path, ".git", "objects", "info", "commit-graph"
  7997. )
  7998. self.assertTrue(os.path.exists(graph_path))
  7999. # Load and verify the commit graph
  8000. from dulwich.commit_graph import read_commit_graph
  8001. commit_graph = read_commit_graph(graph_path)
  8002. self.assertIsNotNone(commit_graph)
  8003. self.assertEqual(3, len(commit_graph))
  8004. # Verify all commits are in the graph
  8005. for commit_obj in [c1, c2, c3]:
  8006. entry = commit_graph.get_entry_by_oid(commit_obj.id)
  8007. self.assertIsNotNone(entry)
  8008. def test_write_commit_graph_config_disabled(self):
  8009. """Test that commit graph is not written when disabled by config."""
  8010. # Create a commit
  8011. (c1,) = build_commit_graph(
  8012. self.repo.object_store, [[1]], attrs={1: {"message": b"First commit"}}
  8013. )
  8014. self.repo.refs[b"refs/heads/master"] = c1.id
  8015. # Disable commit graph in config
  8016. config = self.repo.get_config()
  8017. config.set((b"core",), b"commitGraph", b"false")
  8018. config.write_to_path()
  8019. # Write commit graph (should respect config)
  8020. porcelain.write_commit_graph(self.repo_path)
  8021. # Verify commit graph still gets written
  8022. # (porcelain.write_commit_graph explicitly writes regardless of config)
  8023. graph_path = os.path.join(
  8024. self.repo_path, ".git", "objects", "info", "commit-graph"
  8025. )
  8026. self.assertTrue(os.path.exists(graph_path))
  8027. def test_write_commit_graph_reachable_false(self):
  8028. """Test writing commit graph with reachable=False."""
  8029. # Create commits
  8030. _c1, _c2, c3 = build_commit_graph(
  8031. self.repo.object_store,
  8032. [[1], [2, 1], [3, 2]],
  8033. attrs={
  8034. 1: {"message": b"First commit"},
  8035. 2: {"message": b"Second commit"},
  8036. 3: {"message": b"Third commit"},
  8037. },
  8038. )
  8039. # Only reference the third commit
  8040. self.repo.refs[b"refs/heads/master"] = c3.id
  8041. # Write commit graph with reachable=False
  8042. porcelain.write_commit_graph(self.repo_path, reachable=False)
  8043. # Verify commit graph was created
  8044. graph_path = os.path.join(
  8045. self.repo_path, ".git", "objects", "info", "commit-graph"
  8046. )
  8047. self.assertTrue(os.path.exists(graph_path))
  8048. # Load and verify the commit graph
  8049. from dulwich.commit_graph import read_commit_graph
  8050. commit_graph = read_commit_graph(graph_path)
  8051. self.assertIsNotNone(commit_graph)
  8052. # With reachable=False, only directly referenced commits should be included
  8053. # In this case, only c3 (from refs/heads/master)
  8054. self.assertEqual(1, len(commit_graph))
  8055. entry = commit_graph.get_entry_by_oid(c3.id)
  8056. self.assertIsNotNone(entry)
  8057. class WorktreePorcelainTests(PorcelainTestCase):
  8058. """Tests for porcelain worktree functions."""
  8059. def test_worktree_list_single(self):
  8060. """Test listing worktrees when only main worktree exists."""
  8061. # Create initial commit
  8062. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8063. f.write("test content")
  8064. porcelain.add(self.repo_path, ["test.txt"])
  8065. porcelain.commit(self.repo_path, message=b"Initial commit")
  8066. # List worktrees
  8067. worktrees = porcelain.worktree_list(self.repo_path)
  8068. self.assertEqual(len(worktrees), 1)
  8069. self.assertEqual(worktrees[0].path, self.repo_path)
  8070. self.assertFalse(worktrees[0].bare)
  8071. self.assertIsNotNone(worktrees[0].head)
  8072. self.assertIsNotNone(worktrees[0].branch)
  8073. def test_worktree_add_branch(self):
  8074. """Test adding a worktree with a new branch."""
  8075. # Create initial commit
  8076. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8077. f.write("test content")
  8078. porcelain.add(self.repo_path, ["test.txt"])
  8079. porcelain.commit(self.repo_path, message=b"Initial commit")
  8080. # Add worktree
  8081. wt_path = os.path.join(self.test_dir, "worktree1")
  8082. result_path = porcelain.worktree_add(self.repo_path, wt_path, branch=b"feature")
  8083. self.assertEqual(result_path, wt_path)
  8084. self.assertTrue(os.path.exists(wt_path))
  8085. self.assertTrue(os.path.exists(os.path.join(wt_path, ".git")))
  8086. # Check it appears in the list
  8087. worktrees = porcelain.worktree_list(self.repo_path)
  8088. self.assertEqual(len(worktrees), 2)
  8089. # Find the new worktree
  8090. new_wt = None
  8091. for wt in worktrees:
  8092. if wt.path == wt_path:
  8093. new_wt = wt
  8094. break
  8095. self.assertIsNotNone(new_wt)
  8096. self.assertEqual(new_wt.branch, b"refs/heads/feature")
  8097. self.assertFalse(new_wt.detached)
  8098. def test_worktree_add_detached(self):
  8099. """Test adding a detached worktree."""
  8100. # Create initial commit
  8101. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8102. f.write("test content")
  8103. porcelain.add(self.repo_path, ["test.txt"])
  8104. sha = porcelain.commit(self.repo_path, message=b"Initial commit")
  8105. # Add detached worktree
  8106. wt_path = os.path.join(self.test_dir, "detached")
  8107. porcelain.worktree_add(self.repo_path, wt_path, commit=sha, detach=True)
  8108. # Check it's detached
  8109. worktrees = porcelain.worktree_list(self.repo_path)
  8110. for wt in worktrees:
  8111. if wt.path == wt_path:
  8112. self.assertTrue(wt.detached)
  8113. self.assertIsNone(wt.branch)
  8114. self.assertEqual(wt.head, sha)
  8115. def test_worktree_remove(self):
  8116. """Test removing a worktree."""
  8117. # Create initial commit
  8118. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8119. f.write("test content")
  8120. porcelain.add(self.repo_path, ["test.txt"])
  8121. porcelain.commit(self.repo_path, message=b"Initial commit")
  8122. # Add and remove worktree
  8123. wt_path = os.path.join(self.test_dir, "to-remove")
  8124. porcelain.worktree_add(self.repo_path, wt_path)
  8125. # Verify it exists
  8126. self.assertTrue(os.path.exists(wt_path))
  8127. self.assertEqual(len(porcelain.worktree_list(self.repo_path)), 2)
  8128. # Remove it
  8129. porcelain.worktree_remove(self.repo_path, wt_path)
  8130. # Verify it's gone
  8131. self.assertFalse(os.path.exists(wt_path))
  8132. self.assertEqual(len(porcelain.worktree_list(self.repo_path)), 1)
  8133. def test_worktree_prune(self):
  8134. """Test pruning worktrees."""
  8135. # Create initial commit
  8136. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8137. f.write("test content")
  8138. porcelain.add(self.repo_path, ["test.txt"])
  8139. porcelain.commit(self.repo_path, message=b"Initial commit")
  8140. # Add worktree
  8141. wt_path = os.path.join(self.test_dir, "to-prune")
  8142. porcelain.worktree_add(self.repo_path, wt_path)
  8143. # Manually remove directory
  8144. shutil.rmtree(wt_path)
  8145. # Prune should remove the administrative files
  8146. pruned = porcelain.worktree_prune(self.repo_path)
  8147. self.assertEqual(len(pruned), 1)
  8148. # Verify it's gone from the list
  8149. worktrees = porcelain.worktree_list(self.repo_path)
  8150. self.assertEqual(len(worktrees), 1)
  8151. def test_worktree_lock_unlock(self):
  8152. """Test locking and unlocking worktrees."""
  8153. # Create initial commit
  8154. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8155. f.write("test content")
  8156. porcelain.add(self.repo_path, ["test.txt"])
  8157. porcelain.commit(self.repo_path, message=b"Initial commit")
  8158. # Add worktree
  8159. wt_path = os.path.join(self.test_dir, "lockable")
  8160. porcelain.worktree_add(self.repo_path, wt_path)
  8161. # Lock it
  8162. porcelain.worktree_lock(self.repo_path, wt_path, reason="Testing")
  8163. # Verify it's locked
  8164. worktrees = porcelain.worktree_list(self.repo_path)
  8165. for wt in worktrees:
  8166. if wt.path == wt_path:
  8167. self.assertTrue(wt.locked)
  8168. # Unlock it
  8169. porcelain.worktree_unlock(self.repo_path, wt_path)
  8170. # Verify it's unlocked
  8171. worktrees = porcelain.worktree_list(self.repo_path)
  8172. for wt in worktrees:
  8173. if wt.path == wt_path:
  8174. self.assertFalse(wt.locked)
  8175. def test_worktree_move(self):
  8176. """Test moving a worktree."""
  8177. # Create initial commit
  8178. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8179. f.write("test content")
  8180. porcelain.add(self.repo_path, ["test.txt"])
  8181. porcelain.commit(self.repo_path, message=b"Initial commit")
  8182. # Add worktree
  8183. old_path = os.path.join(self.test_dir, "old-location")
  8184. porcelain.worktree_add(self.repo_path, old_path)
  8185. # Create a file in the worktree
  8186. test_file = os.path.join(old_path, "workspace.txt")
  8187. with open(test_file, "w") as f:
  8188. f.write("workspace content")
  8189. # Move it
  8190. new_path = os.path.join(self.test_dir, "new-location")
  8191. porcelain.worktree_move(self.repo_path, old_path, new_path)
  8192. # Verify old path doesn't exist, new path does
  8193. self.assertFalse(os.path.exists(old_path))
  8194. self.assertTrue(os.path.exists(new_path))
  8195. self.assertTrue(os.path.exists(os.path.join(new_path, "workspace.txt")))
  8196. # Verify it's in the list at new location
  8197. worktrees = porcelain.worktree_list(self.repo_path)
  8198. paths = [wt.path for wt in worktrees]
  8199. self.assertIn(new_path, paths)
  8200. self.assertNotIn(old_path, paths)
  8201. class VarTests(PorcelainTestCase):
  8202. """Tests for the var command."""
  8203. def test_var_author_ident(self):
  8204. """Test getting GIT_AUTHOR_IDENT."""
  8205. # Set up user config
  8206. config = self.repo.get_config()
  8207. config.set((b"user",), b"name", b"Test Author")
  8208. config.set((b"user",), b"email", b"author@example.com")
  8209. config.write_to_path()
  8210. result = porcelain.var(self.repo_path, variable="GIT_AUTHOR_IDENT")
  8211. self.assertIn("Test Author <author@example.com>", result)
  8212. # Check that timestamp and timezone are included
  8213. # Format: Name <email> timestamp timezone
  8214. # "Test Author" is 2 words, so we have: Test, Author, <email>, timestamp, timezone
  8215. parts = result.split()
  8216. self.assertGreaterEqual(
  8217. len(parts), 4
  8218. ) # At least name, <email>, timestamp, timezone
  8219. # Check last two parts are timestamp and timezone
  8220. self.assertTrue(parts[-2].isdigit()) # timestamp
  8221. self.assertRegex(parts[-1], r"[+-]\d{4}") # timezone
  8222. def test_var_committer_ident(self):
  8223. """Test getting GIT_COMMITTER_IDENT."""
  8224. # Set up user config
  8225. config = self.repo.get_config()
  8226. config.set((b"user",), b"name", b"Test Committer")
  8227. config.set((b"user",), b"email", b"committer@example.com")
  8228. config.write_to_path()
  8229. result = porcelain.var(self.repo_path, variable="GIT_COMMITTER_IDENT")
  8230. self.assertIn("Test Committer <committer@example.com>", result)
  8231. # Check that timestamp and timezone are included
  8232. parts = result.split()
  8233. self.assertGreaterEqual(
  8234. len(parts), 4
  8235. ) # At least name, <email>, timestamp, timezone
  8236. # Check last two parts are timestamp and timezone
  8237. self.assertTrue(parts[-2].isdigit()) # timestamp
  8238. self.assertRegex(parts[-1], r"[+-]\d{4}") # timezone
  8239. def test_var_editor(self):
  8240. """Test getting GIT_EDITOR."""
  8241. # Test with environment variable
  8242. self.overrideEnv("GIT_EDITOR", "vim")
  8243. result = porcelain.var(self.repo_path, variable="GIT_EDITOR")
  8244. self.assertEqual(result, "vim")
  8245. def test_var_editor_from_config(self):
  8246. """Test getting GIT_EDITOR from config."""
  8247. # Set up editor in config
  8248. config = self.repo.get_config()
  8249. config.set((b"core",), b"editor", b"emacs")
  8250. config.write_to_path()
  8251. # Make sure env var is not set
  8252. self.overrideEnv("GIT_EDITOR", None)
  8253. result = porcelain.var(self.repo_path, variable="GIT_EDITOR")
  8254. self.assertEqual(result, "emacs")
  8255. def test_var_pager(self):
  8256. """Test getting GIT_PAGER."""
  8257. # Test with environment variable
  8258. self.overrideEnv("GIT_PAGER", "less")
  8259. result = porcelain.var(self.repo_path, variable="GIT_PAGER")
  8260. self.assertEqual(result, "less")
  8261. def test_var_pager_from_config(self):
  8262. """Test getting GIT_PAGER from config."""
  8263. # Set up pager in config
  8264. config = self.repo.get_config()
  8265. config.set((b"core",), b"pager", b"more")
  8266. config.write_to_path()
  8267. # Make sure env var is not set
  8268. self.overrideEnv("GIT_PAGER", None)
  8269. result = porcelain.var(self.repo_path, variable="GIT_PAGER")
  8270. self.assertEqual(result, "more")
  8271. def test_var_default_branch(self):
  8272. """Test getting GIT_DEFAULT_BRANCH."""
  8273. # Set up default branch in config
  8274. config = self.repo.get_config()
  8275. config.set((b"init",), b"defaultBranch", b"main")
  8276. config.write_to_path()
  8277. result = porcelain.var(self.repo_path, variable="GIT_DEFAULT_BRANCH")
  8278. self.assertEqual(result, "main")
  8279. def test_var_default_branch_default(self):
  8280. """Test getting GIT_DEFAULT_BRANCH with default value."""
  8281. result = porcelain.var(self.repo_path, variable="GIT_DEFAULT_BRANCH")
  8282. self.assertEqual(result, "master")
  8283. def test_var_list_all(self):
  8284. """Test listing all logical variables."""
  8285. # Set up some config
  8286. config = self.repo.get_config()
  8287. config.set((b"user",), b"name", b"Test User")
  8288. config.set((b"user",), b"email", b"test@example.com")
  8289. config.write_to_path()
  8290. result = porcelain.var_list(self.repo_path)
  8291. self.assertIsInstance(result, dict)
  8292. # Check that logical variables are present
  8293. self.assertIn("GIT_AUTHOR_IDENT", result)
  8294. self.assertIn("GIT_COMMITTER_IDENT", result)
  8295. self.assertIn("GIT_DEFAULT_BRANCH", result)
  8296. # Config variables should NOT be included (deprecated feature)
  8297. self.assertNotIn("user.name", result)
  8298. self.assertNotIn("user.email", result)
  8299. # Verify only logical variables are present
  8300. for key in result.keys():
  8301. self.assertTrue(key.startswith("GIT_"))
  8302. def test_var_unknown_variable(self):
  8303. """Test requesting an unknown variable."""
  8304. with self.assertRaises(KeyError):
  8305. porcelain.var(self.repo_path, variable="UNKNOWN_VARIABLE")
  8306. class MergeBaseTests(PorcelainTestCase):
  8307. """Tests for merge-base, is_ancestor, and independent_commits."""
  8308. def test_merge_base_linear_history(self):
  8309. """Test merge-base with linear history."""
  8310. # Create linear history: c1 <- c2 <- c3
  8311. _c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8312. self.repo.refs[b"refs/heads/branch1"] = c2.id
  8313. self.repo.refs[b"refs/heads/branch2"] = c3.id
  8314. result = porcelain.merge_base(
  8315. self.repo.path, committishes=["refs/heads/branch1", "refs/heads/branch2"]
  8316. )
  8317. self.assertEqual([c2.id], result)
  8318. def test_merge_base_diverged(self):
  8319. """Test merge-base with diverged branches."""
  8320. # Create diverged history: c1 <- c2a, c1 <- c2b
  8321. c1, c2a, c2b = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1]])
  8322. self.repo.refs[b"refs/heads/branch-a"] = c2a.id
  8323. self.repo.refs[b"refs/heads/branch-b"] = c2b.id
  8324. result = porcelain.merge_base(
  8325. self.repo.path, committishes=["refs/heads/branch-a", "refs/heads/branch-b"]
  8326. )
  8327. self.assertEqual([c1.id], result)
  8328. def test_merge_base_all(self):
  8329. """Test merge-base with --all flag."""
  8330. # Create history with multiple common ancestors
  8331. commits = build_commit_graph(
  8332. self.repo.object_store,
  8333. [[1], [2, 1], [3, 1], [4, 2, 3], [5, 2, 3]],
  8334. )
  8335. _c1, c2, c3, c4, c5 = commits
  8336. self.repo.refs[b"refs/heads/branch1"] = c4.id
  8337. self.repo.refs[b"refs/heads/branch2"] = c5.id
  8338. # Without --all, should return only first result
  8339. result = porcelain.merge_base(
  8340. self.repo.path,
  8341. committishes=["refs/heads/branch1", "refs/heads/branch2"],
  8342. all=False,
  8343. )
  8344. self.assertEqual(1, len(result))
  8345. # With --all, should return all merge bases
  8346. result_all = porcelain.merge_base(
  8347. self.repo.path,
  8348. committishes=["refs/heads/branch1", "refs/heads/branch2"],
  8349. all=True,
  8350. )
  8351. self.assertEqual(2, len(result_all))
  8352. self.assertIn(c2.id, result_all)
  8353. self.assertIn(c3.id, result_all)
  8354. def test_merge_base_octopus(self):
  8355. """Test merge-base with --octopus flag."""
  8356. # Create three-way diverged history
  8357. commits = build_commit_graph(
  8358. self.repo.object_store, [[1], [2, 1], [3, 1], [4, 1]]
  8359. )
  8360. c1, c2, c3, c4 = commits
  8361. self.repo.refs[b"refs/heads/a"] = c2.id
  8362. self.repo.refs[b"refs/heads/b"] = c3.id
  8363. self.repo.refs[b"refs/heads/c"] = c4.id
  8364. result = porcelain.merge_base(
  8365. self.repo.path,
  8366. committishes=["refs/heads/a", "refs/heads/b", "refs/heads/c"],
  8367. octopus=True,
  8368. )
  8369. self.assertEqual([c1.id], result)
  8370. def test_merge_base_requires_two_commits(self):
  8371. """Test merge-base requires at least two commits."""
  8372. with self.assertRaises(ValueError):
  8373. porcelain.merge_base(self.repo.path, committishes=["HEAD"])
  8374. def test_is_ancestor_true(self):
  8375. """Test is_ancestor returns True when commit is an ancestor."""
  8376. # Create linear history: c1 <- c2 <- c3
  8377. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8378. self.repo.refs[b"refs/heads/main"] = c3.id
  8379. # c1 is ancestor of c3
  8380. result = porcelain.is_ancestor(
  8381. self.repo.path, ancestor=c1.id.decode(), descendant=c3.id.decode()
  8382. )
  8383. self.assertTrue(result)
  8384. # c2 is ancestor of c3
  8385. result = porcelain.is_ancestor(
  8386. self.repo.path, ancestor=c2.id.decode(), descendant=c3.id.decode()
  8387. )
  8388. self.assertTrue(result)
  8389. def test_is_ancestor_false(self):
  8390. """Test is_ancestor returns False when commit is not an ancestor."""
  8391. # Create diverged history: c1 <- c2a, c1 <- c2b
  8392. _c1, c2a, c2b = build_commit_graph(
  8393. self.repo.object_store, [[1], [2, 1], [3, 1]]
  8394. )
  8395. # c2a is not ancestor of c2b
  8396. result = porcelain.is_ancestor(
  8397. self.repo.path, ancestor=c2a.id.decode(), descendant=c2b.id.decode()
  8398. )
  8399. self.assertFalse(result)
  8400. # c2b is not ancestor of c2a
  8401. result = porcelain.is_ancestor(
  8402. self.repo.path, ancestor=c2b.id.decode(), descendant=c2a.id.decode()
  8403. )
  8404. self.assertFalse(result)
  8405. def test_is_ancestor_requires_both(self):
  8406. """Test is_ancestor requires both ancestor and descendant."""
  8407. with self.assertRaises(ValueError):
  8408. porcelain.is_ancestor(self.repo.path, ancestor="HEAD", descendant=None)
  8409. with self.assertRaises(ValueError):
  8410. porcelain.is_ancestor(self.repo.path, ancestor=None, descendant="HEAD")
  8411. def test_independent_commits_linear(self):
  8412. """Test independent_commits with linear history."""
  8413. # Create linear history: c1 <- c2 <- c3
  8414. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8415. # Only c3 is independent (c1 and c2 are ancestors)
  8416. result = porcelain.independent_commits(
  8417. self.repo.path,
  8418. committishes=[c1.id.decode(), c2.id.decode(), c3.id.decode()],
  8419. )
  8420. self.assertEqual([c3.id], result)
  8421. def test_independent_commits_diverged(self):
  8422. """Test independent_commits with diverged branches."""
  8423. # Create diverged history: c1 <- c2a, c1 <- c2b
  8424. _c1, c2a, c2b = build_commit_graph(
  8425. self.repo.object_store, [[1], [2, 1], [3, 1]]
  8426. )
  8427. # c2a and c2b are both independent (neither is ancestor of the other)
  8428. result = porcelain.independent_commits(
  8429. self.repo.path, committishes=[c2a.id.decode(), c2b.id.decode()]
  8430. )
  8431. self.assertEqual(2, len(result))
  8432. self.assertIn(c2a.id, result)
  8433. self.assertIn(c2b.id, result)
  8434. def test_independent_commits_mixed(self):
  8435. """Test independent_commits with mixed history."""
  8436. # Create mixed history
  8437. commits = build_commit_graph(
  8438. self.repo.object_store, [[1], [2, 1], [3, 1], [4, 2]]
  8439. )
  8440. _c1, c2, c3, c4 = commits
  8441. # c4 and c3 are independent; c2 is ancestor of c4
  8442. result = porcelain.independent_commits(
  8443. self.repo.path,
  8444. committishes=[c2.id.decode(), c3.id.decode(), c4.id.decode()],
  8445. )
  8446. self.assertEqual(2, len(result))
  8447. self.assertIn(c3.id, result)
  8448. self.assertIn(c4.id, result)
  8449. self.assertNotIn(c2.id, result)
  8450. def test_independent_commits_empty(self):
  8451. """Test independent_commits with empty list."""
  8452. result = porcelain.independent_commits(self.repo.path, committishes=[])
  8453. self.assertEqual([], result)
  8454. class CherryTests(PorcelainTestCase):
  8455. """Tests for cherry command."""
  8456. def test_cherry_no_changes(self):
  8457. """Test cherry when head and upstream are the same."""
  8458. # Create a simple commit
  8459. commit_sha = self.repo.do_commit(
  8460. b"Initial commit", committer=b"Test <test@example.com>"
  8461. )
  8462. # Cherry should return empty when comparing a commit to itself
  8463. results = porcelain.cherry(
  8464. self.repo.path, upstream=commit_sha.decode(), head=commit_sha.decode()
  8465. )
  8466. self.assertEqual([], results)
  8467. def test_cherry_unique_commits(self):
  8468. """Test cherry with commits unique to head."""
  8469. # Create initial commit
  8470. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  8471. f.write("base content\n")
  8472. self.repo.stage(["file1.txt"])
  8473. base_commit = self.repo.do_commit(
  8474. b"Base commit", committer=b"Test <test@example.com>"
  8475. )
  8476. # Create a new commit on head
  8477. with open(os.path.join(self.repo_path, "file2.txt"), "w") as f:
  8478. f.write("new content\n")
  8479. self.repo.stage(["file2.txt"])
  8480. head_commit = self.repo.do_commit(
  8481. b"New commit", committer=b"Test <test@example.com>"
  8482. )
  8483. # Cherry should show the new commit as unique
  8484. results = porcelain.cherry(
  8485. self.repo.path, upstream=base_commit.decode(), head=head_commit.decode()
  8486. )
  8487. self.assertEqual(1, len(results))
  8488. status, commit_sha, message = results[0]
  8489. self.assertEqual("+", status)
  8490. self.assertEqual(head_commit, commit_sha)
  8491. self.assertIsNone(message)
  8492. def test_cherry_verbose(self):
  8493. """Test cherry with verbose flag."""
  8494. # Create initial commit
  8495. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  8496. f.write("base content\n")
  8497. self.repo.stage(["file1.txt"])
  8498. base_commit = self.repo.do_commit(
  8499. b"Base commit", committer=b"Test <test@example.com>"
  8500. )
  8501. # Create a new commit on head
  8502. with open(os.path.join(self.repo_path, "file2.txt"), "w") as f:
  8503. f.write("new content\n")
  8504. self.repo.stage(["file2.txt"])
  8505. head_commit = self.repo.do_commit(
  8506. b"New commit on head", committer=b"Test <test@example.com>"
  8507. )
  8508. # Cherry with verbose should include commit message
  8509. results = porcelain.cherry(
  8510. self.repo.path,
  8511. upstream=base_commit.decode(),
  8512. head=head_commit.decode(),
  8513. verbose=True,
  8514. )
  8515. self.assertEqual(1, len(results))
  8516. status, commit_sha, message = results[0]
  8517. self.assertEqual("+", status)
  8518. self.assertEqual(head_commit, commit_sha)
  8519. self.assertEqual(b"New commit on head", message)
  8520. def test_cherry_equivalent_patches(self):
  8521. """Test cherry with equivalent patches (cherry-picked commits)."""
  8522. # Create base commit
  8523. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  8524. f.write("line1\n")
  8525. self.repo.stage(["file.txt"])
  8526. base_commit = self.repo.do_commit(
  8527. b"Base commit", committer=b"Test <test@example.com>"
  8528. )
  8529. # Create upstream branch with a change
  8530. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  8531. f.write("line1\nline2\n")
  8532. self.repo.stage(["file.txt"])
  8533. upstream_commit = self.repo.do_commit(
  8534. b"Add line2", committer=b"Test <test@example.com>"
  8535. )
  8536. # Reset to base and create same change on head branch
  8537. self.repo.refs[b"HEAD"] = base_commit
  8538. self.repo.reset_index()
  8539. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  8540. f.write("line1\nline2\n")
  8541. self.repo.stage(["file.txt"])
  8542. head_commit = self.repo.do_commit(
  8543. b"Add line2 (different metadata)",
  8544. committer=b"Different <different@example.com>",
  8545. )
  8546. # Cherry should mark this as equivalent (-)
  8547. results = porcelain.cherry(
  8548. self.repo.path,
  8549. upstream=upstream_commit.decode(),
  8550. head=head_commit.decode(),
  8551. )
  8552. self.assertEqual(1, len(results))
  8553. status, commit_sha, _message = results[0]
  8554. self.assertEqual("-", status)
  8555. self.assertEqual(head_commit, commit_sha)
  8556. class GrepTests(PorcelainTestCase):
  8557. def test_basic_grep(self) -> None:
  8558. """Test basic pattern matching in files."""
  8559. # Create some test files
  8560. with open(os.path.join(self.repo_path, "foo.txt"), "w") as f:
  8561. f.write("hello world\ngoodbye world\n")
  8562. with open(os.path.join(self.repo_path, "bar.txt"), "w") as f:
  8563. f.write("foo bar\nbaz qux\n")
  8564. porcelain.add(self.repo, paths=["foo.txt", "bar.txt"])
  8565. porcelain.commit(self.repo, message=b"Add test files")
  8566. # Search for "world"
  8567. outstream = StringIO()
  8568. porcelain.grep(self.repo, "world", outstream=outstream)
  8569. output = outstream.getvalue().replace("\r\n", "\n")
  8570. self.assertEqual("foo.txt:hello world\nfoo.txt:goodbye world\n", output)
  8571. def test_grep_with_line_numbers(self) -> None:
  8572. """Test grep with line numbers."""
  8573. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8574. f.write("line one\nline two\nline three\n")
  8575. porcelain.add(self.repo, paths=["test.txt"])
  8576. porcelain.commit(self.repo, message=b"Add test file")
  8577. outstream = StringIO()
  8578. porcelain.grep(self.repo, "line", outstream=outstream, line_number=True)
  8579. output = outstream.getvalue().replace("\r\n", "\n")
  8580. self.assertEqual(
  8581. "test.txt:1:line one\ntest.txt:2:line two\ntest.txt:3:line three\n",
  8582. output,
  8583. )
  8584. def test_grep_case_insensitive(self) -> None:
  8585. """Test case-insensitive grep."""
  8586. with open(os.path.join(self.repo_path, "case.txt"), "w") as f:
  8587. f.write("Hello WORLD\nGoodbye world\n")
  8588. porcelain.add(self.repo, paths=["case.txt"])
  8589. porcelain.commit(self.repo, message=b"Add case file")
  8590. outstream = StringIO()
  8591. porcelain.grep(self.repo, "HELLO", outstream=outstream, ignore_case=True)
  8592. output = outstream.getvalue().replace("\r\n", "\n")
  8593. self.assertEqual("case.txt:Hello WORLD\n", output)
  8594. def test_grep_with_pathspec(self) -> None:
  8595. """Test grep with pathspec filtering."""
  8596. os.makedirs(os.path.join(self.repo_path, "subdir"))
  8597. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  8598. f.write("pattern match\n")
  8599. with open(os.path.join(self.repo_path, "subdir", "file2.txt"), "w") as f:
  8600. f.write("pattern match\n")
  8601. porcelain.add(self.repo, paths=["file1.txt", "subdir/file2.txt"])
  8602. porcelain.commit(self.repo, message=b"Add files")
  8603. # Search only in subdir
  8604. outstream = StringIO()
  8605. porcelain.grep(self.repo, "pattern", outstream=outstream, pathspecs=["subdir/"])
  8606. output = outstream.getvalue().replace("\r\n", "\n")
  8607. self.assertEqual("subdir/file2.txt:pattern match\n", output)
  8608. def test_grep_no_matches(self) -> None:
  8609. """Test grep with no matches."""
  8610. with open(os.path.join(self.repo_path, "empty.txt"), "w") as f:
  8611. f.write("nothing to see here\n")
  8612. porcelain.add(self.repo, paths=["empty.txt"])
  8613. porcelain.commit(self.repo, message=b"Add empty file")
  8614. outstream = StringIO()
  8615. porcelain.grep(self.repo, "nonexistent", outstream=outstream)
  8616. output = outstream.getvalue()
  8617. self.assertEqual("", output)
  8618. def test_grep_regex_pattern(self) -> None:
  8619. """Test grep with regex patterns."""
  8620. with open(os.path.join(self.repo_path, "regex.txt"), "w") as f:
  8621. f.write("test123\ntest456\nnotest\n")
  8622. porcelain.add(self.repo, paths=["regex.txt"])
  8623. porcelain.commit(self.repo, message=b"Add regex file")
  8624. # Search for "test" followed by digits
  8625. outstream = StringIO()
  8626. porcelain.grep(self.repo, r"test\d+", outstream=outstream)
  8627. output = outstream.getvalue().replace("\r\n", "\n")
  8628. self.assertEqual("regex.txt:test123\nregex.txt:test456\n", output)
  8629. def test_grep_invalid_pattern(self) -> None:
  8630. """Test grep with invalid regex pattern."""
  8631. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8632. f.write("test\n")
  8633. porcelain.add(self.repo, paths=["test.txt"])
  8634. porcelain.commit(self.repo, message=b"Add test file")
  8635. outstream = StringIO()
  8636. with self.assertRaises(ValueError):
  8637. porcelain.grep(self.repo, "[invalid", outstream=outstream)
  8638. def test_grep_no_head(self) -> None:
  8639. """Test grep fails when there's no HEAD commit."""
  8640. # Create a fresh repo with no commits
  8641. empty_repo_path = os.path.join(self.test_dir, "empty_repo")
  8642. empty_repo = Repo.init(empty_repo_path, mkdir=True)
  8643. self.addCleanup(empty_repo.close)
  8644. outstream = StringIO()
  8645. with self.assertRaises(ValueError):
  8646. porcelain.grep(empty_repo, "pattern", outstream=outstream)