test_porcelain.py 409 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186
  1. # test_porcelain.py -- porcelain tests
  2. # Copyright (C) 2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Tests for dulwich.porcelain."""
  22. import contextlib
  23. import os
  24. import platform
  25. import re
  26. import shutil
  27. import stat
  28. import subprocess
  29. import sys
  30. import tarfile
  31. import tempfile
  32. import threading
  33. import time
  34. from io import BytesIO, StringIO
  35. from unittest import skipIf
  36. from dulwich import porcelain
  37. from dulwich.client import SendPackResult
  38. from dulwich.diff_tree import tree_changes
  39. from dulwich.errors import CommitError
  40. from dulwich.object_store import DEFAULT_TEMPFILE_GRACE_PERIOD
  41. from dulwich.objects import ZERO_SHA, Blob, Commit, Tag, Tree
  42. from dulwich.porcelain import (
  43. CheckoutError, # Hypothetical or real error class
  44. CountObjectsResult,
  45. add,
  46. commit,
  47. )
  48. from dulwich.repo import NoIndexPresent, Repo
  49. from dulwich.server import DictBackend
  50. from dulwich.tests.utils import build_commit_graph, make_commit, make_object
  51. from dulwich.web import make_server, make_wsgi_chain
  52. from . import TestCase
  53. try:
  54. import gpg
  55. except ImportError:
  56. gpg = None
  57. def flat_walk_dir(dir_to_walk):
  58. for dirpath, _, filenames in os.walk(dir_to_walk):
  59. rel_dirpath = os.path.relpath(dirpath, dir_to_walk)
  60. if not dirpath == dir_to_walk:
  61. yield rel_dirpath
  62. for filename in filenames:
  63. if dirpath == dir_to_walk:
  64. yield filename
  65. else:
  66. yield os.path.join(rel_dirpath, filename)
  67. class PorcelainTestCase(TestCase):
  68. def setUp(self) -> None:
  69. super().setUp()
  70. # Disable pagers for tests
  71. self.overrideEnv("PAGER", "false")
  72. self.overrideEnv("GIT_PAGER", "false")
  73. self.overrideEnv("DULWICH_PAGER", "false")
  74. self.test_dir = tempfile.mkdtemp()
  75. self.addCleanup(shutil.rmtree, self.test_dir)
  76. self.repo_path = os.path.join(self.test_dir, "repo")
  77. self.repo = Repo.init(self.repo_path, mkdir=True)
  78. self.addCleanup(self.repo.close)
  79. def assertRecentTimestamp(self, ts) -> None:
  80. # On some slow CIs it does actually take more than 5 seconds to go from
  81. # creating the tag to here.
  82. self.assertLess(time.time() - ts, 50)
  83. @skipIf(gpg is None, "gpg is not available")
  84. class PorcelainGpgTestCase(PorcelainTestCase):
  85. DEFAULT_KEY = """
  86. -----BEGIN PGP PRIVATE KEY BLOCK-----
  87. lQVYBGBjIyIBDADAwydvMPQqeEiK54FG1DHwT5sQejAaJOb+PsOhVa4fLcKsrO3F
  88. g5CxO+/9BHCXAr8xQAtp/gOhDN05fyK3MFyGlL9s+Cd8xf34S3R4rN/qbF0oZmaa
  89. FW0MuGnniq54HINs8KshadVn1Dhi/GYSJ588qNFRl/qxFTYAk+zaGsgX/QgFfy0f
  90. djWXJLypZXu9D6DlyJ0cPSzUlfBkI2Ytx6grzIquRjY0FbkjK3l+iGsQ+ebRMdcP
  91. Sqd5iTN9XuzIUVoBFAZBRjibKV3N2wxlnCbfLlzCyDp7rktzSThzjJ2pVDuLrMAx
  92. 6/L9hIhwmFwdtY4FBFGvMR0b0Ugh3kCsRWr8sgj9I7dUoLHid6ObYhJFhnD3GzRc
  93. U+xX1uy3iTCqJDsG334aQIhC5Giuxln4SUZna2MNbq65ksh38N1aM/t3+Dc/TKVB
  94. rb5KWicRPCQ4DIQkHMDCSPyj+dvRLCPzIaPvHD7IrCfHYHOWuvvPGCpwjo0As3iP
  95. IecoMeguPLVaqgcAEQEAAQAL/i5/pQaUd4G7LDydpbixPS6r9UrfPrU/y5zvBP/p
  96. DCynPDutJ1oq539pZvXQ2VwEJJy7x0UVKkjyMndJLNWly9wHC7o8jkHx/NalVP47
  97. LXR+GWbCdOOcYYbdAWcCNB3zOtzPnWhdAEagkc2G9xRQDIB0dLHLCIUpCbLP/CWM
  98. qlHnDsVMrVTWjgzcpsnyGgw8NeLYJtYGB8dsN+XgCCjo7a9LEvUBKNgdmWBbf14/
  99. iBw7PCugazFcH9QYfZwzhsi3nqRRagTXHbxFRG0LD9Ro9qCEutHYGP2PJ59Nj8+M
  100. zaVkJj/OxWxVOGvn2q16mQBCjKpbWfqXZVVl+G5DGOmiSTZqXy+3j6JCKdOMy6Qd
  101. JBHOHhFZXYmWYaaPzoc33T/C3QhMfY5sOtUDLJmV05Wi4dyBeNBEslYgUuTk/jXb
  102. 5ZAie25eDdrsoqkcnSs2ZguMF7AXhe6il2zVhUUMs/6UZgd6I7I4Is0HXT/pnxEp
  103. uiTRFu4v8E+u+5a8O3pffe5boQYA3TsIxceen20qY+kRaTOkURHMZLn/y6KLW8bZ
  104. rNJyXWS9hBAcbbSGhfOwYfzbDCM17yPQO3E2zo8lcGdRklUdIIaCxQwtu36N5dfx
  105. OLCCQc5LmYdl/EAm91iAhrr7dNntZ18MU09gdzUu+ONZwu4CP3cJT83+qYZULso8
  106. 4Fvd/X8IEfGZ7kM+ylrdqBwtlrn8yYXtom+ows2M2UuNR53B+BUOd73kVLTkTCjE
  107. JH63+nE8BqG7tDLCMws+23SAA3xxBgDfDrr0x7zCozQKVQEqBzQr9Uoo/c/ZjAfi
  108. syzNSrDz+g5gqJYtuL9XpPJVWf6V1GXVyJlSbxR9CjTkBxmlPxpvV25IsbVSsh0o
  109. aqkf2eWpbCL6Qb2E0jd1rvf8sGeTTohzYfiSVVsC2t9ngRO/CmetizwQBvRzLGMZ
  110. 4mtAPiy7ZEDc2dFrPp7zlKISYmJZUx/DJVuZWuOrVMpBP+bSgJXoMTlICxZUqUnE
  111. 2VKVStb/L+Tl8XCwIWdrZb9BaDnHqfcGAM2B4HNPxP88Yj1tEDly/vqeb3vVMhj+
  112. S1lunnLdgxp46YyuTMYAzj88eCGurRtzBsdxxlGAsioEnZGebEqAHQbieKq/DO6I
  113. MOMZHMSVBDqyyIx3assGlxSX8BSFW0lhKyT7i0XqnAgCJ9f/5oq0SbFGq+01VQb7
  114. jIx9PbcYJORxsE0JG/CXXPv27bRtQXsudkWGSYvC0NLOgk4z8+kQpQtyFh16lujq
  115. WRwMeriu0qNDjCa1/eHIKDovhAZ3GyO5/9m1tBlUZXN0IFVzZXIgPHRlc3RAdGVz
  116. dC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAFiEEjrR8
  117. MQ4fJK44PYMvfN2AClLmXiYFAmDcEZEACgkQfN2AClLmXibZzgv/ZfeTpTuqQE1W
  118. C1jT5KpQExnt0BizTX0U7BvSn8Fr6VXTyol6kYc3u71GLUuJyawCLtIzOXqOXJvz
  119. bjcZqymcMADuftKcfMy513FhbF6MhdVd6QoeBP6+7/xXOFJCi+QVYF7SQ2h7K1Qm
  120. +yXOiAMgSxhCZQGPBNJLlDUOd47nSIMANvlumFtmLY/1FD7RpG7WQWjeX1mnxNTw
  121. hUU+Yv7GuFc/JprXCIYqHbhWfvXyVtae2ZK4xuVi5eqwA2RfggOVM7drb+CgPhG0
  122. +9aEDDLOZqVi65wK7J73Puo3rFTbPQMljxw5s27rWqF+vB6hhVdJOPNomWy3naPi
  123. k5MW0mhsacASz1WYndpZz+XaQTq/wJF5HUyyeUWJ0vlOEdwx021PHcqSTyfNnkjD
  124. KncrE21t2sxWRsgGDETxIwkd2b2HNGAvveUD0ffFK/oJHGSXjAERFGc3wuiDj3mQ
  125. BvKm4wt4QF9ZMrCdhMAA6ax5kfEUqQR4ntmrJk/khp/mV7TILaI4nQVYBGBjIyIB
  126. DADghIo9wXnRxzfdDTvwnP8dHpLAIaPokgdpyLswqUCixJWiW2xcV6weUjEWwH6n
  127. eN/t1uZYVehbrotxVPla+MPvzhxp6/cmG+2lhzEBOp6zRwnL1wIB6HoKJfpREhyM
  128. c8rLR0zMso1L1bJTyydvnu07a7BWo3VWKjilb0rEZZUSD/2hidx5HxMOJSoidLWe
  129. d/PPuv6yht3NtA4UThlcfldm9G6PbqCdm1kMEKAkq0wVJvhPJ6gEFRNJimgygfUw
  130. MDFXEIhQtxjgdV5Uoz3O5452VLoRsDlgpi3E0WDGj7WXDaO5uSU0T5aJgVgHCP/f
  131. xZhHuQFk2YYIl5nCBpOZyWWI0IKmscTuEwzpkhICQDQFvcMZ5ibsl7wA2P7YTrQf
  132. FDMjjzuaK80GYPfxDFlyKUyLqFt8w/QzsZLDLX7+jxIEpbRAaMw/JsWqm5BMxxbS
  133. 3CIQiS5S3oSKDsNINelqWFfwvLhvlQra8gIxyNTlek25OdgG66BiiX+seH8A/ql+
  134. F+MAEQEAAQAL/1jrNSLjMt9pwo6qFKClVQZP2vf7+sH7v7LeHIDXr3EnYUnVYnOq
  135. B1FU5PspTp/+J9W25DB9CZLx7Gj8qeslFdiuLSOoIBB4RCToB3kAoeTH0DHqW/Gs
  136. hFTrmJkuDp9zpo/ek6SIXJx5rHAyR9KVw0fizQprH2f6PcgLbTWeM61dJuqowmg3
  137. 7eCOyIKv7VQvFqEhYokLD+JNmrvg+Htg0DXGvdjRjAwPf/NezEXpj67a6cHTp1/C
  138. hwp7pevG+3fTxaCJFesl5/TxxtnaBLE8m2uo/S6Hxgn9l0edonroe1QlTjEqGLy2
  139. 7qi2z5Rem+v6GWNDRgvAWur13v8FNdyduHlioG/NgRsU9mE2MYeFsfi3cfNpJQp/
  140. wC9PSCIXrb/45mkS8KyjZpCrIPB9RV/m0MREq01TPom7rstZc4A1pD0Ot7AtUYS3
  141. e95zLyEmeLziPJ9fV4fgPmEudDr1uItnmV0LOskKlpg5sc0hhdrwYoobfkKt2dx6
  142. DqfMlcM1ZkUbLQYA4jwfpFJG4HmYvjL2xCJxM0ycjvMbqFN+4UjgYWVlRfOrm1V4
  143. Op86FjbRbV6OOCNhznotAg7mul4xtzrrTkK8o3YLBeJseDgl4AWuzXtNa9hE0XpK
  144. 9gJoEHUuBOOsamVh2HpXESFyE5CclOV7JSh541TlZKfnqfZYCg4JSbp0UijkawCL
  145. 5bJJUiGGMD9rZUxIAKQO1DvUEzptS7Jl6S3y5sbIIhilp4KfYWbSk3PPu9CnZD5b
  146. LhEQp0elxnb/IL8PBgD+DpTeC8unkGKXUpbe9x0ISI6V1D6FmJq/FxNg7fMa3QCh
  147. fGiAyoTm80ZETynj+blRaDO3gY4lTLa3Opubof1EqK2QmwXmpyvXEZNYcQfQ2CCS
  148. GOWUCK8jEQamUPf1PWndZXJUmROI1WukhlL71V/ir6zQeVCv1wcwPwclJPnAe87u
  149. pEklnCYpvsEldwHUX9u0BWzoULIEsi+ddtHmT0KTeF/DHRy0W15jIHbjFqhqckj1
  150. /6fmr7l7kIi/kN4vWe0F/0Q8IXX+cVMgbl3aIuaGcvENLGcoAsAtPGx88SfRgmfu
  151. HK64Y7hx1m+Bo215rxJzZRjqHTBPp0BmCi+JKkaavIBrYRbsx20gveI4dzhLcUhB
  152. kiT4Q7oz0/VbGHS1CEf9KFeS/YOGj57s4yHauSVI0XdP9kBRTWmXvBkzsooB2cKH
  153. hwhUN7iiT1k717CiTNUT6Q/pcPFCyNuMoBBGQTU206JEgIjQvI3f8xMUMGmGVVQz
  154. 9/k716ycnhb2JZ/Q/AyQIeHJiQG2BBgBCAAgAhsMFiEEjrR8MQ4fJK44PYMvfN2A
  155. ClLmXiYFAmDcEa4ACgkQfN2AClLmXiZxxQv/XaMN0hPCygtrQMbCsTNb34JbvJzh
  156. hngPuUAfTbRHrR3YeATyQofNbL0DD3fvfzeFF8qESqvzCSZxS6dYsXPd4MCJTzlp
  157. zYBZ2X0sOrgDqZvqCZKN72RKgdk0KvthdzAxsIm2dfcQOxxowXMxhJEXZmsFpusx
  158. jKJxOcrfVRjXJnh9isY0NpCoqMQ+3k3wDJ3VGEHV7G+A+vFkWfbLJF5huQ96uaH9
  159. Uc+jUsREUH9G82ZBqpoioEN8Ith4VXpYnKdTMonK/+ZcyeraJZhXrvbjnEomKdzU
  160. 0pu4bt1HlLR3dcnpjN7b009MBf2xLgEfQk2nPZ4zzY+tDkxygtPllaB4dldFjBpT
  161. j7Q+t49sWMjmlJUbLlHfuJ7nUUK5+cGjBsWVObAEcyfemHWCTVFnEa2BJslGC08X
  162. rFcjRRcMEr9ct4551QFBHsv3O/Wp3/wqczYgE9itSnGT05w+4vLt4smG+dnEHjRJ
  163. brMb2upTHa+kjktjdO96/BgSnKYqmNmPB/qB
  164. =ivA/
  165. -----END PGP PRIVATE KEY BLOCK-----
  166. """
  167. DEFAULT_KEY_ID = "8EB47C310E1F24AE383D832F7CDD800A52E65E26"
  168. NON_DEFAULT_KEY = """
  169. -----BEGIN PGP PRIVATE KEY BLOCK-----
  170. lQVYBGBjI0ABDADGWBRp+t02emfzUlhrc1psqIhhecFm6Em0Kv33cfDpnfoMF1tK
  171. Yy/4eLYIR7FmpdbFPcDThFNHbXJzBi00L1mp0XQE2l50h/2bDAAgREdZ+NVo5a7/
  172. RSZjauNU1PxW6pnXMehEh1tyIQmV78jAukaakwaicrpIenMiFUN3fAKHnLuFffA6
  173. t0f3LqJvTDhUw/o2vPgw5e6UDQhA1C+KTv1KXVrhJNo88a3hZqCZ76z3drKR411Q
  174. zYgT4DUb8lfnbN+z2wfqT9oM5cegh2k86/mxAA3BYOeQrhmQo/7uhezcgbxtdGZr
  175. YlbuaNDTSBrn10ZoaxLPo2dJe2zWxgD6MpvsGU1w3tcRW508qo/+xoWp2/pDzmok
  176. +uhOh1NAj9zB05VWBz1r7oBgCOIKpkD/LD4VKq59etsZ/UnrYDwKdXWZp7uhshkU
  177. M7N35lUJcR76a852dlMdrgpmY18+BP7+o7M+5ElHTiqQbMuE1nHTg8RgVpdV+tUx
  178. dg6GWY/XHf5asm8AEQEAAQAL/A85epOp+GnymmEQfI3+5D178D//Lwu9n86vECB6
  179. xAHCqQtdjZnXpDp/1YUsL59P8nzgYRk7SoMskQDoQ/cB/XFuDOhEdMSgHaTVlnrj
  180. ktCCq6rqGnUosyolbb64vIfVaSqd/5SnCStpAsnaBoBYrAu4ZmV4xfjDQWwn0q5s
  181. u+r56mD0SkjPgbwk/b3qTVagVmf2OFzUgWwm1e/X+bA1oPag1NV8VS4hZPXswT4f
  182. qhiyqUFOgP6vUBcqehkjkIDIl/54xII7/P5tp3LIZawvIXqHKNTqYPCqaCqCj+SL
  183. vMYDIb6acjescfZoM71eAeHAANeFZzr/rwfBT+dEP6qKmPXNcvgE11X44ZCr04nT
  184. zOV/uDUifEvKT5qgtyJpSFEVr7EXubJPKoNNhoYqq9z1pYU7IedX5BloiVXKOKTY
  185. 0pk7JkLqf3g5fYtXh/wol1owemITJy5V5PgaqZvk491LkI6S+kWC7ANYUg+TDPIW
  186. afxW3E5N1CYV6XDAl0ZihbLcoQYAy0Ky/p/wayWKePyuPBLwx9O89GSONK2pQljZ
  187. yaAgxPQ5/i1vx6LIMg7k/722bXR9W3zOjWOin4eatPM3d2hkG96HFvnBqXSmXOPV
  188. 03Xqy1/B5Tj8E9naLKUHE/OBQEc363DgLLG9db5HfPlpAngeppYPdyWkhzXyzkgS
  189. PylaE5eW3zkdjEbYJ6RBTecTZEgBaMvJNPdWbn//frpP7kGvyiCg5Es+WjLInUZ6
  190. 0sdifcNTCewzLXK80v/y5mVOdJhPBgD5zs9cYdyiQJayqAuOr+He1eMHMVUbm9as
  191. qBmPrst398eBW9ZYF7eBfTSlUf6B+WnvyLKEGsUf/7IK0EWDlzoBuWzWiHjUAY1g
  192. m9eTV2MnvCCCefqCErWwfFo2nWOasAZA9sKD+ICIBY4tbtvSl4yfLBzTMwSvs9ZS
  193. K1ocPSYUnhm2miSWZ8RLZPH7roHQasNHpyq/AX7DahFf2S/bJ+46ZGZ8Pigr7hA+
  194. MjmpQ4qVdb5SaViPmZhAKO+PjuCHm+EF/2H0Y3Sl4eXgxZWoQVOUeXdWg9eMfYrj
  195. XDtUMIFppV/QxbeztZKvJdfk64vt/crvLsOp0hOky9cKwY89r4QaHfexU3qR+qDq
  196. UlMvR1rHk7dS5HZAtw0xKsFJNkuDxvBkMqv8Los8zp3nUl+U99dfZOArzNkW38wx
  197. FPa0ixkC9za2BkDrWEA8vTnxw0A2upIFegDUhwOByrSyfPPnG3tKGeqt3Izb/kDk
  198. Q9vmo+HgxBOguMIvlzbBfQZwtbd/gXzlvPqCtCJBbm90aGVyIFRlc3QgVXNlciA8
  199. dGVzdDJAdGVzdC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4B
  200. AheAFiEEapM5P1DF5qzT1vtFuTYhLttOFMAFAmDcEeEACgkQuTYhLttOFMDe0Qv/
  201. Qx/bzXztJ3BCc+CYAVDx7Kr37S68etwwLgcWzhG+CDeMB5F/QE+upKgxy2iaqQFR
  202. mxfOMgf/TIQkUfkbaASzK1LpnesYO85pk7XYjoN1bYEHiXTkeW+bgB6aJIxrRmO2
  203. SrWasdBC/DsI3Mrya8YMt/TiHC6VpRJVxCe5vv7/kZC4CXrgTBnZocXx/YXimbke
  204. poPMVdbvhYh6N0aGeS38jRKgyN10KXmhDTAQDwseVFavBWAjVfx3DEwjtK2Z2GbA
  205. aL8JvAwRtqiPFkDMIKPL4UwxtXFws8SpMt6juroUkNyf6+BxNWYqmwXHPy8zCJAb
  206. xkxIJMlEc+s7qQsP3fILOo8Xn+dVzJ5sa5AoARoXm1GMjsdqaKAzq99Dic/dHnaQ
  207. Civev1PQsdwlYW2C2wNXNeIrxMndbDMFfNuZ6BnGHWJ/wjcp/pFs4YkyyZN8JH7L
  208. hP2FO4Jgham3AuP13kC3Ivea7V6hR8QNcDZRwFPOMIX4tXwQv1T72+7DZGaA25O7
  209. nQVXBGBjI0ABDADJMBYIcG0Yil9YxFs7aYzNbd7alUAr89VbY8eIGPHP3INFPM1w
  210. lBQCu+4j6xdEbhMpppLBZ9A5TEylP4C6qLtPa+oLtPeuSw8gHDE10XE4lbgPs376
  211. rL60XdImSOHhiduACUefYjqpcmFH9Bim1CC+koArYrSQJQx1Jri+OpnTaL/8UID0
  212. KzD/kEgMVGlHIVj9oJmb4+j9pW8I/g0wDSnIaEKFMxqu6SIVJ1GWj+MUMvZigjLC
  213. sNCZd7PnbOC5VeU3SsXj6he74Jx0AmGMPWIHi9M0DjHO5d1cCbXTnud8xxM1bOh4
  214. 7aCTnMK5cVyIr+adihgJpVVhrndSM8aklBPRgtozrGNCgF2CkYU2P1blxfloNr/8
  215. UZpM83o+s1aObBszzRNLxnpNORqoLqjfPtLEPQnagxE+4EapCq0NZ/x6yO5VTwwp
  216. NljdFAEk40uGuKyn1QA3uNMHy5DlpLl+tU7t1KEovdZ+OVYsYKZhVzw0MTpKogk9
  217. JI7AN0q62ronPskAEQEAAQAL+O8BUSt1ZCVjPSIXIsrR+ZOSkszZwgJ1CWIoh0IH
  218. YD2vmcMHGIhFYgBdgerpvhptKhaw7GcXDScEnYkyh5s4GE2hxclik1tbj/x1gYCN
  219. 8BNoyeDdPFxQG73qN12D99QYEctpOsz9xPLIDwmL0j1ehAfhwqHIAPm9Ca+i8JYM
  220. x/F+35S/jnKDXRI+NVlwbiEyXKXxxIqNlpy9i8sDBGexO5H5Sg0zSN/B1duLekGD
  221. biDw6gLc6bCgnS+0JOUpU07Z2fccMOY9ncjKGD2uIb/ePPUaek92GCQyq0eorCIV
  222. brcQsRc5sSsNtnRKQTQtxioROeDg7kf2oWySeHTswlXW/219ihrSXgteHJd+rPm7
  223. DYLEeGLRny8bRKv8rQdAtApHaJE4dAATXeY4RYo4NlXHYaztGYtU6kiM/3zCfWAe
  224. 9Nn+Wh9jMTZrjefUCagS5r6ZqAh7veNo/vgIGaCLh0a1Ypa0Yk9KFrn3LYEM3zgk
  225. 3m3bn+7qgy5cUYXoJ3DGJJEhBgDPonpW0WElqLs5ZMem1ha85SC38F0IkAaSuzuz
  226. v3eORiKWuyJGF32Q2XHa1RHQs1JtUKd8rxFer3b8Oq71zLz6JtVc9dmRudvgcJYX
  227. 0PC11F6WGjZFSSp39dajFp0A5DKUs39F3w7J1yuDM56TDIN810ywufGAHARY1pZb
  228. UJAy/dTqjFnCbNjpAakor3hVzqxcmUG+7Y2X9c2AGncT1MqAQC3M8JZcuZvkK8A9
  229. cMk8B914ryYE7VsZMdMhyTwHmykGAPgNLLa3RDETeGeGCKWI+ZPOoU0ib5JtJZ1d
  230. P3tNwfZKuZBZXKW9gqYqyBa/qhMip84SP30pr/TvulcdAFC759HK8sQZyJ6Vw24P
  231. c+5ssRxrQUEw1rvJPWhmQCmCOZHBMQl5T6eaTOpR5u3aUKTMlxPKhK9eC1dCSTnI
  232. /nyL8An3VKnLy+K/LI42YGphBVLLJmBewuTVDIJviWRdntiG8dElyEJMOywUltk3
  233. 2CEmqgsD9tPO8rXZjnMrMn3gfsiaoQYA6/6/e2utkHr7gAoWBgrBBdqVHsvqh5Ro
  234. 2DjLAOpZItO/EdCJfDAmbTYOa04535sBDP2tcH/vipPOPpbr1Y9Y/mNsKCulNxed
  235. yqAmEkKOcerLUP5UHju0AB6VBjHJFdU2mqT+UjPyBk7WeKXgFomyoYMv3KpNOFWR
  236. xi0Xji4kKHbttA6Hy3UcGPr9acyUAlDYeKmxbSUYIPhw32bbGrX9+F5YriTufRsG
  237. 3jftQVo9zqdcQSD/5pUTMn3EYbEcohYB2YWJAbYEGAEIACACGwwWIQRqkzk/UMXm
  238. rNPW+0W5NiEu204UwAUCYNwR6wAKCRC5NiEu204UwOPnC/92PgB1c3h9FBXH1maz
  239. g29fndHIHH65VLgqMiQ7HAMojwRlT5Xnj5tdkCBmszRkv5vMvdJRa3ZY8Ed/Inqr
  240. hxBFNzpjqX4oj/RYIQLKXWWfkTKYVLJFZFPCSo00jesw2gieu3Ke/Yy4gwhtNodA
  241. v+s6QNMvffTW/K3XNrWDB0E7/LXbdidzhm+MBu8ov2tuC3tp9liLICiE1jv/2xT4
  242. CNSO6yphmk1/1zEYHS/mN9qJ2csBmte2cdmGyOcuVEHk3pyINNMDOamaURBJGRwF
  243. XB5V7gTKUFU4jCp3chywKrBHJHxGGDUmPBmZtDtfWAOgL32drK7/KUyzZL/WO7Fj
  244. akOI0hRDFOcqTYWL20H7+hAiX3oHMP7eou3L5C7wJ9+JMcACklN/WMjG9a536DFJ
  245. 4UgZ6HyKPP+wy837Hbe8b25kNMBwFgiaLR0lcgzxj7NyQWjVCMOEN+M55tRCjvL6
  246. ya6JVZCRbMXfdCy8lVPgtNQ6VlHaj8Wvnn2FLbWWO2n2r3s=
  247. =9zU5
  248. -----END PGP PRIVATE KEY BLOCK-----
  249. """
  250. NON_DEFAULT_KEY_ID = "6A93393F50C5E6ACD3D6FB45B936212EDB4E14C0"
  251. def setUp(self) -> None:
  252. super().setUp()
  253. self.gpg_dir = os.path.join(self.test_dir, "gpg")
  254. os.mkdir(self.gpg_dir, mode=0o700)
  255. # Ignore errors when deleting GNUPGHOME, because of race conditions
  256. # (e.g. the gpg-agent socket having been deleted). See
  257. # https://github.com/jelmer/dulwich/issues/1000
  258. self.addCleanup(shutil.rmtree, self.gpg_dir, ignore_errors=True)
  259. self.overrideEnv("GNUPGHOME", self.gpg_dir)
  260. def import_default_key(self) -> None:
  261. subprocess.run(
  262. ["gpg", "--import"],
  263. stdout=subprocess.DEVNULL,
  264. stderr=subprocess.DEVNULL,
  265. input=PorcelainGpgTestCase.DEFAULT_KEY,
  266. text=True,
  267. )
  268. def import_non_default_key(self) -> None:
  269. subprocess.run(
  270. ["gpg", "--import"],
  271. stdout=subprocess.DEVNULL,
  272. stderr=subprocess.DEVNULL,
  273. input=PorcelainGpgTestCase.NON_DEFAULT_KEY,
  274. text=True,
  275. )
  276. class ArchiveTests(PorcelainTestCase):
  277. """Tests for the archive command."""
  278. def test_simple(self) -> None:
  279. _c1, _c2, c3 = build_commit_graph(
  280. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  281. )
  282. self.repo.refs[b"refs/heads/master"] = c3.id
  283. out = BytesIO()
  284. err = BytesIO()
  285. porcelain.archive(
  286. self.repo.path, b"refs/heads/master", outstream=out, errstream=err
  287. )
  288. self.assertEqual(b"", err.getvalue())
  289. tf = tarfile.TarFile(fileobj=out)
  290. self.addCleanup(tf.close)
  291. self.assertEqual([], tf.getnames())
  292. class UpdateServerInfoTests(PorcelainTestCase):
  293. def test_simple(self) -> None:
  294. _c1, _c2, c3 = build_commit_graph(
  295. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  296. )
  297. self.repo.refs[b"refs/heads/foo"] = c3.id
  298. porcelain.update_server_info(self.repo.path)
  299. self.assertTrue(
  300. os.path.exists(os.path.join(self.repo.controldir(), "info", "refs"))
  301. )
  302. class CommitTests(PorcelainTestCase):
  303. def test_custom_author(self) -> None:
  304. _c1, _c2, c3 = build_commit_graph(
  305. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  306. )
  307. self.repo.refs[b"refs/heads/foo"] = c3.id
  308. sha = porcelain.commit(
  309. self.repo.path,
  310. message=b"Some message",
  311. author=b"Joe <joe@example.com>",
  312. committer=b"Bob <bob@example.com>",
  313. )
  314. self.assertIsInstance(sha, bytes)
  315. self.assertEqual(len(sha), 40)
  316. def test_unicode(self) -> None:
  317. _c1, _c2, c3 = build_commit_graph(
  318. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  319. )
  320. self.repo.refs[b"refs/heads/foo"] = c3.id
  321. sha = porcelain.commit(
  322. self.repo.path,
  323. message="Some message",
  324. author="Joe <joe@example.com>",
  325. committer="Bob <bob@example.com>",
  326. )
  327. self.assertIsInstance(sha, bytes)
  328. self.assertEqual(len(sha), 40)
  329. def test_no_verify(self) -> None:
  330. if os.name != "posix":
  331. self.skipTest("shell hook tests requires POSIX shell")
  332. self.assertTrue(os.path.exists("/bin/sh"))
  333. hooks_dir = os.path.join(self.repo.controldir(), "hooks")
  334. os.makedirs(hooks_dir, exist_ok=True)
  335. self.addCleanup(shutil.rmtree, hooks_dir)
  336. _c1, _c2, _c3 = build_commit_graph(
  337. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  338. )
  339. hook_fail = "#!/bin/sh\nexit 1"
  340. # hooks are executed in pre-commit, commit-msg order
  341. # test commit-msg failure first, then pre-commit failure, then
  342. # no_verify to skip both hooks
  343. commit_msg = os.path.join(hooks_dir, "commit-msg")
  344. with open(commit_msg, "w") as f:
  345. f.write(hook_fail)
  346. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  347. with self.assertRaises(CommitError):
  348. porcelain.commit(
  349. self.repo.path,
  350. message="Some message",
  351. author="Joe <joe@example.com>",
  352. committer="Bob <bob@example.com>",
  353. )
  354. pre_commit = os.path.join(hooks_dir, "pre-commit")
  355. with open(pre_commit, "w") as f:
  356. f.write(hook_fail)
  357. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  358. with self.assertRaises(CommitError):
  359. porcelain.commit(
  360. self.repo.path,
  361. message="Some message",
  362. author="Joe <joe@example.com>",
  363. committer="Bob <bob@example.com>",
  364. )
  365. sha = porcelain.commit(
  366. self.repo.path,
  367. message="Some message",
  368. author="Joe <joe@example.com>",
  369. committer="Bob <bob@example.com>",
  370. no_verify=True,
  371. )
  372. self.assertIsInstance(sha, bytes)
  373. self.assertEqual(len(sha), 40)
  374. def test_timezone(self) -> None:
  375. _c1, _c2, c3 = build_commit_graph(
  376. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  377. )
  378. self.repo.refs[b"refs/heads/foo"] = c3.id
  379. sha = porcelain.commit(
  380. self.repo.path,
  381. message="Some message",
  382. author="Joe <joe@example.com>",
  383. author_timezone=18000,
  384. committer="Bob <bob@example.com>",
  385. commit_timezone=18000,
  386. )
  387. self.assertIsInstance(sha, bytes)
  388. self.assertEqual(len(sha), 40)
  389. commit = self.repo.get_object(sha)
  390. assert isinstance(commit, Commit)
  391. self.assertEqual(commit._author_timezone, 18000)
  392. self.assertEqual(commit._commit_timezone, 18000)
  393. self.overrideEnv("GIT_AUTHOR_DATE", "1995-11-20T19:12:08-0501")
  394. self.overrideEnv("GIT_COMMITTER_DATE", "1995-11-20T19:12:08-0501")
  395. sha = porcelain.commit(
  396. self.repo.path,
  397. message="Some message",
  398. author="Joe <joe@example.com>",
  399. committer="Bob <bob@example.com>",
  400. )
  401. self.assertIsInstance(sha, bytes)
  402. self.assertEqual(len(sha), 40)
  403. commit = self.repo.get_object(sha)
  404. assert isinstance(commit, Commit)
  405. self.assertEqual(commit._author_timezone, -18060)
  406. self.assertEqual(commit._commit_timezone, -18060)
  407. self.overrideEnv("GIT_AUTHOR_DATE", None)
  408. self.overrideEnv("GIT_COMMITTER_DATE", None)
  409. local_timezone = time.localtime().tm_gmtoff
  410. sha = porcelain.commit(
  411. self.repo.path,
  412. message="Some message",
  413. author="Joe <joe@example.com>",
  414. committer="Bob <bob@example.com>",
  415. )
  416. self.assertIsInstance(sha, bytes)
  417. self.assertEqual(len(sha), 40)
  418. commit = self.repo.get_object(sha)
  419. assert isinstance(commit, Commit)
  420. self.assertEqual(commit._author_timezone, local_timezone)
  421. self.assertEqual(commit._commit_timezone, local_timezone)
  422. def test_commit_all(self) -> None:
  423. # Create initial commit
  424. filename = os.path.join(self.repo.path, "test.txt")
  425. with open(filename, "wb") as f:
  426. f.write(b"initial content")
  427. porcelain.add(self.repo.path, paths=["test.txt"])
  428. initial_sha = porcelain.commit(self.repo.path, message=b"Initial commit")
  429. # Modify the file without staging
  430. with open(filename, "wb") as f:
  431. f.write(b"modified content")
  432. # Create an untracked file
  433. untracked_file = os.path.join(self.repo.path, "untracked.txt")
  434. with open(untracked_file, "wb") as f:
  435. f.write(b"untracked content")
  436. # Commit with all=True should stage modified files but not untracked
  437. sha = porcelain.commit(self.repo.path, message=b"Modified commit", all=True)
  438. self.assertIsInstance(sha, bytes)
  439. self.assertEqual(len(sha), 40)
  440. self.assertNotEqual(sha, initial_sha)
  441. # Verify the commit contains the modification
  442. commit = self.repo.get_object(sha)
  443. assert isinstance(commit, Commit)
  444. tree = self.repo.get_object(commit.tree)
  445. # The modified file should be in the commit
  446. self.assertIn(b"test.txt", tree)
  447. # The untracked file should not be in the commit
  448. self.assertNotIn(b"untracked.txt", tree)
  449. def test_commit_all_no_changes(self) -> None:
  450. # Create initial commit
  451. filename = os.path.join(self.repo.path, "test.txt")
  452. with open(filename, "wb") as f:
  453. f.write(b"initial content")
  454. porcelain.add(self.repo.path, paths=["test.txt"])
  455. initial_sha = porcelain.commit(self.repo.path, message=b"Initial commit")
  456. # Try to commit with all=True when there are no unstaged changes
  457. sha = porcelain.commit(self.repo.path, message=b"No changes commit", all=True)
  458. self.assertIsInstance(sha, bytes)
  459. self.assertEqual(len(sha), 40)
  460. self.assertNotEqual(sha, initial_sha)
  461. def test_commit_all_multiple_files(self) -> None:
  462. # Create initial commit with multiple files
  463. file1 = os.path.join(self.repo.path, "file1.txt")
  464. file2 = os.path.join(self.repo.path, "file2.txt")
  465. with open(file1, "wb") as f:
  466. f.write(b"content1")
  467. with open(file2, "wb") as f:
  468. f.write(b"content2")
  469. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  470. initial_sha = porcelain.commit(self.repo.path, message=b"Initial commit")
  471. # Modify both files
  472. with open(file1, "wb") as f:
  473. f.write(b"modified content1")
  474. with open(file2, "wb") as f:
  475. f.write(b"modified content2")
  476. # Commit with all=True should stage both modified files
  477. sha = porcelain.commit(self.repo.path, message=b"Modified both files", all=True)
  478. self.assertIsInstance(sha, bytes)
  479. self.assertEqual(len(sha), 40)
  480. self.assertNotEqual(sha, initial_sha)
  481. # Verify both modifications are in the commit
  482. commit = self.repo.get_object(sha)
  483. assert isinstance(commit, Commit)
  484. tree = self.repo.get_object(commit.tree)
  485. self.assertIn(b"file1.txt", tree)
  486. self.assertIn(b"file2.txt", tree)
  487. def test_commit_amend_message(self) -> None:
  488. # Create initial commit
  489. filename = os.path.join(self.repo.path, "test.txt")
  490. with open(filename, "wb") as f:
  491. f.write(b"initial content")
  492. porcelain.add(self.repo.path, paths=["test.txt"])
  493. original_sha = porcelain.commit(self.repo.path, message=b"Original commit")
  494. # Amend with new message
  495. amended_sha = porcelain.commit(
  496. self.repo.path, message=b"Amended commit", amend=True
  497. )
  498. self.assertIsInstance(amended_sha, bytes)
  499. self.assertEqual(len(amended_sha), 40)
  500. self.assertNotEqual(amended_sha, original_sha)
  501. # Check that the amended commit has the new message
  502. amended_commit = self.repo.get_object(amended_sha)
  503. assert isinstance(amended_commit, Commit)
  504. self.assertEqual(amended_commit.message, b"Amended commit")
  505. # Check that the amended commit uses the original commit's parents
  506. original_commit = self.repo.get_object(original_sha)
  507. assert isinstance(original_commit, Commit)
  508. # Since this was the first commit, it should have no parents,
  509. # and the amended commit should also have no parents
  510. self.assertEqual(amended_commit.parents, original_commit.parents)
  511. def test_commit_amend_no_message(self) -> None:
  512. # Create initial commit
  513. filename = os.path.join(self.repo.path, "test.txt")
  514. with open(filename, "wb") as f:
  515. f.write(b"initial content")
  516. porcelain.add(self.repo.path, paths=["test.txt"])
  517. original_sha = porcelain.commit(self.repo.path, message=b"Original commit")
  518. # Modify file and stage it
  519. with open(filename, "wb") as f:
  520. f.write(b"modified content")
  521. porcelain.add(self.repo.path, paths=["test.txt"])
  522. # Amend without providing message (should reuse original message)
  523. amended_sha = porcelain.commit(self.repo.path, amend=True)
  524. self.assertIsInstance(amended_sha, bytes)
  525. self.assertEqual(len(amended_sha), 40)
  526. self.assertNotEqual(amended_sha, original_sha)
  527. # Check that the amended commit has the original message
  528. amended_commit = self.repo.get_object(amended_sha)
  529. assert isinstance(amended_commit, Commit)
  530. self.assertEqual(amended_commit.message, b"Original commit")
  531. def test_commit_amend_no_existing_commit(self) -> None:
  532. # Try to amend when there's no existing commit
  533. with self.assertRaises(ValueError) as cm:
  534. porcelain.commit(self.repo.path, message=b"Should fail", amend=True)
  535. self.assertIn("Cannot amend: no existing commit found", str(cm.exception))
  536. @skipIf(
  537. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  538. "gpgme not easily available or supported on Windows and PyPy",
  539. )
  540. class CommitSignTests(PorcelainGpgTestCase):
  541. def test_default_key(self) -> None:
  542. _c1, _c2, c3 = build_commit_graph(
  543. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  544. )
  545. self.repo.refs[b"HEAD"] = c3.id
  546. cfg = self.repo.get_config()
  547. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  548. self.import_default_key()
  549. sha = porcelain.commit(
  550. self.repo.path,
  551. message="Some message",
  552. author="Joe <joe@example.com>",
  553. committer="Bob <bob@example.com>",
  554. sign=True,
  555. )
  556. self.assertIsInstance(sha, bytes)
  557. self.assertEqual(len(sha), 40)
  558. commit = self.repo.get_object(sha)
  559. assert isinstance(commit, Commit)
  560. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  561. commit.verify()
  562. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  563. self.import_non_default_key()
  564. self.assertRaises(
  565. gpg.errors.MissingSignatures,
  566. commit.verify,
  567. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  568. )
  569. assert isinstance(commit, Commit)
  570. commit.committer = b"Alice <alice@example.com>"
  571. self.assertRaises(
  572. gpg.errors.BadSignatures,
  573. commit.verify,
  574. )
  575. def test_non_default_key(self) -> None:
  576. _c1, _c2, c3 = build_commit_graph(
  577. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  578. )
  579. self.repo.refs[b"HEAD"] = c3.id
  580. cfg = self.repo.get_config()
  581. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  582. self.import_non_default_key()
  583. sha = porcelain.commit(
  584. self.repo.path,
  585. message="Some message",
  586. author="Joe <joe@example.com>",
  587. committer="Bob <bob@example.com>",
  588. signoff=PorcelainGpgTestCase.NON_DEFAULT_KEY_ID,
  589. )
  590. self.assertIsInstance(sha, bytes)
  591. self.assertEqual(len(sha), 40)
  592. commit = self.repo.get_object(sha)
  593. assert isinstance(commit, Commit)
  594. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  595. commit.verify()
  596. def test_sign_uses_config_signingkey(self) -> None:
  597. """Test that sign=True uses user.signingKey from config."""
  598. _c1, _c2, c3 = build_commit_graph(
  599. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  600. )
  601. self.repo.refs[b"HEAD"] = c3.id
  602. # Set up user.signingKey in config
  603. cfg = self.repo.get_config()
  604. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  605. cfg.write_to_path()
  606. self.import_default_key()
  607. # Create commit with sign=True (should use signingKey from config)
  608. sha = porcelain.commit(
  609. self.repo.path,
  610. message="Signed with configured key",
  611. author="Joe <joe@example.com>",
  612. committer="Bob <bob@example.com>",
  613. sign=True, # This should read user.signingKey from config
  614. )
  615. self.assertIsInstance(sha, bytes)
  616. self.assertEqual(len(sha), 40)
  617. commit = self.repo.get_object(sha)
  618. assert isinstance(commit, Commit)
  619. # Verify the commit is signed with the configured key
  620. commit.verify()
  621. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  622. def test_commit_gpg_sign_config_enabled(self) -> None:
  623. """Test that commit.gpgSign=true automatically signs commits."""
  624. _c1, _c2, c3 = build_commit_graph(
  625. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  626. )
  627. self.repo.refs[b"HEAD"] = c3.id
  628. # Set up user.signingKey and commit.gpgSign in config
  629. cfg = self.repo.get_config()
  630. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  631. cfg.set(("commit",), "gpgSign", True)
  632. cfg.write_to_path()
  633. self.import_default_key()
  634. # Create commit without explicit signoff parameter (should auto-sign due to config)
  635. sha = porcelain.commit(
  636. self.repo.path,
  637. message="Auto-signed commit",
  638. author="Joe <joe@example.com>",
  639. committer="Bob <bob@example.com>",
  640. # No signoff parameter - should use commit.gpgSign config
  641. )
  642. self.assertIsInstance(sha, bytes)
  643. self.assertEqual(len(sha), 40)
  644. commit = self.repo.get_object(sha)
  645. assert isinstance(commit, Commit)
  646. # Verify the commit is signed due to config
  647. commit.verify()
  648. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  649. def test_commit_gpg_sign_config_disabled(self) -> None:
  650. """Test that commit.gpgSign=false does not sign commits."""
  651. _c1, _c2, c3 = build_commit_graph(
  652. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  653. )
  654. self.repo.refs[b"HEAD"] = c3.id
  655. # Set up user.signingKey and commit.gpgSign=false in config
  656. cfg = self.repo.get_config()
  657. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  658. cfg.set(("commit",), "gpgSign", False)
  659. cfg.write_to_path()
  660. self.import_default_key()
  661. # Create commit without explicit signoff parameter (should not sign)
  662. sha = porcelain.commit(
  663. self.repo.path,
  664. message="Unsigned commit",
  665. author="Joe <joe@example.com>",
  666. committer="Bob <bob@example.com>",
  667. # No signoff parameter - should use commit.gpgSign=false config
  668. )
  669. self.assertIsInstance(sha, bytes)
  670. self.assertEqual(len(sha), 40)
  671. commit = self.repo.get_object(sha)
  672. assert isinstance(commit, Commit)
  673. # Verify the commit is not signed
  674. self.assertIsNone(commit._gpgsig)
  675. def test_commit_gpg_sign_config_no_signing_key(self) -> None:
  676. """Test that commit.gpgSign=true works without user.signingKey (uses default)."""
  677. _c1, _c2, c3 = build_commit_graph(
  678. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  679. )
  680. self.repo.refs[b"HEAD"] = c3.id
  681. # Set up commit.gpgSign but no user.signingKey
  682. cfg = self.repo.get_config()
  683. cfg.set(("commit",), "gpgSign", True)
  684. cfg.write_to_path()
  685. self.import_default_key()
  686. # Create commit without explicit signoff parameter (should auto-sign with default key)
  687. sha = porcelain.commit(
  688. self.repo.path,
  689. message="Default signed commit",
  690. author="Joe <joe@example.com>",
  691. committer="Bob <bob@example.com>",
  692. # No signoff parameter - should use commit.gpgSign config with default key
  693. )
  694. self.assertIsInstance(sha, bytes)
  695. self.assertEqual(len(sha), 40)
  696. commit = self.repo.get_object(sha)
  697. assert isinstance(commit, Commit)
  698. # Verify the commit is signed with default key
  699. commit.verify()
  700. def test_explicit_signoff_overrides_config(self) -> None:
  701. """Test that explicit signoff parameter overrides commit.gpgSign config."""
  702. _c1, _c2, c3 = build_commit_graph(
  703. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  704. )
  705. self.repo.refs[b"HEAD"] = c3.id
  706. # Set up commit.gpgSign=false but explicitly pass sign=True
  707. cfg = self.repo.get_config()
  708. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  709. cfg.set(("commit",), "gpgSign", False)
  710. cfg.write_to_path()
  711. self.import_default_key()
  712. # Create commit with explicit sign=True (should override config)
  713. sha = porcelain.commit(
  714. self.repo.path,
  715. message="Explicitly signed commit",
  716. author="Joe <joe@example.com>",
  717. committer="Bob <bob@example.com>",
  718. sign=True, # This should override commit.gpgSign=false
  719. )
  720. self.assertIsInstance(sha, bytes)
  721. self.assertEqual(len(sha), 40)
  722. commit = self.repo.get_object(sha)
  723. assert isinstance(commit, Commit)
  724. # Verify the commit is signed despite config=false
  725. commit.verify()
  726. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  727. def test_explicit_false_disables_signing(self) -> None:
  728. """Test that explicit signoff=False disables signing even with config=true."""
  729. _c1, _c2, c3 = build_commit_graph(
  730. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  731. )
  732. self.repo.refs[b"HEAD"] = c3.id
  733. # Set up commit.gpgSign=true but explicitly pass sign=False
  734. cfg = self.repo.get_config()
  735. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  736. cfg.set(("commit",), "gpgSign", True)
  737. cfg.write_to_path()
  738. self.import_default_key()
  739. # Create commit with explicit sign=False (should disable signing)
  740. sha = porcelain.commit(
  741. self.repo.path,
  742. message="Explicitly unsigned commit",
  743. author="Joe <joe@example.com>",
  744. committer="Bob <bob@example.com>",
  745. sign=False, # This should override commit.gpgSign=true
  746. )
  747. self.assertIsInstance(sha, bytes)
  748. self.assertEqual(len(sha), 40)
  749. commit = self.repo.get_object(sha)
  750. assert isinstance(commit, Commit)
  751. # Verify the commit is NOT signed despite config=true
  752. self.assertIsNone(commit._gpgsig)
  753. @skipIf(
  754. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  755. "gpgme not easily available or supported on Windows and PyPy",
  756. )
  757. class VerifyCommitTests(PorcelainGpgTestCase):
  758. def test_verify_commit_valid_signature(self) -> None:
  759. """Test verifying a commit with a valid GPG signature."""
  760. _c1, _c2, c3 = build_commit_graph(
  761. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  762. )
  763. self.repo.refs[b"HEAD"] = c3.id
  764. cfg = self.repo.get_config()
  765. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  766. cfg.write_to_path()
  767. self.import_default_key()
  768. # Create a signed commit
  769. sha = porcelain.commit(
  770. self.repo.path,
  771. message="Signed commit",
  772. author="Joe <joe@example.com>",
  773. committer="Bob <bob@example.com>",
  774. sign=True,
  775. )
  776. # Verify should not raise
  777. porcelain.verify_commit(self.repo.path, sha)
  778. porcelain.verify_commit(
  779. self.repo.path, sha, keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID]
  780. )
  781. def test_verify_commit_with_wrong_key(self) -> None:
  782. """Test that verifying with wrong keyid raises MissingSignatures."""
  783. _c1, _c2, c3 = build_commit_graph(
  784. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  785. )
  786. self.repo.refs[b"HEAD"] = c3.id
  787. cfg = self.repo.get_config()
  788. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  789. cfg.write_to_path()
  790. self.import_default_key()
  791. sha = porcelain.commit(
  792. self.repo.path,
  793. message="Signed commit",
  794. author="Joe <joe@example.com>",
  795. committer="Bob <bob@example.com>",
  796. sign=True,
  797. )
  798. self.import_non_default_key()
  799. self.assertRaises(
  800. gpg.errors.MissingSignatures,
  801. porcelain.verify_commit,
  802. self.repo.path,
  803. sha,
  804. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  805. )
  806. def test_verify_commit_unsigned(self) -> None:
  807. """Test that verifying an unsigned commit succeeds (no signature to verify)."""
  808. _c1, _c2, c3 = build_commit_graph(
  809. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  810. )
  811. self.repo.refs[b"HEAD"] = c3.id
  812. sha = porcelain.commit(
  813. self.repo.path,
  814. message="Unsigned commit",
  815. author="Joe <joe@example.com>",
  816. committer="Bob <bob@example.com>",
  817. sign=False,
  818. )
  819. # Verify should not raise for unsigned commits
  820. porcelain.verify_commit(self.repo.path, sha)
  821. @skipIf(
  822. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  823. "gpgme not easily available or supported on Windows and PyPy",
  824. )
  825. class VerifyTagTests(PorcelainGpgTestCase):
  826. def test_verify_tag_valid_signature(self) -> None:
  827. """Test verifying a tag with a valid GPG signature."""
  828. _c1, _c2, c3 = build_commit_graph(
  829. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  830. )
  831. self.repo.refs[b"HEAD"] = c3.id
  832. cfg = self.repo.get_config()
  833. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  834. cfg.write_to_path()
  835. self.import_default_key()
  836. # Create a signed tag
  837. porcelain.tag_create(
  838. self.repo.path,
  839. b"signed-tag",
  840. b"Tagger <tagger@example.com>",
  841. b"Signed tag message",
  842. annotated=True,
  843. sign=True,
  844. )
  845. # Verify should not raise
  846. porcelain.verify_tag(self.repo.path, b"signed-tag")
  847. porcelain.verify_tag(
  848. self.repo.path, b"signed-tag", keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID]
  849. )
  850. def test_verify_tag_with_wrong_key(self) -> None:
  851. """Test that verifying with wrong keyid raises MissingSignatures."""
  852. _c1, _c2, c3 = build_commit_graph(
  853. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  854. )
  855. self.repo.refs[b"HEAD"] = c3.id
  856. cfg = self.repo.get_config()
  857. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  858. cfg.write_to_path()
  859. self.import_default_key()
  860. porcelain.tag_create(
  861. self.repo.path,
  862. b"signed-tag",
  863. b"Tagger <tagger@example.com>",
  864. b"Signed tag message",
  865. annotated=True,
  866. sign=True,
  867. )
  868. self.import_non_default_key()
  869. self.assertRaises(
  870. gpg.errors.MissingSignatures,
  871. porcelain.verify_tag,
  872. self.repo.path,
  873. b"signed-tag",
  874. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  875. )
  876. def test_verify_tag_unsigned(self) -> None:
  877. """Test that verifying an unsigned tag succeeds (no signature to verify)."""
  878. _c1, _c2, c3 = build_commit_graph(
  879. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  880. )
  881. self.repo.refs[b"HEAD"] = c3.id
  882. porcelain.tag_create(
  883. self.repo.path,
  884. b"unsigned-tag",
  885. b"Tagger <tagger@example.com>",
  886. b"Unsigned tag message",
  887. annotated=True,
  888. sign=False,
  889. )
  890. # Verify should not raise for unsigned tags
  891. porcelain.verify_tag(self.repo.path, b"unsigned-tag")
  892. class TimezoneTests(PorcelainTestCase):
  893. def put_envs(self, value) -> None:
  894. self.overrideEnv("GIT_AUTHOR_DATE", value)
  895. self.overrideEnv("GIT_COMMITTER_DATE", value)
  896. def fallback(self, value) -> None:
  897. self.put_envs(value)
  898. self.assertRaises(porcelain.TimezoneFormatError, porcelain.get_user_timezones)
  899. def test_internal_format(self) -> None:
  900. self.put_envs("0 +0500")
  901. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  902. def test_rfc_2822(self) -> None:
  903. self.put_envs("Mon, 20 Nov 1995 19:12:08 -0500")
  904. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  905. self.put_envs("Mon, 20 Nov 1995 19:12:08")
  906. self.assertTupleEqual((0, 0), porcelain.get_user_timezones())
  907. def test_iso8601(self) -> None:
  908. self.put_envs("1995-11-20T19:12:08-0501")
  909. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  910. self.put_envs("1995-11-20T19:12:08+0501")
  911. self.assertTupleEqual((18060, 18060), porcelain.get_user_timezones())
  912. self.put_envs("1995-11-20T19:12:08-05:01")
  913. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  914. self.put_envs("1995-11-20 19:12:08-05")
  915. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  916. # https://github.com/git/git/blob/96b2d4fa927c5055adc5b1d08f10a5d7352e2989/t/t6300-for-each-ref.sh#L128
  917. self.put_envs("2006-07-03 17:18:44 +0200")
  918. self.assertTupleEqual((7200, 7200), porcelain.get_user_timezones())
  919. def test_missing_or_malformed(self) -> None:
  920. # TODO: add more here
  921. self.fallback("0 + 0500")
  922. self.fallback("a +0500")
  923. self.fallback("1995-11-20T19:12:08")
  924. self.fallback("1995-11-20T19:12:08-05:")
  925. self.fallback("1995.11.20")
  926. self.fallback("11/20/1995")
  927. self.fallback("20.11.1995")
  928. def test_different_envs(self) -> None:
  929. self.overrideEnv("GIT_AUTHOR_DATE", "0 +0500")
  930. self.overrideEnv("GIT_COMMITTER_DATE", "0 +0501")
  931. self.assertTupleEqual((18000, 18060), porcelain.get_user_timezones())
  932. def test_no_envs(self) -> None:
  933. local_timezone = time.localtime().tm_gmtoff
  934. self.put_envs("0 +0500")
  935. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  936. self.overrideEnv("GIT_COMMITTER_DATE", None)
  937. self.assertTupleEqual((18000, local_timezone), porcelain.get_user_timezones())
  938. self.put_envs("0 +0500")
  939. self.overrideEnv("GIT_AUTHOR_DATE", None)
  940. self.assertTupleEqual((local_timezone, 18000), porcelain.get_user_timezones())
  941. self.put_envs("0 +0500")
  942. self.overrideEnv("GIT_AUTHOR_DATE", None)
  943. self.overrideEnv("GIT_COMMITTER_DATE", None)
  944. self.assertTupleEqual(
  945. (local_timezone, local_timezone), porcelain.get_user_timezones()
  946. )
  947. class CleanTests(PorcelainTestCase):
  948. def put_files(self, tracked, ignored, untracked, empty_dirs) -> None:
  949. """Put the described files in the wd."""
  950. all_files = tracked | ignored | untracked
  951. for file_path in all_files:
  952. abs_path = os.path.join(self.repo.path, file_path)
  953. # File may need to be written in a dir that doesn't exist yet, so
  954. # create the parent dir(s) as necessary
  955. parent_dir = os.path.dirname(abs_path)
  956. try:
  957. os.makedirs(parent_dir)
  958. except FileExistsError:
  959. pass
  960. with open(abs_path, "w") as f:
  961. f.write("")
  962. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  963. f.writelines(ignored)
  964. for dir_path in empty_dirs:
  965. os.mkdir(os.path.join(self.repo.path, "empty_dir"))
  966. files_to_add = [os.path.join(self.repo.path, t) for t in tracked]
  967. porcelain.add(repo=self.repo.path, paths=files_to_add)
  968. porcelain.commit(repo=self.repo.path, message="init commit")
  969. def assert_wd(self, expected_paths) -> None:
  970. """Assert paths of files and dirs in wd are same as expected_paths."""
  971. control_dir_rel = os.path.relpath(self.repo._controldir, self.repo.path)
  972. # normalize paths to simplify comparison across platforms
  973. found_paths = {
  974. os.path.normpath(p)
  975. for p in flat_walk_dir(self.repo.path)
  976. if not p.split(os.sep)[0] == control_dir_rel
  977. }
  978. norm_expected_paths = {os.path.normpath(p) for p in expected_paths}
  979. self.assertEqual(found_paths, norm_expected_paths)
  980. def test_from_root(self) -> None:
  981. self.put_files(
  982. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  983. ignored={"ignored_file"},
  984. untracked={
  985. "untracked_file",
  986. "tracked_dir/untracked_dir/untracked_file",
  987. "untracked_dir/untracked_dir/untracked_file",
  988. },
  989. empty_dirs={"empty_dir"},
  990. )
  991. porcelain.clean(repo=self.repo.path, target_dir=self.repo.path)
  992. self.assert_wd(
  993. {
  994. "tracked_file",
  995. "tracked_dir/tracked_file",
  996. ".gitignore",
  997. "ignored_file",
  998. "tracked_dir",
  999. }
  1000. )
  1001. def test_from_subdir(self) -> None:
  1002. self.put_files(
  1003. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  1004. ignored={"ignored_file"},
  1005. untracked={
  1006. "untracked_file",
  1007. "tracked_dir/untracked_dir/untracked_file",
  1008. "untracked_dir/untracked_dir/untracked_file",
  1009. },
  1010. empty_dirs={"empty_dir"},
  1011. )
  1012. porcelain.clean(
  1013. repo=self.repo,
  1014. target_dir=os.path.join(self.repo.path, "untracked_dir"),
  1015. )
  1016. self.assert_wd(
  1017. {
  1018. "tracked_file",
  1019. "tracked_dir/tracked_file",
  1020. ".gitignore",
  1021. "ignored_file",
  1022. "untracked_file",
  1023. "tracked_dir/untracked_dir/untracked_file",
  1024. "empty_dir",
  1025. "untracked_dir",
  1026. "tracked_dir",
  1027. "tracked_dir/untracked_dir",
  1028. }
  1029. )
  1030. class CloneTests(PorcelainTestCase):
  1031. def test_simple_local(self) -> None:
  1032. f1_1 = make_object(Blob, data=b"f1")
  1033. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1034. trees = {
  1035. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1036. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1037. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1038. }
  1039. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1040. self.repo.refs[b"refs/heads/master"] = c3.id
  1041. self.repo.refs[b"refs/tags/foo"] = c3.id
  1042. target_path = tempfile.mkdtemp()
  1043. errstream = BytesIO()
  1044. self.addCleanup(shutil.rmtree, target_path)
  1045. r = porcelain.clone(
  1046. self.repo.path, target_path, checkout=False, errstream=errstream
  1047. )
  1048. self.addCleanup(r.close)
  1049. self.assertEqual(r.path, target_path)
  1050. target_repo = Repo(target_path)
  1051. self.addCleanup(target_repo.close)
  1052. self.assertEqual(0, len(target_repo.open_index()))
  1053. self.assertEqual(c3.id, target_repo.refs[b"refs/tags/foo"])
  1054. self.assertNotIn(b"f1", os.listdir(target_path))
  1055. self.assertNotIn(b"f2", os.listdir(target_path))
  1056. c = r.get_config()
  1057. encoded_path = self.repo.path
  1058. if not isinstance(encoded_path, bytes):
  1059. encoded_path_bytes = encoded_path.encode("utf-8")
  1060. else:
  1061. encoded_path_bytes = encoded_path
  1062. self.assertEqual(encoded_path_bytes, c.get((b"remote", b"origin"), b"url"))
  1063. self.assertEqual(
  1064. b"+refs/heads/*:refs/remotes/origin/*",
  1065. c.get((b"remote", b"origin"), b"fetch"),
  1066. )
  1067. def test_simple_local_with_checkout(self) -> None:
  1068. f1_1 = make_object(Blob, data=b"f1")
  1069. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1070. trees = {
  1071. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1072. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1073. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1074. }
  1075. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1076. self.repo.refs[b"refs/heads/master"] = c3.id
  1077. target_path = tempfile.mkdtemp()
  1078. errstream = BytesIO()
  1079. self.addCleanup(shutil.rmtree, target_path)
  1080. with porcelain.clone(
  1081. self.repo.path, target_path, checkout=True, errstream=errstream
  1082. ) as r:
  1083. self.assertEqual(r.path, target_path)
  1084. with Repo(target_path) as r:
  1085. self.assertEqual(r.head(), c3.id)
  1086. self.assertIn("f1", os.listdir(target_path))
  1087. self.assertIn("f2", os.listdir(target_path))
  1088. def test_bare_local_with_checkout(self) -> None:
  1089. f1_1 = make_object(Blob, data=b"f1")
  1090. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1091. trees = {
  1092. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1093. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1094. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1095. }
  1096. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1097. self.repo.refs[b"refs/heads/master"] = c3.id
  1098. target_path = tempfile.mkdtemp()
  1099. errstream = BytesIO()
  1100. self.addCleanup(shutil.rmtree, target_path)
  1101. with porcelain.clone(
  1102. self.repo.path, target_path, bare=True, errstream=errstream
  1103. ) as r:
  1104. self.assertEqual(r.path, target_path)
  1105. with Repo(target_path) as r:
  1106. r.head()
  1107. self.assertRaises(NoIndexPresent, r.open_index)
  1108. self.assertNotIn(b"f1", os.listdir(target_path))
  1109. self.assertNotIn(b"f2", os.listdir(target_path))
  1110. def test_no_checkout_with_bare(self) -> None:
  1111. f1_1 = make_object(Blob, data=b"f1")
  1112. commit_spec = [[1]]
  1113. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1114. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1115. self.repo.refs[b"refs/heads/master"] = c1.id
  1116. self.repo.refs[b"HEAD"] = c1.id
  1117. target_path = tempfile.mkdtemp()
  1118. errstream = BytesIO()
  1119. self.addCleanup(shutil.rmtree, target_path)
  1120. self.assertRaises(
  1121. porcelain.Error,
  1122. porcelain.clone,
  1123. self.repo.path,
  1124. target_path,
  1125. checkout=True,
  1126. bare=True,
  1127. errstream=errstream,
  1128. )
  1129. def test_no_head_no_checkout(self) -> None:
  1130. f1_1 = make_object(Blob, data=b"f1")
  1131. commit_spec = [[1]]
  1132. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1133. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1134. self.repo.refs[b"refs/heads/master"] = c1.id
  1135. target_path = tempfile.mkdtemp()
  1136. self.addCleanup(shutil.rmtree, target_path)
  1137. errstream = BytesIO()
  1138. r = porcelain.clone(
  1139. self.repo.path, target_path, checkout=True, errstream=errstream
  1140. )
  1141. r.close()
  1142. def test_no_head_no_checkout_outstream_errstream_autofallback(self) -> None:
  1143. f1_1 = make_object(Blob, data=b"f1")
  1144. commit_spec = [[1]]
  1145. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1146. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1147. self.repo.refs[b"refs/heads/master"] = c1.id
  1148. target_path = tempfile.mkdtemp()
  1149. self.addCleanup(shutil.rmtree, target_path)
  1150. errstream = porcelain.NoneStream()
  1151. r = porcelain.clone(
  1152. self.repo.path, target_path, checkout=True, errstream=errstream
  1153. )
  1154. r.close()
  1155. def test_source_broken(self) -> None:
  1156. with tempfile.TemporaryDirectory() as parent:
  1157. target_path = os.path.join(parent, "target")
  1158. self.assertRaises(
  1159. Exception, porcelain.clone, "/nonexistent/repo", target_path
  1160. )
  1161. self.assertFalse(os.path.exists(target_path))
  1162. def test_fetch_symref(self) -> None:
  1163. f1_1 = make_object(Blob, data=b"f1")
  1164. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1165. [c1] = build_commit_graph(self.repo.object_store, [[1]], trees)
  1166. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/else")
  1167. self.repo.refs[b"refs/heads/else"] = c1.id
  1168. target_path = tempfile.mkdtemp()
  1169. errstream = BytesIO()
  1170. self.addCleanup(shutil.rmtree, target_path)
  1171. r = porcelain.clone(
  1172. self.repo.path, target_path, checkout=False, errstream=errstream
  1173. )
  1174. self.addCleanup(r.close)
  1175. self.assertEqual(r.path, target_path)
  1176. target_repo = Repo(target_path)
  1177. self.addCleanup(target_repo.close)
  1178. self.assertEqual(0, len(target_repo.open_index()))
  1179. self.assertEqual(c1.id, target_repo.refs[b"refs/heads/else"])
  1180. self.assertEqual(c1.id, target_repo.refs[b"HEAD"])
  1181. self.assertEqual(
  1182. {
  1183. b"HEAD": b"refs/heads/else",
  1184. b"refs/remotes/origin/HEAD": b"refs/remotes/origin/else",
  1185. },
  1186. target_repo.refs.get_symrefs(),
  1187. )
  1188. def test_detached_head(self) -> None:
  1189. f1_1 = make_object(Blob, data=b"f1")
  1190. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1191. trees = {
  1192. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1193. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1194. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1195. }
  1196. _c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1197. self.repo.refs[b"refs/heads/master"] = c2.id
  1198. self.repo.refs.remove_if_equals(b"HEAD", None)
  1199. self.repo.refs[b"HEAD"] = c3.id
  1200. target_path = tempfile.mkdtemp()
  1201. self.addCleanup(shutil.rmtree, target_path)
  1202. errstream = porcelain.NoneStream()
  1203. with porcelain.clone(
  1204. self.repo.path, target_path, checkout=True, errstream=errstream
  1205. ) as r:
  1206. self.assertEqual(c3.id, r.refs[b"HEAD"])
  1207. def test_clone_pathlib(self) -> None:
  1208. from pathlib import Path
  1209. f1_1 = make_object(Blob, data=b"f1")
  1210. commit_spec = [[1]]
  1211. trees = {1: [(b"f1", f1_1)]}
  1212. c1 = build_commit_graph(self.repo.object_store, commit_spec, trees)[0]
  1213. self.repo.refs[b"refs/heads/master"] = c1.id
  1214. target_dir = tempfile.mkdtemp()
  1215. self.addCleanup(shutil.rmtree, target_dir)
  1216. target_path = Path(target_dir) / "clone_repo"
  1217. errstream = BytesIO()
  1218. r = porcelain.clone(
  1219. self.repo.path, target_path, checkout=False, errstream=errstream
  1220. )
  1221. self.addCleanup(r.close)
  1222. self.assertEqual(r.path, str(target_path))
  1223. self.assertTrue(os.path.exists(str(target_path)))
  1224. def test_clone_with_recurse_submodules(self) -> None:
  1225. # Create a submodule repository
  1226. sub_repo_path = tempfile.mkdtemp()
  1227. self.addCleanup(shutil.rmtree, sub_repo_path)
  1228. sub_repo = Repo.init(sub_repo_path)
  1229. self.addCleanup(sub_repo.close)
  1230. # Add a file to the submodule repo
  1231. sub_file = os.path.join(sub_repo_path, "subfile.txt")
  1232. with open(sub_file, "w") as f:
  1233. f.write("submodule content")
  1234. porcelain.add(sub_repo, paths=[sub_file])
  1235. sub_commit = porcelain.commit(
  1236. sub_repo,
  1237. message=b"Initial submodule commit",
  1238. author=b"Test Author <test@example.com>",
  1239. committer=b"Test Committer <test@example.com>",
  1240. )
  1241. # Create main repository with submodule
  1242. main_file = os.path.join(self.repo.path, "main.txt")
  1243. with open(main_file, "w") as f:
  1244. f.write("main content")
  1245. porcelain.add(self.repo, paths=[main_file])
  1246. porcelain.submodule_add(self.repo, sub_repo_path, "sub")
  1247. # Manually add the submodule to the index since submodule_add doesn't do it
  1248. # when the repository is local (to maintain backward compatibility)
  1249. from dulwich.index import IndexEntry
  1250. from dulwich.objects import S_IFGITLINK
  1251. index = self.repo.open_index()
  1252. index[b"sub"] = IndexEntry(
  1253. ctime=0,
  1254. mtime=0,
  1255. dev=0,
  1256. ino=0,
  1257. mode=S_IFGITLINK,
  1258. uid=0,
  1259. gid=0,
  1260. size=0,
  1261. sha=sub_commit,
  1262. flags=0,
  1263. )
  1264. index.write()
  1265. porcelain.add(self.repo, paths=[".gitmodules"])
  1266. porcelain.commit(
  1267. self.repo,
  1268. message=b"Add submodule",
  1269. author=b"Test Author <test@example.com>",
  1270. committer=b"Test Committer <test@example.com>",
  1271. )
  1272. # Clone with recurse_submodules
  1273. target_path = tempfile.mkdtemp()
  1274. self.addCleanup(shutil.rmtree, target_path)
  1275. cloned = porcelain.clone(
  1276. self.repo.path,
  1277. target_path,
  1278. recurse_submodules=True,
  1279. )
  1280. self.addCleanup(cloned.close)
  1281. # Check main file exists
  1282. cloned_main = os.path.join(target_path, "main.txt")
  1283. self.assertTrue(os.path.exists(cloned_main))
  1284. with open(cloned_main) as f:
  1285. self.assertEqual(f.read(), "main content")
  1286. # Check submodule file exists
  1287. cloned_sub_file = os.path.join(target_path, "sub", "subfile.txt")
  1288. self.assertTrue(os.path.exists(cloned_sub_file))
  1289. with open(cloned_sub_file) as f:
  1290. self.assertEqual(f.read(), "submodule content")
  1291. def test_clone_with_refspec_kwarg(self) -> None:
  1292. """Test that clone accepts refspec as a kwarg without TypeError.
  1293. This reproduces a bug where passing refspec as a kwarg to clone()
  1294. would cause a TypeError because it was being passed to
  1295. get_transport_and_path() which doesn't accept that parameter.
  1296. """
  1297. f1_1 = make_object(Blob, data=b"f1")
  1298. commit_spec = [[1]]
  1299. trees = {1: [(b"f1", f1_1)]}
  1300. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1301. self.repo.refs[b"refs/heads/master"] = c1.id
  1302. target_path = tempfile.mkdtemp()
  1303. errstream = BytesIO()
  1304. self.addCleanup(shutil.rmtree, target_path)
  1305. # This should not raise TypeError
  1306. r = porcelain.clone(
  1307. self.repo.path,
  1308. target_path,
  1309. checkout=False,
  1310. errstream=errstream,
  1311. refspec="refs/heads/master",
  1312. )
  1313. self.addCleanup(r.close)
  1314. self.assertEqual(r.path, target_path)
  1315. class InitTests(TestCase):
  1316. def test_non_bare(self) -> None:
  1317. repo_dir = tempfile.mkdtemp()
  1318. self.addCleanup(shutil.rmtree, repo_dir)
  1319. porcelain.init(repo_dir)
  1320. def test_bare(self) -> None:
  1321. repo_dir = tempfile.mkdtemp()
  1322. self.addCleanup(shutil.rmtree, repo_dir)
  1323. porcelain.init(repo_dir, bare=True)
  1324. def test_init_pathlib(self) -> None:
  1325. from pathlib import Path
  1326. repo_dir = tempfile.mkdtemp()
  1327. self.addCleanup(shutil.rmtree, repo_dir)
  1328. repo_path = Path(repo_dir)
  1329. # Test non-bare repo with pathlib
  1330. repo = porcelain.init(repo_path)
  1331. self.assertTrue(os.path.exists(os.path.join(repo_dir, ".git")))
  1332. repo.close()
  1333. def test_init_bare_pathlib(self) -> None:
  1334. from pathlib import Path
  1335. repo_dir = tempfile.mkdtemp()
  1336. self.addCleanup(shutil.rmtree, repo_dir)
  1337. repo_path = Path(repo_dir)
  1338. # Test bare repo with pathlib
  1339. repo = porcelain.init(repo_path, bare=True)
  1340. self.assertTrue(os.path.exists(os.path.join(repo_dir, "refs")))
  1341. repo.close()
  1342. class AddTests(PorcelainTestCase):
  1343. def test_add_default_paths(self) -> None:
  1344. # create a file for initial commit
  1345. fullpath = os.path.join(self.repo.path, "blah")
  1346. with open(fullpath, "w") as f:
  1347. f.write("\n")
  1348. porcelain.add(repo=self.repo.path, paths=[fullpath])
  1349. porcelain.commit(
  1350. repo=self.repo.path,
  1351. message=b"test",
  1352. author=b"test <email>",
  1353. committer=b"test <email>",
  1354. )
  1355. # Add a second test file and a file in a directory
  1356. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1357. f.write("\n")
  1358. os.mkdir(os.path.join(self.repo.path, "adir"))
  1359. with open(os.path.join(self.repo.path, "adir", "afile"), "w") as f:
  1360. f.write("\n")
  1361. cwd = os.getcwd()
  1362. self.addCleanup(os.chdir, cwd)
  1363. os.chdir(self.repo.path)
  1364. self.assertEqual({"foo", "blah", "adir", ".git"}, set(os.listdir(".")))
  1365. added, ignored = porcelain.add(self.repo.path)
  1366. # Normalize paths to use forward slashes for comparison
  1367. added_normalized = [path.replace(os.sep, "/") for path in added]
  1368. self.assertEqual(
  1369. (added_normalized, ignored),
  1370. (["foo", "adir/afile"], set()),
  1371. )
  1372. # Check that foo was added and nothing in .git was modified
  1373. index = self.repo.open_index()
  1374. self.assertEqual(sorted(index), [b"adir/afile", b"blah", b"foo"])
  1375. def test_add_default_paths_subdir(self) -> None:
  1376. os.mkdir(os.path.join(self.repo.path, "foo"))
  1377. with open(os.path.join(self.repo.path, "blah"), "w") as f:
  1378. f.write("\n")
  1379. with open(os.path.join(self.repo.path, "foo", "blie"), "w") as f:
  1380. f.write("\n")
  1381. cwd = os.getcwd()
  1382. self.addCleanup(os.chdir, cwd)
  1383. os.chdir(os.path.join(self.repo.path, "foo"))
  1384. porcelain.add(repo=self.repo.path)
  1385. porcelain.commit(
  1386. repo=self.repo.path,
  1387. message=b"test",
  1388. author=b"test <email>",
  1389. committer=b"test <email>",
  1390. )
  1391. index = self.repo.open_index()
  1392. # After fix: add() with no paths should behave like git add -A (add everything)
  1393. self.assertEqual(sorted(index), [b"blah", b"foo/blie"])
  1394. def test_add_file(self) -> None:
  1395. fullpath = os.path.join(self.repo.path, "foo")
  1396. with open(fullpath, "w") as f:
  1397. f.write("BAR")
  1398. porcelain.add(self.repo.path, paths=[fullpath])
  1399. self.assertIn(b"foo", self.repo.open_index())
  1400. def test_add_ignored(self) -> None:
  1401. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1402. f.write("foo\nsubdir/")
  1403. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1404. f.write("BAR")
  1405. with open(os.path.join(self.repo.path, "bar"), "w") as f:
  1406. f.write("BAR")
  1407. os.mkdir(os.path.join(self.repo.path, "subdir"))
  1408. with open(os.path.join(self.repo.path, "subdir", "baz"), "w") as f:
  1409. f.write("BAZ")
  1410. (added, ignored) = porcelain.add(
  1411. self.repo.path,
  1412. paths=[
  1413. os.path.join(self.repo.path, "foo"),
  1414. os.path.join(self.repo.path, "bar"),
  1415. os.path.join(self.repo.path, "subdir"),
  1416. ],
  1417. )
  1418. self.assertIn(b"bar", self.repo.open_index())
  1419. self.assertEqual({"bar"}, set(added))
  1420. self.assertEqual({"foo", "subdir/"}, ignored)
  1421. def test_add_from_ignored_directory(self) -> None:
  1422. # Test for issue #550 - adding files when cwd is in ignored directory
  1423. # Create .gitignore that ignores build/
  1424. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1425. f.write("build/\n")
  1426. # Create ignored directory
  1427. build_dir = os.path.join(self.repo.path, "build")
  1428. os.mkdir(build_dir)
  1429. # Create a file in the repo (not in ignored directory)
  1430. src_file = os.path.join(self.repo.path, "source.py")
  1431. with open(src_file, "w") as f:
  1432. f.write("print('hello')\n")
  1433. # Save current directory and change to ignored directory
  1434. original_cwd = os.getcwd()
  1435. try:
  1436. os.chdir(build_dir)
  1437. # Add file using absolute path from within ignored directory
  1438. (added, _ignored) = porcelain.add(self.repo.path, paths=[src_file])
  1439. self.assertIn(b"source.py", self.repo.open_index())
  1440. self.assertEqual({"source.py"}, set(added))
  1441. finally:
  1442. os.chdir(original_cwd)
  1443. def test_add_file_absolute_path(self) -> None:
  1444. # Absolute paths are (not yet) supported
  1445. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1446. f.write("BAR")
  1447. porcelain.add(self.repo, paths=[os.path.join(self.repo.path, "foo")])
  1448. self.assertIn(b"foo", self.repo.open_index())
  1449. def test_add_not_in_repo(self) -> None:
  1450. with open(os.path.join(self.test_dir, "foo"), "w") as f:
  1451. f.write("BAR")
  1452. self.assertRaises(
  1453. ValueError,
  1454. porcelain.add,
  1455. self.repo,
  1456. paths=[os.path.join(self.test_dir, "foo")],
  1457. )
  1458. self.assertRaises(
  1459. (ValueError, FileNotFoundError),
  1460. porcelain.add,
  1461. self.repo,
  1462. paths=["../foo"],
  1463. )
  1464. self.assertEqual([], list(self.repo.open_index()))
  1465. def test_add_file_clrf_conversion(self) -> None:
  1466. from dulwich.index import IndexEntry
  1467. # Set the right configuration to the repo
  1468. c = self.repo.get_config()
  1469. c.set("core", "autocrlf", "input")
  1470. c.write_to_path()
  1471. # Add a file with CRLF line-ending
  1472. fullpath = os.path.join(self.repo.path, "foo")
  1473. with open(fullpath, "wb") as f:
  1474. f.write(b"line1\r\nline2")
  1475. porcelain.add(self.repo.path, paths=[fullpath])
  1476. # The line-endings should have been converted to LF
  1477. index = self.repo.open_index()
  1478. self.assertIn(b"foo", index)
  1479. entry = index[b"foo"]
  1480. assert isinstance(entry, IndexEntry)
  1481. blob = self.repo[entry.sha]
  1482. self.assertEqual(blob.data, b"line1\nline2")
  1483. def test_add_symlink_outside_repo(self) -> None:
  1484. """Test adding a symlink that points outside the repository."""
  1485. # Create a symlink pointing outside the repository
  1486. symlink_path = os.path.join(self.repo.path, "symlink_to_nowhere")
  1487. os.symlink("/nonexistent/path", symlink_path)
  1488. # Adding the symlink should succeed (matching Git's behavior)
  1489. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1490. # Should successfully add the symlink
  1491. self.assertIn("symlink_to_nowhere", added)
  1492. self.assertEqual(len(ignored), 0)
  1493. # Verify symlink is actually staged
  1494. index = self.repo.open_index()
  1495. self.assertIn(b"symlink_to_nowhere", index)
  1496. def test_add_symlink_to_file_inside_repo(self) -> None:
  1497. """Test adding a symlink that points to a file inside the repository."""
  1498. # Create a regular file
  1499. target_file = os.path.join(self.repo.path, "target.txt")
  1500. with open(target_file, "w") as f:
  1501. f.write("target content")
  1502. # Create a symlink to the file
  1503. symlink_path = os.path.join(self.repo.path, "link_to_target")
  1504. os.symlink("target.txt", symlink_path)
  1505. # Add both the target and the symlink
  1506. added, ignored = porcelain.add(
  1507. self.repo.path, paths=[target_file, symlink_path]
  1508. )
  1509. # Both should be added successfully
  1510. self.assertIn("target.txt", added)
  1511. self.assertIn("link_to_target", added)
  1512. self.assertEqual(len(ignored), 0)
  1513. # Verify both are in the index
  1514. index = self.repo.open_index()
  1515. self.assertIn(b"target.txt", index)
  1516. self.assertIn(b"link_to_target", index)
  1517. def test_add_symlink_to_directory_inside_repo(self) -> None:
  1518. """Test adding a symlink that points to a directory inside the repository."""
  1519. # Create a directory with some files
  1520. target_dir = os.path.join(self.repo.path, "target_dir")
  1521. os.mkdir(target_dir)
  1522. with open(os.path.join(target_dir, "file1.txt"), "w") as f:
  1523. f.write("content1")
  1524. with open(os.path.join(target_dir, "file2.txt"), "w") as f:
  1525. f.write("content2")
  1526. # Create a symlink to the directory
  1527. symlink_path = os.path.join(self.repo.path, "link_to_dir")
  1528. os.symlink("target_dir", symlink_path)
  1529. # Add the symlink
  1530. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1531. # When adding a symlink to a directory, it follows the symlink and adds contents
  1532. self.assertEqual(len(added), 2)
  1533. self.assertIn("link_to_dir/file1.txt", added)
  1534. self.assertIn("link_to_dir/file2.txt", added)
  1535. self.assertEqual(len(ignored), 0)
  1536. # Verify files are added through the symlink path
  1537. index = self.repo.open_index()
  1538. self.assertIn(b"link_to_dir/file1.txt", index)
  1539. self.assertIn(b"link_to_dir/file2.txt", index)
  1540. # The original target directory files are not added
  1541. self.assertNotIn(b"target_dir/file1.txt", index)
  1542. self.assertNotIn(b"target_dir/file2.txt", index)
  1543. def test_add_symlink_chain(self) -> None:
  1544. """Test adding a chain of symlinks (symlink to symlink)."""
  1545. # Create a regular file
  1546. target_file = os.path.join(self.repo.path, "original.txt")
  1547. with open(target_file, "w") as f:
  1548. f.write("original content")
  1549. # Create first symlink
  1550. first_link = os.path.join(self.repo.path, "link1")
  1551. os.symlink("original.txt", first_link)
  1552. # Create second symlink pointing to first
  1553. second_link = os.path.join(self.repo.path, "link2")
  1554. os.symlink("link1", second_link)
  1555. # Add all files
  1556. added, _ignored = porcelain.add(
  1557. self.repo.path, paths=[target_file, first_link, second_link]
  1558. )
  1559. # All should be added
  1560. self.assertEqual(len(added), 3)
  1561. self.assertIn("original.txt", added)
  1562. self.assertIn("link1", added)
  1563. self.assertIn("link2", added)
  1564. # Verify all are in the index
  1565. index = self.repo.open_index()
  1566. self.assertIn(b"original.txt", index)
  1567. self.assertIn(b"link1", index)
  1568. self.assertIn(b"link2", index)
  1569. def test_add_broken_symlink(self) -> None:
  1570. """Test adding a broken symlink (points to non-existent target)."""
  1571. # Create a symlink to a non-existent file
  1572. broken_link = os.path.join(self.repo.path, "broken_link")
  1573. os.symlink("does_not_exist.txt", broken_link)
  1574. # Add the broken symlink
  1575. added, ignored = porcelain.add(self.repo.path, paths=[broken_link])
  1576. # Should be added successfully (Git tracks the symlink, not its target)
  1577. self.assertIn("broken_link", added)
  1578. self.assertEqual(len(ignored), 0)
  1579. # Verify it's in the index
  1580. index = self.repo.open_index()
  1581. self.assertIn(b"broken_link", index)
  1582. def test_add_symlink_relative_outside_repo(self) -> None:
  1583. """Test adding a symlink that uses '..' to point outside the repository."""
  1584. # Create a file outside the repo
  1585. outside_file = os.path.join(self.test_dir, "outside.txt")
  1586. with open(outside_file, "w") as f:
  1587. f.write("outside content")
  1588. # Create a symlink using relative path to go outside
  1589. symlink_path = os.path.join(self.repo.path, "link_outside")
  1590. os.symlink("../outside.txt", symlink_path)
  1591. # Add the symlink
  1592. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1593. # Should be added successfully
  1594. self.assertIn("link_outside", added)
  1595. self.assertEqual(len(ignored), 0)
  1596. # Verify it's in the index
  1597. index = self.repo.open_index()
  1598. self.assertIn(b"link_outside", index)
  1599. def test_add_symlink_absolute_to_system(self) -> None:
  1600. """Test adding a symlink with absolute path to system directory."""
  1601. # Create a symlink to a system directory
  1602. symlink_path = os.path.join(self.repo.path, "link_to_tmp")
  1603. if os.name == "nt":
  1604. # On Windows, use a system directory like TEMP
  1605. symlink_target = os.environ["TEMP"]
  1606. else:
  1607. # On Unix-like systems, use /tmp
  1608. symlink_target = os.environ.get("TMPDIR", "/tmp")
  1609. os.symlink(symlink_target, symlink_path)
  1610. # Adding a symlink to a directory outside the repo should raise ValueError
  1611. with self.assertRaises(ValueError) as cm:
  1612. porcelain.add(self.repo.path, paths=[symlink_path])
  1613. # Check that the error indicates the path is outside the repository
  1614. self.assertIn("is not in the subpath of", str(cm.exception))
  1615. def test_add_file_through_symlink(self) -> None:
  1616. """Test adding a file through a symlinked directory."""
  1617. # Create a directory with a file
  1618. real_dir = os.path.join(self.repo.path, "real_dir")
  1619. os.mkdir(real_dir)
  1620. real_file = os.path.join(real_dir, "file.txt")
  1621. with open(real_file, "w") as f:
  1622. f.write("content")
  1623. # Create a symlink to the directory
  1624. link_dir = os.path.join(self.repo.path, "link_dir")
  1625. os.symlink("real_dir", link_dir)
  1626. # Try to add the file through the symlink path
  1627. symlink_file_path = os.path.join(link_dir, "file.txt")
  1628. # This should add the real file, not create a new entry
  1629. added, _ignored = porcelain.add(self.repo.path, paths=[symlink_file_path])
  1630. # The real file should be added
  1631. self.assertIn("real_dir/file.txt", added)
  1632. self.assertEqual(len(added), 1)
  1633. # Verify correct path in index
  1634. index = self.repo.open_index()
  1635. self.assertIn(b"real_dir/file.txt", index)
  1636. # Should not create a separate entry for the symlink path
  1637. self.assertNotIn(b"link_dir/file.txt", index)
  1638. def test_add_repo_path(self) -> None:
  1639. """Test adding the repository path itself should add all untracked files."""
  1640. # Create some untracked files
  1641. with open(os.path.join(self.repo.path, "file1.txt"), "w") as f:
  1642. f.write("content1")
  1643. with open(os.path.join(self.repo.path, "file2.txt"), "w") as f:
  1644. f.write("content2")
  1645. # Add the repository path itself
  1646. added, _ignored = porcelain.add(self.repo.path, paths=[self.repo.path])
  1647. # Should add all untracked files, not stage './'
  1648. self.assertIn("file1.txt", added)
  1649. self.assertIn("file2.txt", added)
  1650. self.assertNotIn("./", added)
  1651. # Verify files are actually staged
  1652. index = self.repo.open_index()
  1653. self.assertIn(b"file1.txt", index)
  1654. self.assertIn(b"file2.txt", index)
  1655. def test_add_directory_contents(self) -> None:
  1656. """Test adding a directory adds all files within it."""
  1657. # Create a subdirectory with multiple files
  1658. subdir = os.path.join(self.repo.path, "subdir")
  1659. os.mkdir(subdir)
  1660. with open(os.path.join(subdir, "file1.txt"), "w") as f:
  1661. f.write("content1")
  1662. with open(os.path.join(subdir, "file2.txt"), "w") as f:
  1663. f.write("content2")
  1664. with open(os.path.join(subdir, "file3.txt"), "w") as f:
  1665. f.write("content3")
  1666. # Add the directory
  1667. added, _ignored = porcelain.add(self.repo.path, paths=["subdir"])
  1668. # Should add all files in the directory
  1669. self.assertEqual(len(added), 3)
  1670. # Normalize paths to use forward slashes for comparison
  1671. added_normalized = [path.replace(os.sep, "/") for path in added]
  1672. self.assertIn("subdir/file1.txt", added_normalized)
  1673. self.assertIn("subdir/file2.txt", added_normalized)
  1674. self.assertIn("subdir/file3.txt", added_normalized)
  1675. # Verify files are actually staged
  1676. index = self.repo.open_index()
  1677. self.assertIn(b"subdir/file1.txt", index)
  1678. self.assertIn(b"subdir/file2.txt", index)
  1679. self.assertIn(b"subdir/file3.txt", index)
  1680. def test_add_nested_directories(self) -> None:
  1681. """Test adding a directory with nested subdirectories."""
  1682. # Create nested directory structure
  1683. dir1 = os.path.join(self.repo.path, "dir1")
  1684. dir2 = os.path.join(dir1, "dir2")
  1685. dir3 = os.path.join(dir2, "dir3")
  1686. os.makedirs(dir3)
  1687. # Add files at each level
  1688. with open(os.path.join(dir1, "file1.txt"), "w") as f:
  1689. f.write("level1")
  1690. with open(os.path.join(dir2, "file2.txt"), "w") as f:
  1691. f.write("level2")
  1692. with open(os.path.join(dir3, "file3.txt"), "w") as f:
  1693. f.write("level3")
  1694. # Add the top-level directory
  1695. added, _ignored = porcelain.add(self.repo.path, paths=["dir1"])
  1696. # Should add all files recursively
  1697. self.assertEqual(len(added), 3)
  1698. # Normalize paths to use forward slashes for comparison
  1699. added_normalized = [path.replace(os.sep, "/") for path in added]
  1700. self.assertIn("dir1/file1.txt", added_normalized)
  1701. self.assertIn("dir1/dir2/file2.txt", added_normalized)
  1702. self.assertIn("dir1/dir2/dir3/file3.txt", added_normalized)
  1703. # Verify files are actually staged
  1704. index = self.repo.open_index()
  1705. self.assertIn(b"dir1/file1.txt", index)
  1706. self.assertIn(b"dir1/dir2/file2.txt", index)
  1707. self.assertIn(b"dir1/dir2/dir3/file3.txt", index)
  1708. def test_add_directory_with_tracked_files(self) -> None:
  1709. """Test adding a directory with some files already tracked."""
  1710. # Create a subdirectory with files
  1711. subdir = os.path.join(self.repo.path, "mixed")
  1712. os.mkdir(subdir)
  1713. # Create and commit one file
  1714. tracked_file = os.path.join(subdir, "tracked.txt")
  1715. with open(tracked_file, "w") as f:
  1716. f.write("already tracked")
  1717. porcelain.add(self.repo.path, paths=[tracked_file])
  1718. porcelain.commit(
  1719. repo=self.repo.path,
  1720. message=b"Add tracked file",
  1721. author=b"test <email>",
  1722. committer=b"test <email>",
  1723. )
  1724. # Add more untracked files
  1725. with open(os.path.join(subdir, "untracked1.txt"), "w") as f:
  1726. f.write("new file 1")
  1727. with open(os.path.join(subdir, "untracked2.txt"), "w") as f:
  1728. f.write("new file 2")
  1729. # Add the directory
  1730. added, _ignored = porcelain.add(self.repo.path, paths=["mixed"])
  1731. # Should only add the untracked files
  1732. self.assertEqual(len(added), 2)
  1733. # Normalize paths to use forward slashes for comparison
  1734. added_normalized = [path.replace(os.sep, "/") for path in added]
  1735. self.assertIn("mixed/untracked1.txt", added_normalized)
  1736. self.assertIn("mixed/untracked2.txt", added_normalized)
  1737. self.assertNotIn("mixed/tracked.txt", added)
  1738. # Verify the index contains all files
  1739. index = self.repo.open_index()
  1740. self.assertIn(b"mixed/tracked.txt", index)
  1741. self.assertIn(b"mixed/untracked1.txt", index)
  1742. self.assertIn(b"mixed/untracked2.txt", index)
  1743. def test_add_directory_with_gitignore(self) -> None:
  1744. """Test adding a directory respects .gitignore patterns."""
  1745. # Create .gitignore
  1746. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1747. f.write("*.log\n*.tmp\nbuild/\n")
  1748. # Create directory with mixed files
  1749. testdir = os.path.join(self.repo.path, "testdir")
  1750. os.mkdir(testdir)
  1751. # Create various files
  1752. with open(os.path.join(testdir, "important.txt"), "w") as f:
  1753. f.write("keep this")
  1754. with open(os.path.join(testdir, "debug.log"), "w") as f:
  1755. f.write("ignore this")
  1756. with open(os.path.join(testdir, "temp.tmp"), "w") as f:
  1757. f.write("ignore this too")
  1758. with open(os.path.join(testdir, "readme.md"), "w") as f:
  1759. f.write("keep this too")
  1760. # Create a build directory that should be ignored
  1761. builddir = os.path.join(testdir, "build")
  1762. os.mkdir(builddir)
  1763. with open(os.path.join(builddir, "output.txt"), "w") as f:
  1764. f.write("ignore entire directory")
  1765. # Add the directory
  1766. added, ignored = porcelain.add(self.repo.path, paths=["testdir"])
  1767. # Should only add non-ignored files
  1768. # Normalize paths to use forward slashes for comparison
  1769. added_normalized = {path.replace(os.sep, "/") for path in added}
  1770. self.assertEqual(
  1771. added_normalized, {"testdir/important.txt", "testdir/readme.md"}
  1772. )
  1773. # Check ignored files
  1774. # Normalize paths to use forward slashes for comparison
  1775. ignored_normalized = {path.replace(os.sep, "/") for path in ignored}
  1776. self.assertIn("testdir/debug.log", ignored_normalized)
  1777. self.assertIn("testdir/temp.tmp", ignored_normalized)
  1778. self.assertIn("testdir/build/", ignored_normalized)
  1779. def test_add_multiple_directories(self) -> None:
  1780. """Test adding multiple directories in one call."""
  1781. # Create multiple directories
  1782. for dirname in ["dir1", "dir2", "dir3"]:
  1783. dirpath = os.path.join(self.repo.path, dirname)
  1784. os.mkdir(dirpath)
  1785. # Add files to each directory
  1786. for i in range(2):
  1787. with open(os.path.join(dirpath, f"file{i}.txt"), "w") as f:
  1788. f.write(f"content {dirname} {i}")
  1789. # Add all directories at once
  1790. added, _ignored = porcelain.add(self.repo.path, paths=["dir1", "dir2", "dir3"])
  1791. # Should add all files from all directories
  1792. self.assertEqual(len(added), 6)
  1793. # Normalize paths to use forward slashes for comparison
  1794. added_normalized = [path.replace(os.sep, "/") for path in added]
  1795. for dirname in ["dir1", "dir2", "dir3"]:
  1796. for i in range(2):
  1797. self.assertIn(f"{dirname}/file{i}.txt", added_normalized)
  1798. # Verify all files are staged
  1799. index = self.repo.open_index()
  1800. self.assertEqual(len(index), 6)
  1801. def test_add_default_paths_includes_modified_files(self) -> None:
  1802. """Test that add() with no paths includes both untracked and modified files."""
  1803. # Create and commit initial file
  1804. initial_file = os.path.join(self.repo.path, "existing.txt")
  1805. with open(initial_file, "w") as f:
  1806. f.write("initial content\n")
  1807. porcelain.add(repo=self.repo.path, paths=[initial_file])
  1808. porcelain.commit(
  1809. repo=self.repo.path,
  1810. message=b"initial commit",
  1811. author=b"test <email>",
  1812. committer=b"test <email>",
  1813. )
  1814. # Modify the existing file (this creates an unstaged change)
  1815. with open(initial_file, "w") as f:
  1816. f.write("modified content\n")
  1817. # Create a new untracked file
  1818. new_file = os.path.join(self.repo.path, "new.txt")
  1819. with open(new_file, "w") as f:
  1820. f.write("new file content\n")
  1821. # Call add() with no paths - should stage both modified and untracked files
  1822. added_files, ignored_files = porcelain.add(repo=self.repo.path)
  1823. # Verify both files were added
  1824. self.assertIn("existing.txt", added_files)
  1825. self.assertIn("new.txt", added_files)
  1826. self.assertEqual(len(ignored_files), 0)
  1827. # Verify both files are now staged
  1828. index = self.repo.open_index()
  1829. self.assertIn(b"existing.txt", index)
  1830. self.assertIn(b"new.txt", index)
  1831. class RemoveTests(PorcelainTestCase):
  1832. def test_remove_file(self) -> None:
  1833. fullpath = os.path.join(self.repo.path, "foo")
  1834. with open(fullpath, "w") as f:
  1835. f.write("BAR")
  1836. porcelain.add(self.repo.path, paths=[fullpath])
  1837. porcelain.commit(
  1838. repo=self.repo,
  1839. message=b"test",
  1840. author=b"test <email>",
  1841. committer=b"test <email>",
  1842. )
  1843. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "foo")))
  1844. cwd = os.getcwd()
  1845. self.addCleanup(os.chdir, cwd)
  1846. os.chdir(self.repo.path)
  1847. porcelain.remove(self.repo.path, paths=["foo"])
  1848. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1849. def test_remove_file_staged(self) -> None:
  1850. fullpath = os.path.join(self.repo.path, "foo")
  1851. with open(fullpath, "w") as f:
  1852. f.write("BAR")
  1853. cwd = os.getcwd()
  1854. self.addCleanup(os.chdir, cwd)
  1855. os.chdir(self.repo.path)
  1856. porcelain.add(self.repo.path, paths=[fullpath])
  1857. self.assertRaises(Exception, porcelain.rm, self.repo.path, paths=["foo"])
  1858. def test_remove_file_removed_on_disk(self) -> None:
  1859. fullpath = os.path.join(self.repo.path, "foo")
  1860. with open(fullpath, "w") as f:
  1861. f.write("BAR")
  1862. porcelain.add(self.repo.path, paths=[fullpath])
  1863. cwd = os.getcwd()
  1864. self.addCleanup(os.chdir, cwd)
  1865. os.chdir(self.repo.path)
  1866. os.remove(fullpath)
  1867. porcelain.remove(self.repo.path, paths=["foo"])
  1868. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1869. def test_remove_from_different_directory(self) -> None:
  1870. # Create a subdirectory with a file
  1871. subdir = os.path.join(self.repo.path, "mydir")
  1872. os.makedirs(subdir)
  1873. fullpath = os.path.join(subdir, "myfile")
  1874. with open(fullpath, "w") as f:
  1875. f.write("BAR")
  1876. # Add and commit the file
  1877. porcelain.add(self.repo.path, paths=[fullpath])
  1878. porcelain.commit(
  1879. repo=self.repo,
  1880. message=b"test",
  1881. author=b"test <email>",
  1882. committer=b"test <email>",
  1883. )
  1884. # Change to a different directory
  1885. cwd = os.getcwd()
  1886. tempdir = tempfile.mkdtemp()
  1887. def cleanup():
  1888. os.chdir(cwd)
  1889. shutil.rmtree(tempdir)
  1890. self.addCleanup(cleanup)
  1891. os.chdir(tempdir)
  1892. # Remove the file using relative path from repository root
  1893. porcelain.remove(self.repo.path, paths=["mydir/myfile"])
  1894. # Verify file was removed
  1895. self.assertFalse(os.path.exists(fullpath))
  1896. def test_remove_with_absolute_path(self) -> None:
  1897. # Create a file
  1898. fullpath = os.path.join(self.repo.path, "foo")
  1899. with open(fullpath, "w") as f:
  1900. f.write("BAR")
  1901. # Add and commit the file
  1902. porcelain.add(self.repo.path, paths=[fullpath])
  1903. porcelain.commit(
  1904. repo=self.repo,
  1905. message=b"test",
  1906. author=b"test <email>",
  1907. committer=b"test <email>",
  1908. )
  1909. # Change to a different directory
  1910. cwd = os.getcwd()
  1911. tempdir = tempfile.mkdtemp()
  1912. def cleanup():
  1913. os.chdir(cwd)
  1914. shutil.rmtree(tempdir)
  1915. self.addCleanup(cleanup)
  1916. os.chdir(tempdir)
  1917. # Remove the file using absolute path
  1918. porcelain.remove(self.repo.path, paths=[fullpath])
  1919. # Verify file was removed
  1920. self.assertFalse(os.path.exists(fullpath))
  1921. def test_remove_with_filter_normalization(self) -> None:
  1922. # Enable autocrlf to normalize line endings
  1923. config = self.repo.get_config()
  1924. config.set(("core",), "autocrlf", b"true")
  1925. config.write_to_path()
  1926. # Create a file with LF line endings (will be stored with LF in index)
  1927. fullpath = os.path.join(self.repo.path, "foo.txt")
  1928. with open(fullpath, "wb") as f:
  1929. f.write(b"line1\nline2\nline3")
  1930. # Add and commit the file (stored with LF in index)
  1931. porcelain.add(self.repo.path, paths=[fullpath])
  1932. porcelain.commit(
  1933. repo=self.repo,
  1934. message=b"Add file with LF",
  1935. author=b"test <email>",
  1936. committer=b"test <email>",
  1937. )
  1938. # Simulate checkout with CRLF conversion (as would happen on Windows)
  1939. with open(fullpath, "wb") as f:
  1940. f.write(b"line1\r\nline2\r\nline3")
  1941. # Verify file exists
  1942. self.assertTrue(os.path.exists(fullpath))
  1943. # Remove the file - this should not fail even though working tree has CRLF
  1944. # and index has LF (thanks to the normalization in the commit)
  1945. cwd = os.getcwd()
  1946. os.chdir(self.repo.path)
  1947. self.addCleanup(os.chdir, cwd)
  1948. porcelain.remove(self.repo.path, paths=["foo.txt"])
  1949. # Verify file was removed
  1950. self.assertFalse(os.path.exists(fullpath))
  1951. class MvTests(PorcelainTestCase):
  1952. def test_mv_file(self) -> None:
  1953. # Create a file
  1954. fullpath = os.path.join(self.repo.path, "foo")
  1955. with open(fullpath, "w") as f:
  1956. f.write("BAR")
  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
  1966. porcelain.mv(self.repo.path, "foo", "bar")
  1967. # Verify old path doesn't exist and new path does
  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, "bar")))
  1970. # Verify index was updated
  1971. index = self.repo.open_index()
  1972. self.assertNotIn(b"foo", index)
  1973. self.assertIn(b"bar", index)
  1974. def test_mv_file_to_existing_directory(self) -> None:
  1975. # Create a file and a directory
  1976. fullpath = os.path.join(self.repo.path, "foo")
  1977. with open(fullpath, "w") as f:
  1978. f.write("BAR")
  1979. dirpath = os.path.join(self.repo.path, "mydir")
  1980. os.makedirs(dirpath)
  1981. # Add and commit the file
  1982. porcelain.add(self.repo.path, paths=[fullpath])
  1983. porcelain.commit(
  1984. repo=self.repo,
  1985. message=b"test",
  1986. author=b"test <email>",
  1987. committer=b"test <email>",
  1988. )
  1989. # Move the file into the directory
  1990. porcelain.mv(self.repo.path, "foo", "mydir")
  1991. # Verify file moved into directory
  1992. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1993. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "mydir", "foo")))
  1994. # Verify index was updated
  1995. index = self.repo.open_index()
  1996. self.assertNotIn(b"foo", index)
  1997. self.assertIn(b"mydir/foo", index)
  1998. def test_mv_file_force_overwrite(self) -> None:
  1999. # Create two files
  2000. fullpath1 = os.path.join(self.repo.path, "foo")
  2001. with open(fullpath1, "w") as f:
  2002. f.write("FOO")
  2003. fullpath2 = os.path.join(self.repo.path, "bar")
  2004. with open(fullpath2, "w") as f:
  2005. f.write("BAR")
  2006. # Add and commit both files
  2007. porcelain.add(self.repo.path, paths=[fullpath1, fullpath2])
  2008. porcelain.commit(
  2009. repo=self.repo,
  2010. message=b"test",
  2011. author=b"test <email>",
  2012. committer=b"test <email>",
  2013. )
  2014. # Try to move without force (should fail)
  2015. self.assertRaises(porcelain.Error, porcelain.mv, self.repo.path, "foo", "bar")
  2016. # Move with force
  2017. porcelain.mv(self.repo.path, "foo", "bar", force=True)
  2018. # Verify foo doesn't exist and bar has foo's content
  2019. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  2020. with open(os.path.join(self.repo.path, "bar")) as f:
  2021. self.assertEqual(f.read(), "FOO")
  2022. def test_mv_file_not_tracked(self) -> None:
  2023. # Create an untracked file
  2024. fullpath = os.path.join(self.repo.path, "untracked")
  2025. with open(fullpath, "w") as f:
  2026. f.write("UNTRACKED")
  2027. # Try to move it (should fail)
  2028. self.assertRaises(
  2029. porcelain.Error, porcelain.mv, self.repo.path, "untracked", "tracked"
  2030. )
  2031. def test_mv_file_not_exists(self) -> None:
  2032. # Try to move a non-existent file
  2033. self.assertRaises(
  2034. porcelain.Error, porcelain.mv, self.repo.path, "nonexistent", "destination"
  2035. )
  2036. def test_mv_absolute_paths(self) -> None:
  2037. # Create a file
  2038. fullpath = os.path.join(self.repo.path, "foo")
  2039. with open(fullpath, "w") as f:
  2040. f.write("BAR")
  2041. # Add and commit the file
  2042. porcelain.add(self.repo.path, paths=[fullpath])
  2043. porcelain.commit(
  2044. repo=self.repo,
  2045. message=b"test",
  2046. author=b"test <email>",
  2047. committer=b"test <email>",
  2048. )
  2049. # Move using absolute paths
  2050. dest_path = os.path.join(self.repo.path, "bar")
  2051. porcelain.mv(self.repo.path, fullpath, dest_path)
  2052. # Verify file moved
  2053. self.assertFalse(os.path.exists(fullpath))
  2054. self.assertTrue(os.path.exists(dest_path))
  2055. def test_mv_from_different_directory(self) -> None:
  2056. # Create a subdirectory with a file
  2057. subdir = os.path.join(self.repo.path, "mydir")
  2058. os.makedirs(subdir)
  2059. fullpath = os.path.join(subdir, "myfile")
  2060. with open(fullpath, "w") as f:
  2061. f.write("BAR")
  2062. # Add and commit the file
  2063. porcelain.add(self.repo.path, paths=[fullpath])
  2064. porcelain.commit(
  2065. repo=self.repo,
  2066. message=b"test",
  2067. author=b"test <email>",
  2068. committer=b"test <email>",
  2069. )
  2070. # Change to a different directory and move the file
  2071. cwd = os.getcwd()
  2072. tempdir = tempfile.mkdtemp()
  2073. def cleanup():
  2074. os.chdir(cwd)
  2075. shutil.rmtree(tempdir)
  2076. self.addCleanup(cleanup)
  2077. os.chdir(tempdir)
  2078. # Move the file using relative path from repository root
  2079. porcelain.mv(self.repo.path, "mydir/myfile", "renamed")
  2080. # Verify file was moved
  2081. self.assertFalse(os.path.exists(fullpath))
  2082. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "renamed")))
  2083. class LogTests(PorcelainTestCase):
  2084. def test_simple(self) -> None:
  2085. _c1, _c2, c3 = build_commit_graph(
  2086. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2087. )
  2088. self.repo.refs[b"HEAD"] = c3.id
  2089. self.maxDiff = None
  2090. outstream = StringIO()
  2091. porcelain.log(self.repo.path, outstream=outstream)
  2092. self.assertEqual(
  2093. outstream.getvalue(),
  2094. """\
  2095. --------------------------------------------------
  2096. commit: 4a3b887baa9ecb2d054d2469b628aef84e2d74f0
  2097. merge: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  2098. Author: Test Author <test@nodomain.com>
  2099. Committer: Test Committer <test@nodomain.com>
  2100. Date: Fri Jan 01 2010 00:00:00 +0000
  2101. Commit 3
  2102. --------------------------------------------------
  2103. commit: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  2104. Author: Test Author <test@nodomain.com>
  2105. Committer: Test Committer <test@nodomain.com>
  2106. Date: Fri Jan 01 2010 00:00:00 +0000
  2107. Commit 2
  2108. --------------------------------------------------
  2109. commit: 11d3cf672a19366435c1983c7340b008ec6b8bf3
  2110. Author: Test Author <test@nodomain.com>
  2111. Committer: Test Committer <test@nodomain.com>
  2112. Date: Fri Jan 01 2010 00:00:00 +0000
  2113. Commit 1
  2114. """,
  2115. )
  2116. def test_max_entries(self) -> None:
  2117. _c1, _c2, c3 = build_commit_graph(
  2118. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2119. )
  2120. self.repo.refs[b"HEAD"] = c3.id
  2121. outstream = StringIO()
  2122. porcelain.log(self.repo.path, outstream=outstream, max_entries=1)
  2123. self.assertEqual(1, outstream.getvalue().count("-" * 50))
  2124. def test_no_revisions(self) -> None:
  2125. outstream = StringIO()
  2126. porcelain.log(self.repo.path, outstream=outstream)
  2127. self.assertEqual("", outstream.getvalue())
  2128. def test_empty_message(self) -> None:
  2129. c1 = make_commit(message="")
  2130. self.repo.object_store.add_object(c1)
  2131. self.repo.refs[b"HEAD"] = c1.id
  2132. outstream = StringIO()
  2133. porcelain.log(self.repo.path, outstream=outstream)
  2134. self.assertEqual(
  2135. outstream.getvalue(),
  2136. """\
  2137. --------------------------------------------------
  2138. commit: 4a7ad5552fad70647a81fb9a4a923ccefcca4b76
  2139. Author: Test Author <test@nodomain.com>
  2140. Committer: Test Committer <test@nodomain.com>
  2141. Date: Fri Jan 01 2010 00:00:00 +0000
  2142. """,
  2143. )
  2144. class ShowTests(PorcelainTestCase):
  2145. def test_nolist(self) -> None:
  2146. _c1, _c2, c3 = build_commit_graph(
  2147. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2148. )
  2149. self.repo.refs[b"HEAD"] = c3.id
  2150. outstream = StringIO()
  2151. porcelain.show(self.repo.path, objects=c3.id, outstream=outstream)
  2152. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  2153. def test_simple(self) -> None:
  2154. _c1, _c2, c3 = build_commit_graph(
  2155. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2156. )
  2157. self.repo.refs[b"HEAD"] = c3.id
  2158. outstream = StringIO()
  2159. porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream)
  2160. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  2161. def test_blob(self) -> None:
  2162. b = Blob.from_string(b"The Foo\n")
  2163. self.repo.object_store.add_object(b)
  2164. outstream = StringIO()
  2165. porcelain.show(self.repo.path, objects=[b.id], outstream=outstream)
  2166. self.assertEqual(outstream.getvalue(), "The Foo\n")
  2167. def test_commit_no_parent(self) -> None:
  2168. a = Blob.from_string(b"The Foo\n")
  2169. ta = Tree()
  2170. ta.add(b"somename", 0o100644, a.id)
  2171. ca = make_commit(tree=ta.id)
  2172. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2173. outstream = StringIO()
  2174. porcelain.show(self.repo.path, objects=[ca.id], outstream=outstream)
  2175. self.assertMultiLineEqual(
  2176. outstream.getvalue(),
  2177. """\
  2178. --------------------------------------------------
  2179. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2180. Author: Test Author <test@nodomain.com>
  2181. Committer: Test Committer <test@nodomain.com>
  2182. Date: Fri Jan 01 2010 00:00:00 +0000
  2183. Test message.
  2184. diff --git a/somename b/somename
  2185. new file mode 100644
  2186. index 0000000..ea5c7bf
  2187. --- /dev/null
  2188. +++ b/somename
  2189. @@ -0,0 +1 @@
  2190. +The Foo
  2191. """,
  2192. )
  2193. def test_tag(self) -> None:
  2194. a = Blob.from_string(b"The Foo\n")
  2195. ta = Tree()
  2196. ta.add(b"somename", 0o100644, a.id)
  2197. ca = make_commit(tree=ta.id)
  2198. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2199. porcelain.tag_create(
  2200. self.repo.path,
  2201. b"tryme",
  2202. b"foo <foo@bar.com>",
  2203. b"bar",
  2204. annotated=True,
  2205. objectish=ca.id,
  2206. tag_time=1552854211,
  2207. tag_timezone=0,
  2208. )
  2209. outstream = StringIO()
  2210. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2211. self.maxDiff = None
  2212. self.assertMultiLineEqual(
  2213. outstream.getvalue(),
  2214. """\
  2215. Tagger: foo <foo@bar.com>
  2216. Date: Sun Mar 17 2019 20:23:31 +0000
  2217. bar
  2218. --------------------------------------------------
  2219. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2220. Author: Test Author <test@nodomain.com>
  2221. Committer: Test Committer <test@nodomain.com>
  2222. Date: Fri Jan 01 2010 00:00:00 +0000
  2223. Test message.
  2224. diff --git a/somename b/somename
  2225. new file mode 100644
  2226. index 0000000..ea5c7bf
  2227. --- /dev/null
  2228. +++ b/somename
  2229. @@ -0,0 +1 @@
  2230. +The Foo
  2231. """,
  2232. )
  2233. def test_tag_unicode(self) -> None:
  2234. a = Blob.from_string(b"The Foo\n")
  2235. ta = Tree()
  2236. ta.add(b"somename", 0o100644, a.id)
  2237. ca = make_commit(tree=ta.id)
  2238. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2239. porcelain.tag_create(
  2240. self.repo.path,
  2241. "tryme",
  2242. "foo <foo@bar.com>",
  2243. "bar",
  2244. annotated=True,
  2245. objectish=ca.id,
  2246. tag_time=1552854211,
  2247. tag_timezone=0,
  2248. )
  2249. outstream = StringIO()
  2250. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2251. self.maxDiff = None
  2252. self.assertMultiLineEqual(
  2253. outstream.getvalue(),
  2254. """\
  2255. Tagger: foo <foo@bar.com>
  2256. Date: Sun Mar 17 2019 20:23:31 +0000
  2257. bar
  2258. --------------------------------------------------
  2259. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2260. Author: Test Author <test@nodomain.com>
  2261. Committer: Test Committer <test@nodomain.com>
  2262. Date: Fri Jan 01 2010 00:00:00 +0000
  2263. Test message.
  2264. diff --git a/somename b/somename
  2265. new file mode 100644
  2266. index 0000000..ea5c7bf
  2267. --- /dev/null
  2268. +++ b/somename
  2269. @@ -0,0 +1 @@
  2270. +The Foo
  2271. """,
  2272. )
  2273. def test_commit_with_change(self) -> None:
  2274. a = Blob.from_string(b"The Foo\n")
  2275. ta = Tree()
  2276. ta.add(b"somename", 0o100644, a.id)
  2277. ca = make_commit(tree=ta.id)
  2278. b = Blob.from_string(b"The Bar\n")
  2279. tb = Tree()
  2280. tb.add(b"somename", 0o100644, b.id)
  2281. cb = make_commit(tree=tb.id, parents=[ca.id])
  2282. self.repo.object_store.add_objects(
  2283. [
  2284. (a, None),
  2285. (b, None),
  2286. (ta, None),
  2287. (tb, None),
  2288. (ca, None),
  2289. (cb, None),
  2290. ]
  2291. )
  2292. outstream = StringIO()
  2293. porcelain.show(self.repo.path, objects=[cb.id], outstream=outstream)
  2294. self.assertMultiLineEqual(
  2295. outstream.getvalue(),
  2296. """\
  2297. --------------------------------------------------
  2298. commit: 2c6b6c9cb72c130956657e1fdae58e5b103744fa
  2299. Author: Test Author <test@nodomain.com>
  2300. Committer: Test Committer <test@nodomain.com>
  2301. Date: Fri Jan 01 2010 00:00:00 +0000
  2302. Test message.
  2303. diff --git a/somename b/somename
  2304. index ea5c7bf..fd38bcb 100644
  2305. --- a/somename
  2306. +++ b/somename
  2307. @@ -1 +1 @@
  2308. -The Foo
  2309. +The Bar
  2310. """,
  2311. )
  2312. class FormatPatchTests(PorcelainTestCase):
  2313. def test_format_patch_single_commit(self) -> None:
  2314. # Create initial commit
  2315. tree1 = Tree()
  2316. c1 = make_commit(
  2317. tree=tree1,
  2318. message=b"Initial commit",
  2319. )
  2320. self.repo.object_store.add_objects([(tree1, None), (c1, None)])
  2321. # Create second commit
  2322. b = Blob.from_string(b"modified")
  2323. tree = Tree()
  2324. tree.add(b"test.txt", 0o100644, b.id)
  2325. c2 = make_commit(
  2326. tree=tree,
  2327. parents=[c1.id],
  2328. message=b"Add test.txt",
  2329. )
  2330. self.repo.object_store.add_objects([(b, None), (tree, None), (c2, None)])
  2331. self.repo[b"HEAD"] = c2.id
  2332. # Generate patch for single commit
  2333. with tempfile.TemporaryDirectory() as tmpdir:
  2334. patches = porcelain.format_patch(
  2335. self.repo.path,
  2336. committish=c2.id,
  2337. outdir=tmpdir,
  2338. )
  2339. self.assertEqual(len(patches), 1)
  2340. self.assertTrue(patches[0].endswith("-Add-test.txt.patch"))
  2341. # Verify patch content
  2342. with open(patches[0], "rb") as f:
  2343. content = f.read()
  2344. self.assertIn(b"Subject: [PATCH 1/1] Add test.txt", content)
  2345. self.assertIn(b"+modified", content)
  2346. def test_format_patch_multiple_commits(self) -> None:
  2347. # Create commit chain
  2348. commits = []
  2349. for i in range(3):
  2350. blob = Blob.from_string(f"content {i}".encode())
  2351. tree = Tree()
  2352. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  2353. parents = [commits[-1].id] if commits else []
  2354. commit = make_commit(
  2355. tree=tree,
  2356. parents=parents,
  2357. message=f"Commit {i}".encode(),
  2358. )
  2359. self.repo.object_store.add_objects(
  2360. [(blob, None), (tree, None), (commit, None)]
  2361. )
  2362. commits.append(commit)
  2363. self.repo[b"HEAD"] = commits[-1].id
  2364. # Test generating last 2 commits
  2365. with tempfile.TemporaryDirectory() as tmpdir:
  2366. patches = porcelain.format_patch(
  2367. self.repo.path,
  2368. n=2,
  2369. outdir=tmpdir,
  2370. )
  2371. self.assertEqual(len(patches), 2)
  2372. self.assertTrue(patches[0].endswith("-Commit-1.patch"))
  2373. self.assertTrue(patches[1].endswith("-Commit-2.patch"))
  2374. # Check patch numbering
  2375. with open(patches[0], "rb") as f:
  2376. self.assertIn(b"Subject: [PATCH 1/2] Commit 1", f.read())
  2377. with open(patches[1], "rb") as f:
  2378. self.assertIn(b"Subject: [PATCH 2/2] Commit 2", f.read())
  2379. def test_format_patch_range(self) -> None:
  2380. # Create commit chain
  2381. c1, _c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  2382. self.repo[b"HEAD"] = c3.id
  2383. # Test commit range
  2384. with tempfile.TemporaryDirectory() as tmpdir:
  2385. patches = porcelain.format_patch(
  2386. self.repo.path,
  2387. committish=(c1.id, c3.id),
  2388. outdir=tmpdir,
  2389. )
  2390. # Should include c2 and c3
  2391. self.assertEqual(len(patches), 2)
  2392. def test_format_patch_stdout(self) -> None:
  2393. # Create a commit
  2394. blob = Blob.from_string(b"test content")
  2395. tree = Tree()
  2396. tree.add(b"test.txt", 0o100644, blob.id)
  2397. commit = make_commit(
  2398. tree=tree,
  2399. message=b"Test commit",
  2400. )
  2401. self.repo.object_store.add_objects([(blob, None), (tree, None), (commit, None)])
  2402. self.repo[b"HEAD"] = commit.id
  2403. # Test stdout output
  2404. outstream = BytesIO()
  2405. patches = porcelain.format_patch(
  2406. self.repo.path,
  2407. committish=commit.id,
  2408. stdout=True,
  2409. outstream=outstream,
  2410. )
  2411. # Should return empty list when writing to stdout
  2412. self.assertEqual(patches, [])
  2413. # Check stdout content
  2414. outstream.seek(0)
  2415. content = outstream.read()
  2416. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  2417. self.assertIn(b"diff --git", content)
  2418. def test_format_patch_no_commits(self) -> None:
  2419. # Test with a new repository with no commits
  2420. # Just remove HEAD to simulate empty repo
  2421. patches = porcelain.format_patch(
  2422. self.repo.path,
  2423. n=5,
  2424. )
  2425. self.assertEqual(patches, [])
  2426. class SymbolicRefTests(PorcelainTestCase):
  2427. def test_set_wrong_symbolic_ref(self) -> None:
  2428. _c1, _c2, c3 = build_commit_graph(
  2429. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2430. )
  2431. self.repo.refs[b"HEAD"] = c3.id
  2432. self.assertRaises(
  2433. porcelain.Error, porcelain.symbolic_ref, self.repo.path, b"foobar"
  2434. )
  2435. def test_set_force_wrong_symbolic_ref(self) -> None:
  2436. _c1, _c2, c3 = build_commit_graph(
  2437. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2438. )
  2439. self.repo.refs[b"HEAD"] = c3.id
  2440. porcelain.symbolic_ref(self.repo.path, b"force_foobar", force=True)
  2441. # test if we actually changed the file
  2442. with self.repo.get_named_file("HEAD") as f:
  2443. new_ref = f.read()
  2444. self.assertEqual(new_ref, b"ref: refs/heads/force_foobar\n")
  2445. def test_set_symbolic_ref(self) -> None:
  2446. _c1, _c2, c3 = build_commit_graph(
  2447. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2448. )
  2449. self.repo.refs[b"HEAD"] = c3.id
  2450. porcelain.symbolic_ref(self.repo.path, b"master")
  2451. def test_set_symbolic_ref_other_than_master(self) -> None:
  2452. _c1, _c2, c3 = build_commit_graph(
  2453. self.repo.object_store,
  2454. [[1], [2, 1], [3, 1, 2]],
  2455. attrs=dict(refs="develop"),
  2456. )
  2457. self.repo.refs[b"HEAD"] = c3.id
  2458. self.repo.refs[b"refs/heads/develop"] = c3.id
  2459. porcelain.symbolic_ref(self.repo.path, b"develop")
  2460. # test if we actually changed the file
  2461. with self.repo.get_named_file("HEAD") as f:
  2462. new_ref = f.read()
  2463. self.assertEqual(new_ref, b"ref: refs/heads/develop\n")
  2464. class DiffTreeTests(PorcelainTestCase):
  2465. def test_empty(self) -> None:
  2466. _c1, c2, c3 = build_commit_graph(
  2467. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2468. )
  2469. self.repo.refs[b"HEAD"] = c3.id
  2470. outstream = BytesIO()
  2471. porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream)
  2472. self.assertEqual(outstream.getvalue(), b"")
  2473. class DiffTests(PorcelainTestCase):
  2474. def test_diff_uncommitted_stage(self) -> None:
  2475. # Test diff in repository with no commits yet
  2476. fullpath = os.path.join(self.repo.path, "test.txt")
  2477. with open(fullpath, "w") as f:
  2478. f.write("Hello, world!\n")
  2479. porcelain.add(self.repo.path, paths=["test.txt"])
  2480. outstream = BytesIO()
  2481. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2482. diff_output = outstream.getvalue()
  2483. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2484. self.assertIn(b"new file mode", diff_output)
  2485. self.assertIn(b"+Hello, world!", diff_output)
  2486. def test_diff_uncommitted_working_tree(self) -> None:
  2487. # Test unstaged changes in repository with no commits
  2488. fullpath = os.path.join(self.repo.path, "test.txt")
  2489. with open(fullpath, "w") as f:
  2490. f.write("Hello, world!\n")
  2491. porcelain.add(self.repo.path, paths=["test.txt"])
  2492. # Modify file in working tree
  2493. with open(fullpath, "w") as f:
  2494. f.write("Hello, world!\nNew line\n")
  2495. outstream = BytesIO()
  2496. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2497. diff_output = outstream.getvalue()
  2498. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2499. self.assertIn(b"+New line", diff_output)
  2500. def test_diff_with_commits_staged(self) -> None:
  2501. # Test staged changes with existing commits
  2502. fullpath = os.path.join(self.repo.path, "test.txt")
  2503. with open(fullpath, "w") as f:
  2504. f.write("Initial content\n")
  2505. porcelain.add(self.repo.path, paths=["test.txt"])
  2506. porcelain.commit(self.repo.path, message=b"Initial commit")
  2507. # Modify and stage
  2508. with open(fullpath, "w") as f:
  2509. f.write("Initial content\nModified\n")
  2510. porcelain.add(self.repo.path, paths=["test.txt"])
  2511. outstream = BytesIO()
  2512. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2513. diff_output = outstream.getvalue()
  2514. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2515. self.assertIn(b"+Modified", diff_output)
  2516. def test_diff_with_commits_unstaged(self) -> None:
  2517. # Test unstaged changes with existing commits
  2518. fullpath = os.path.join(self.repo.path, "test.txt")
  2519. with open(fullpath, "w") as f:
  2520. f.write("Initial content\n")
  2521. porcelain.add(self.repo.path, paths=["test.txt"])
  2522. porcelain.commit(self.repo.path, message=b"Initial commit")
  2523. # Modify without staging
  2524. with open(fullpath, "w") as f:
  2525. f.write("Initial content\nModified\n")
  2526. outstream = BytesIO()
  2527. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2528. diff_output = outstream.getvalue()
  2529. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2530. self.assertIn(b"+Modified", diff_output)
  2531. def test_diff_file_deletion(self) -> None:
  2532. # Test showing file deletion
  2533. fullpath = os.path.join(self.repo.path, "test.txt")
  2534. with open(fullpath, "w") as f:
  2535. f.write("Content to delete\n")
  2536. porcelain.add(self.repo.path, paths=["test.txt"])
  2537. porcelain.commit(self.repo.path, message=b"Add file")
  2538. # Delete file
  2539. os.unlink(fullpath)
  2540. outstream = BytesIO()
  2541. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2542. diff_output = outstream.getvalue()
  2543. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2544. self.assertIn(b"deleted file mode", diff_output)
  2545. self.assertIn(b"-Content to delete", diff_output)
  2546. def test_diff_with_paths(self) -> None:
  2547. # Test diff with specific paths
  2548. # Create two files
  2549. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2550. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2551. with open(fullpath1, "w") as f:
  2552. f.write("File 1 content\n")
  2553. with open(fullpath2, "w") as f:
  2554. f.write("File 2 content\n")
  2555. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2556. porcelain.commit(self.repo.path, message=b"Add two files")
  2557. # Modify both files
  2558. with open(fullpath1, "w") as f:
  2559. f.write("File 1 modified\n")
  2560. with open(fullpath2, "w") as f:
  2561. f.write("File 2 modified\n")
  2562. # Test diff with specific path
  2563. outstream = BytesIO()
  2564. porcelain.diff(self.repo.path, paths=["file1.txt"], outstream=outstream)
  2565. diff_output = outstream.getvalue()
  2566. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2567. self.assertIn(b"-File 1 content", diff_output)
  2568. self.assertIn(b"+File 1 modified", diff_output)
  2569. # file2.txt should not appear in diff
  2570. self.assertNotIn(b"file2.txt", diff_output)
  2571. def test_diff_with_paths_multiple(self) -> None:
  2572. # Test diff with multiple paths
  2573. # Create three files
  2574. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2575. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2576. fullpath3 = os.path.join(self.repo.path, "file3.txt")
  2577. with open(fullpath1, "w") as f:
  2578. f.write("File 1 content\n")
  2579. with open(fullpath2, "w") as f:
  2580. f.write("File 2 content\n")
  2581. with open(fullpath3, "w") as f:
  2582. f.write("File 3 content\n")
  2583. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt", "file3.txt"])
  2584. porcelain.commit(self.repo.path, message=b"Add three files")
  2585. # Modify all files
  2586. with open(fullpath1, "w") as f:
  2587. f.write("File 1 modified\n")
  2588. with open(fullpath2, "w") as f:
  2589. f.write("File 2 modified\n")
  2590. with open(fullpath3, "w") as f:
  2591. f.write("File 3 modified\n")
  2592. # Test diff with two specific paths
  2593. outstream = BytesIO()
  2594. porcelain.diff(
  2595. self.repo.path, paths=["file1.txt", "file3.txt"], outstream=outstream
  2596. )
  2597. diff_output = outstream.getvalue()
  2598. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2599. self.assertIn(b"diff --git a/file3.txt b/file3.txt", diff_output)
  2600. # file2.txt should not appear in diff
  2601. self.assertNotIn(b"file2.txt", diff_output)
  2602. def test_diff_with_paths_directory(self) -> None:
  2603. # Test diff with directory paths
  2604. # Create files in subdirectory
  2605. os.mkdir(os.path.join(self.repo.path, "subdir"))
  2606. fullpath1 = os.path.join(self.repo.path, "subdir", "file1.txt")
  2607. fullpath2 = os.path.join(self.repo.path, "subdir", "file2.txt")
  2608. fullpath3 = os.path.join(self.repo.path, "root.txt")
  2609. with open(fullpath1, "w") as f:
  2610. f.write("Subdir file 1\n")
  2611. with open(fullpath2, "w") as f:
  2612. f.write("Subdir file 2\n")
  2613. with open(fullpath3, "w") as f:
  2614. f.write("Root file\n")
  2615. porcelain.add(
  2616. self.repo.path, paths=["subdir/file1.txt", "subdir/file2.txt", "root.txt"]
  2617. )
  2618. porcelain.commit(self.repo.path, message=b"Add files in subdir")
  2619. # Modify all files
  2620. with open(fullpath1, "w") as f:
  2621. f.write("Subdir file 1 modified\n")
  2622. with open(fullpath2, "w") as f:
  2623. f.write("Subdir file 2 modified\n")
  2624. with open(fullpath3, "w") as f:
  2625. f.write("Root file modified\n")
  2626. # Test diff with directory path
  2627. outstream = BytesIO()
  2628. porcelain.diff(self.repo.path, paths=["subdir"], outstream=outstream)
  2629. diff_output = outstream.getvalue()
  2630. self.assertIn(b"subdir/file1.txt", diff_output)
  2631. self.assertIn(b"subdir/file2.txt", diff_output)
  2632. # root.txt should not appear in diff
  2633. self.assertNotIn(b"root.txt", diff_output)
  2634. def test_diff_staged_with_paths(self) -> None:
  2635. # Test staged diff with specific paths
  2636. # Create two files
  2637. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2638. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2639. with open(fullpath1, "w") as f:
  2640. f.write("File 1 content\n")
  2641. with open(fullpath2, "w") as f:
  2642. f.write("File 2 content\n")
  2643. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2644. porcelain.commit(self.repo.path, message=b"Add two files")
  2645. # Modify and stage both files
  2646. with open(fullpath1, "w") as f:
  2647. f.write("File 1 staged\n")
  2648. with open(fullpath2, "w") as f:
  2649. f.write("File 2 staged\n")
  2650. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2651. # Test staged diff with specific path
  2652. outstream = BytesIO()
  2653. porcelain.diff(
  2654. self.repo.path, staged=True, paths=["file1.txt"], outstream=outstream
  2655. )
  2656. diff_output = outstream.getvalue()
  2657. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2658. self.assertIn(b"-File 1 content", diff_output)
  2659. self.assertIn(b"+File 1 staged", diff_output)
  2660. # file2.txt should not appear in diff
  2661. self.assertNotIn(b"file2.txt", diff_output)
  2662. def test_diff_with_commit_and_paths(self) -> None:
  2663. # Test diff against specific commit with paths
  2664. # Create initial file
  2665. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2666. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2667. with open(fullpath1, "w") as f:
  2668. f.write("Initial content 1\n")
  2669. with open(fullpath2, "w") as f:
  2670. f.write("Initial content 2\n")
  2671. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2672. first_commit = porcelain.commit(self.repo.path, message=b"Initial commit")
  2673. # Make second commit
  2674. with open(fullpath1, "w") as f:
  2675. f.write("Second content 1\n")
  2676. with open(fullpath2, "w") as f:
  2677. f.write("Second content 2\n")
  2678. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2679. porcelain.commit(self.repo.path, message=b"Second commit")
  2680. # Modify working tree
  2681. with open(fullpath1, "w") as f:
  2682. f.write("Working content 1\n")
  2683. with open(fullpath2, "w") as f:
  2684. f.write("Working content 2\n")
  2685. # Test diff against first commit with specific path
  2686. outstream = BytesIO()
  2687. porcelain.diff(
  2688. self.repo.path,
  2689. commit=first_commit,
  2690. paths=["file1.txt"],
  2691. outstream=outstream,
  2692. )
  2693. diff_output = outstream.getvalue()
  2694. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2695. self.assertIn(b"-Initial content 1", diff_output)
  2696. self.assertIn(b"+Working content 1", diff_output)
  2697. # file2.txt should not appear in diff
  2698. self.assertNotIn(b"file2.txt", diff_output)
  2699. class CommitTreeTests(PorcelainTestCase):
  2700. def test_simple(self) -> None:
  2701. _c1, _c2, _c3 = build_commit_graph(
  2702. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2703. )
  2704. b = Blob()
  2705. b.data = b"foo the bar"
  2706. t = Tree()
  2707. t.add(b"somename", 0o100644, b.id)
  2708. self.repo.object_store.add_object(t)
  2709. self.repo.object_store.add_object(b)
  2710. sha = porcelain.commit_tree(
  2711. self.repo.path,
  2712. t.id,
  2713. message=b"Withcommit.",
  2714. author=b"Joe <joe@example.com>",
  2715. committer=b"Jane <jane@example.com>",
  2716. )
  2717. self.assertIsInstance(sha, bytes)
  2718. self.assertEqual(len(sha), 40)
  2719. class RevListTests(PorcelainTestCase):
  2720. def test_simple(self) -> None:
  2721. c1, c2, c3 = build_commit_graph(
  2722. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2723. )
  2724. outstream = BytesIO()
  2725. porcelain.rev_list(self.repo.path, [c3.id], outstream=outstream)
  2726. self.assertEqual(
  2727. c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue()
  2728. )
  2729. @skipIf(
  2730. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  2731. "gpgme not easily available or supported on Windows and PyPy",
  2732. )
  2733. class TagCreateSignTests(PorcelainGpgTestCase):
  2734. def test_default_key(self) -> None:
  2735. _c1, _c2, c3 = build_commit_graph(
  2736. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2737. )
  2738. self.repo.refs[b"HEAD"] = c3.id
  2739. cfg = self.repo.get_config()
  2740. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2741. self.import_default_key()
  2742. porcelain.tag_create(
  2743. self.repo.path,
  2744. b"tryme",
  2745. b"foo <foo@bar.com>",
  2746. b"bar",
  2747. annotated=True,
  2748. sign=True,
  2749. )
  2750. tags = self.repo.refs.as_dict(b"refs/tags")
  2751. self.assertEqual(list(tags.keys()), [b"tryme"])
  2752. tag = self.repo[b"refs/tags/tryme"]
  2753. self.assertIsInstance(tag, Tag)
  2754. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2755. self.assertEqual(b"bar\n", tag.message)
  2756. self.assertRecentTimestamp(tag.tag_time)
  2757. tag = self.repo[b"refs/tags/tryme"]
  2758. assert isinstance(tag, Tag)
  2759. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2760. tag.verify()
  2761. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2762. self.import_non_default_key()
  2763. self.assertRaises(
  2764. gpg.errors.MissingSignatures,
  2765. tag.verify,
  2766. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  2767. )
  2768. assert tag.signature is not None
  2769. tag._chunked_text = [b"bad data", tag.signature]
  2770. self.assertRaises(
  2771. gpg.errors.BadSignatures,
  2772. tag.verify,
  2773. )
  2774. def test_non_default_key(self) -> None:
  2775. _c1, _c2, c3 = build_commit_graph(
  2776. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2777. )
  2778. self.repo.refs[b"HEAD"] = c3.id
  2779. cfg = self.repo.get_config()
  2780. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2781. self.import_non_default_key()
  2782. porcelain.tag_create(
  2783. self.repo.path,
  2784. b"tryme",
  2785. b"foo <foo@bar.com>",
  2786. b"bar",
  2787. annotated=True,
  2788. sign=True,
  2789. )
  2790. tags = self.repo.refs.as_dict(b"refs/tags")
  2791. self.assertEqual(list(tags.keys()), [b"tryme"])
  2792. tag = self.repo[b"refs/tags/tryme"]
  2793. self.assertIsInstance(tag, Tag)
  2794. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2795. self.assertEqual(b"bar\n", tag.message)
  2796. self.assertRecentTimestamp(tag.tag_time)
  2797. tag = self.repo[b"refs/tags/tryme"]
  2798. assert isinstance(tag, Tag)
  2799. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2800. tag.verify()
  2801. def test_sign_uses_config_signingkey(self) -> None:
  2802. """Test that sign=True uses user.signingKey from config."""
  2803. _c1, _c2, c3 = build_commit_graph(
  2804. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2805. )
  2806. self.repo.refs[b"HEAD"] = c3.id
  2807. # Set up user.signingKey in config
  2808. cfg = self.repo.get_config()
  2809. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2810. cfg.write_to_path()
  2811. self.import_default_key()
  2812. # Create tag with sign=True (should use signingKey from config)
  2813. porcelain.tag_create(
  2814. self.repo.path,
  2815. b"signed-tag",
  2816. b"foo <foo@bar.com>",
  2817. b"Tag with configured key",
  2818. annotated=True,
  2819. sign=True, # This should read user.signingKey from config
  2820. )
  2821. tags = self.repo.refs.as_dict(b"refs/tags")
  2822. self.assertEqual(list(tags.keys()), [b"signed-tag"])
  2823. tag = self.repo[b"refs/tags/signed-tag"]
  2824. self.assertIsInstance(tag, Tag)
  2825. # Verify the tag is signed with the configured key
  2826. tag.verify()
  2827. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2828. def test_tag_gpg_sign_config_enabled(self) -> None:
  2829. """Test that tag.gpgSign=true automatically signs tags."""
  2830. _c1, _c2, c3 = build_commit_graph(
  2831. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2832. )
  2833. self.repo.refs[b"HEAD"] = c3.id
  2834. # Set up user.signingKey and tag.gpgSign in config
  2835. cfg = self.repo.get_config()
  2836. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2837. cfg.set(("tag",), "gpgSign", True)
  2838. cfg.write_to_path()
  2839. self.import_default_key()
  2840. # Create tag without explicit sign parameter (should auto-sign due to config)
  2841. porcelain.tag_create(
  2842. self.repo.path,
  2843. b"auto-signed-tag",
  2844. b"foo <foo@bar.com>",
  2845. b"Auto-signed tag",
  2846. annotated=True,
  2847. # No sign parameter - should use tag.gpgSign config
  2848. )
  2849. tags = self.repo.refs.as_dict(b"refs/tags")
  2850. self.assertEqual(list(tags.keys()), [b"auto-signed-tag"])
  2851. tag = self.repo[b"refs/tags/auto-signed-tag"]
  2852. self.assertIsInstance(tag, Tag)
  2853. # Verify the tag is signed due to config
  2854. tag.verify()
  2855. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2856. def test_tag_gpg_sign_config_disabled(self) -> None:
  2857. """Test that tag.gpgSign=false does not sign tags."""
  2858. _c1, _c2, c3 = build_commit_graph(
  2859. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2860. )
  2861. self.repo.refs[b"HEAD"] = c3.id
  2862. # Set up user.signingKey and tag.gpgSign=false in config
  2863. cfg = self.repo.get_config()
  2864. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2865. cfg.set(("tag",), "gpgSign", False)
  2866. cfg.write_to_path()
  2867. self.import_default_key()
  2868. # Create tag without explicit sign parameter (should not sign)
  2869. porcelain.tag_create(
  2870. self.repo.path,
  2871. b"unsigned-tag",
  2872. b"foo <foo@bar.com>",
  2873. b"Unsigned tag",
  2874. annotated=True,
  2875. # No sign parameter - should use tag.gpgSign=false config
  2876. )
  2877. tags = self.repo.refs.as_dict(b"refs/tags")
  2878. self.assertEqual(list(tags.keys()), [b"unsigned-tag"])
  2879. tag = self.repo[b"refs/tags/unsigned-tag"]
  2880. self.assertIsInstance(tag, Tag)
  2881. # Verify the tag is not signed
  2882. self.assertIsNone(tag._signature)
  2883. def test_tag_gpg_sign_config_no_signing_key(self) -> None:
  2884. """Test that tag.gpgSign=true works without user.signingKey (uses default)."""
  2885. _c1, _c2, c3 = build_commit_graph(
  2886. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2887. )
  2888. self.repo.refs[b"HEAD"] = c3.id
  2889. # Set up tag.gpgSign but no user.signingKey
  2890. cfg = self.repo.get_config()
  2891. cfg.set(("tag",), "gpgSign", True)
  2892. cfg.write_to_path()
  2893. self.import_default_key()
  2894. # Create tag without explicit sign parameter (should auto-sign with default key)
  2895. porcelain.tag_create(
  2896. self.repo.path,
  2897. b"default-signed-tag",
  2898. b"foo <foo@bar.com>",
  2899. b"Default signed tag",
  2900. annotated=True,
  2901. # No sign parameter - should use tag.gpgSign config with default key
  2902. )
  2903. tags = self.repo.refs.as_dict(b"refs/tags")
  2904. self.assertEqual(list(tags.keys()), [b"default-signed-tag"])
  2905. tag = self.repo[b"refs/tags/default-signed-tag"]
  2906. self.assertIsInstance(tag, Tag)
  2907. # Verify the tag is signed with default key
  2908. tag.verify()
  2909. def test_explicit_sign_overrides_config(self) -> None:
  2910. """Test that explicit sign parameter overrides tag.gpgSign config."""
  2911. _c1, _c2, c3 = build_commit_graph(
  2912. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2913. )
  2914. self.repo.refs[b"HEAD"] = c3.id
  2915. # Set up tag.gpgSign=false but explicitly pass sign=True
  2916. cfg = self.repo.get_config()
  2917. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2918. cfg.set(("tag",), "gpgSign", False)
  2919. cfg.write_to_path()
  2920. self.import_default_key()
  2921. # Create tag with explicit sign=True (should override config)
  2922. porcelain.tag_create(
  2923. self.repo.path,
  2924. b"explicit-signed-tag",
  2925. b"foo <foo@bar.com>",
  2926. b"Explicitly signed tag",
  2927. annotated=True,
  2928. sign=True, # This should override tag.gpgSign=false
  2929. )
  2930. tags = self.repo.refs.as_dict(b"refs/tags")
  2931. self.assertEqual(list(tags.keys()), [b"explicit-signed-tag"])
  2932. tag = self.repo[b"refs/tags/explicit-signed-tag"]
  2933. self.assertIsInstance(tag, Tag)
  2934. # Verify the tag is signed despite config=false
  2935. tag.verify()
  2936. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2937. def test_explicit_false_disables_tag_signing(self) -> None:
  2938. """Test that explicit sign=False disables signing even with config=true."""
  2939. _c1, _c2, c3 = build_commit_graph(
  2940. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2941. )
  2942. self.repo.refs[b"HEAD"] = c3.id
  2943. # Set up tag.gpgSign=true but explicitly pass sign=False
  2944. cfg = self.repo.get_config()
  2945. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2946. cfg.set(("tag",), "gpgSign", True)
  2947. cfg.write_to_path()
  2948. self.import_default_key()
  2949. # Create tag with explicit sign=False (should disable signing)
  2950. porcelain.tag_create(
  2951. self.repo.path,
  2952. b"explicit-unsigned-tag",
  2953. b"foo <foo@bar.com>",
  2954. b"Explicitly unsigned tag",
  2955. annotated=True,
  2956. sign=False, # This should override tag.gpgSign=true
  2957. )
  2958. tags = self.repo.refs.as_dict(b"refs/tags")
  2959. self.assertEqual(list(tags.keys()), [b"explicit-unsigned-tag"])
  2960. tag = self.repo[b"refs/tags/explicit-unsigned-tag"]
  2961. self.assertIsInstance(tag, Tag)
  2962. # Verify the tag is NOT signed despite config=true
  2963. self.assertIsNone(tag._signature)
  2964. class TagCreateTests(PorcelainTestCase):
  2965. def test_annotated(self) -> None:
  2966. _c1, _c2, c3 = build_commit_graph(
  2967. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2968. )
  2969. self.repo.refs[b"HEAD"] = c3.id
  2970. porcelain.tag_create(
  2971. self.repo.path,
  2972. b"tryme",
  2973. b"foo <foo@bar.com>",
  2974. b"bar",
  2975. annotated=True,
  2976. )
  2977. tags = self.repo.refs.as_dict(b"refs/tags")
  2978. self.assertEqual(list(tags.keys()), [b"tryme"])
  2979. tag = self.repo[b"refs/tags/tryme"]
  2980. self.assertIsInstance(tag, Tag)
  2981. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2982. self.assertEqual(b"bar\n", tag.message)
  2983. self.assertRecentTimestamp(tag.tag_time)
  2984. def test_unannotated(self) -> None:
  2985. _c1, _c2, c3 = build_commit_graph(
  2986. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2987. )
  2988. self.repo.refs[b"HEAD"] = c3.id
  2989. porcelain.tag_create(self.repo.path, b"tryme", annotated=False)
  2990. tags = self.repo.refs.as_dict(b"refs/tags")
  2991. self.assertEqual(list(tags.keys()), [b"tryme"])
  2992. self.repo[b"refs/tags/tryme"]
  2993. self.assertEqual(list(tags.values()), [self.repo.head()])
  2994. def test_unannotated_unicode(self) -> None:
  2995. _c1, _c2, c3 = build_commit_graph(
  2996. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2997. )
  2998. self.repo.refs[b"HEAD"] = c3.id
  2999. porcelain.tag_create(self.repo.path, "tryme", annotated=False)
  3000. tags = self.repo.refs.as_dict(b"refs/tags")
  3001. self.assertEqual(list(tags.keys()), [b"tryme"])
  3002. self.repo[b"refs/tags/tryme"]
  3003. self.assertEqual(list(tags.values()), [self.repo.head()])
  3004. class TagListTests(PorcelainTestCase):
  3005. def test_empty(self) -> None:
  3006. tags = porcelain.tag_list(self.repo.path)
  3007. self.assertEqual([], tags)
  3008. def test_simple(self) -> None:
  3009. self.repo.refs[b"refs/tags/foo"] = b"aa" * 20
  3010. self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20
  3011. tags = porcelain.tag_list(self.repo.path)
  3012. self.assertEqual([b"bar/bla", b"foo"], tags)
  3013. class TagDeleteTests(PorcelainTestCase):
  3014. def test_simple(self) -> None:
  3015. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3016. self.repo[b"HEAD"] = c1.id
  3017. porcelain.tag_create(self.repo, b"foo")
  3018. self.assertIn(b"foo", porcelain.tag_list(self.repo))
  3019. porcelain.tag_delete(self.repo, b"foo")
  3020. self.assertNotIn(b"foo", porcelain.tag_list(self.repo))
  3021. class ResetTests(PorcelainTestCase):
  3022. def test_hard_head(self) -> None:
  3023. fullpath = os.path.join(self.repo.path, "foo")
  3024. with open(fullpath, "w") as f:
  3025. f.write("BAR")
  3026. porcelain.add(self.repo.path, paths=[fullpath])
  3027. porcelain.commit(
  3028. self.repo.path,
  3029. message=b"Some message",
  3030. committer=b"Jane <jane@example.com>",
  3031. author=b"John <john@example.com>",
  3032. )
  3033. with open(os.path.join(self.repo.path, "foo"), "wb") as f:
  3034. f.write(b"OOH")
  3035. porcelain.reset(self.repo, "hard", b"HEAD")
  3036. index = self.repo.open_index()
  3037. changes = list(
  3038. tree_changes(
  3039. self.repo.object_store,
  3040. index.commit(self.repo.object_store),
  3041. self.repo[b"HEAD"].tree,
  3042. )
  3043. )
  3044. self.assertEqual([], changes)
  3045. def test_hard_commit(self) -> None:
  3046. fullpath = os.path.join(self.repo.path, "foo")
  3047. with open(fullpath, "w") as f:
  3048. f.write("BAR")
  3049. porcelain.add(self.repo.path, paths=[fullpath])
  3050. sha = porcelain.commit(
  3051. self.repo.path,
  3052. message=b"Some message",
  3053. committer=b"Jane <jane@example.com>",
  3054. author=b"John <john@example.com>",
  3055. )
  3056. with open(fullpath, "wb") as f:
  3057. f.write(b"BAZ")
  3058. porcelain.add(self.repo.path, paths=[fullpath])
  3059. porcelain.commit(
  3060. self.repo.path,
  3061. message=b"Some other message",
  3062. committer=b"Jane <jane@example.com>",
  3063. author=b"John <john@example.com>",
  3064. )
  3065. porcelain.reset(self.repo, "hard", sha)
  3066. index = self.repo.open_index()
  3067. changes = list(
  3068. tree_changes(
  3069. self.repo.object_store,
  3070. index.commit(self.repo.object_store),
  3071. self.repo[sha].tree,
  3072. )
  3073. )
  3074. self.assertEqual([], changes)
  3075. def test_hard_commit_short_hash(self) -> None:
  3076. fullpath = os.path.join(self.repo.path, "foo")
  3077. with open(fullpath, "w") as f:
  3078. f.write("BAR")
  3079. porcelain.add(self.repo.path, paths=[fullpath])
  3080. sha = porcelain.commit(
  3081. self.repo.path,
  3082. message=b"Some message",
  3083. committer=b"Jane <jane@example.com>",
  3084. author=b"John <john@example.com>",
  3085. )
  3086. with open(fullpath, "wb") as f:
  3087. f.write(b"BAZ")
  3088. porcelain.add(self.repo.path, paths=[fullpath])
  3089. porcelain.commit(
  3090. self.repo.path,
  3091. message=b"Some other message",
  3092. committer=b"Jane <jane@example.com>",
  3093. author=b"John <john@example.com>",
  3094. )
  3095. # Test with short hash (7 characters)
  3096. short_sha = sha[:7].decode("ascii")
  3097. porcelain.reset(self.repo, "hard", short_sha)
  3098. index = self.repo.open_index()
  3099. changes = list(
  3100. tree_changes(
  3101. self.repo.object_store,
  3102. index.commit(self.repo.object_store),
  3103. self.repo[sha].tree,
  3104. )
  3105. )
  3106. self.assertEqual([], changes)
  3107. def test_hard_deletes_untracked_files(self) -> None:
  3108. """Test that reset --hard deletes files that don't exist in target tree."""
  3109. # Create and commit a file
  3110. fullpath = os.path.join(self.repo.path, "foo")
  3111. with open(fullpath, "w") as f:
  3112. f.write("BAR")
  3113. porcelain.add(self.repo.path, paths=[fullpath])
  3114. sha1 = porcelain.commit(
  3115. self.repo.path,
  3116. message=b"First commit",
  3117. committer=b"Jane <jane@example.com>",
  3118. author=b"John <john@example.com>",
  3119. )
  3120. # Create another file and commit
  3121. fullpath2 = os.path.join(self.repo.path, "bar")
  3122. with open(fullpath2, "w") as f:
  3123. f.write("BAZ")
  3124. porcelain.add(self.repo.path, paths=[fullpath2])
  3125. porcelain.commit(
  3126. self.repo.path,
  3127. message=b"Second commit",
  3128. committer=b"Jane <jane@example.com>",
  3129. author=b"John <john@example.com>",
  3130. )
  3131. # Reset hard to first commit - this should delete 'bar'
  3132. porcelain.reset(self.repo, "hard", sha1)
  3133. # Check that 'foo' still exists and 'bar' is deleted
  3134. self.assertTrue(os.path.exists(fullpath))
  3135. self.assertFalse(os.path.exists(fullpath2))
  3136. # Check index matches first commit
  3137. index = self.repo.open_index()
  3138. self.assertIn(b"foo", index)
  3139. self.assertNotIn(b"bar", index)
  3140. def test_hard_deletes_files_in_subdirs(self) -> None:
  3141. """Test that reset --hard deletes files in subdirectories."""
  3142. # Create and commit files in subdirectory
  3143. subdir = os.path.join(self.repo.path, "subdir")
  3144. os.makedirs(subdir)
  3145. file1 = os.path.join(subdir, "file1")
  3146. file2 = os.path.join(subdir, "file2")
  3147. with open(file1, "w") as f:
  3148. f.write("content1")
  3149. with open(file2, "w") as f:
  3150. f.write("content2")
  3151. porcelain.add(self.repo.path, paths=[file1, file2])
  3152. porcelain.commit(
  3153. self.repo.path,
  3154. message=b"First commit",
  3155. committer=b"Jane <jane@example.com>",
  3156. author=b"John <john@example.com>",
  3157. )
  3158. # Remove one file from subdirectory and commit
  3159. porcelain.rm(self.repo.path, paths=[file2])
  3160. sha2 = porcelain.commit(
  3161. self.repo.path,
  3162. message=b"Remove file2",
  3163. committer=b"Jane <jane@example.com>",
  3164. author=b"John <john@example.com>",
  3165. )
  3166. # Create file2 again (untracked)
  3167. with open(file2, "w") as f:
  3168. f.write("new content")
  3169. # Reset to commit that has file2 removed - untracked file2 should remain
  3170. porcelain.reset(self.repo, "hard", sha2)
  3171. self.assertTrue(os.path.exists(file1))
  3172. # Untracked files are not removed by reset --hard
  3173. self.assertTrue(os.path.exists(file2))
  3174. def test_hard_reset_to_remote_branch(self) -> None:
  3175. """Test reset --hard to remote branch deletes local files not in remote."""
  3176. # Create a file and commit
  3177. file1 = os.path.join(self.repo.path, "file1")
  3178. with open(file1, "w") as f:
  3179. f.write("content1")
  3180. porcelain.add(self.repo.path, paths=[file1])
  3181. sha1 = porcelain.commit(
  3182. self.repo.path,
  3183. message=b"Initial commit",
  3184. committer=b"Jane <jane@example.com>",
  3185. author=b"John <john@example.com>",
  3186. )
  3187. # Create a "remote" ref that doesn't have additional files
  3188. self.repo.refs[b"refs/remotes/origin/master"] = sha1
  3189. # Add another file locally and commit
  3190. file2 = os.path.join(self.repo.path, "file2")
  3191. with open(file2, "w") as f:
  3192. f.write("content2")
  3193. porcelain.add(self.repo.path, paths=[file2])
  3194. porcelain.commit(
  3195. self.repo.path,
  3196. message=b"Add file2",
  3197. committer=b"Jane <jane@example.com>",
  3198. author=b"John <john@example.com>",
  3199. )
  3200. # Both files should exist
  3201. self.assertTrue(os.path.exists(file1))
  3202. self.assertTrue(os.path.exists(file2))
  3203. # Reset to remote branch - should delete file2
  3204. porcelain.reset(self.repo, "hard", b"refs/remotes/origin/master")
  3205. # file1 should exist, file2 should be deleted
  3206. self.assertTrue(os.path.exists(file1))
  3207. self.assertFalse(os.path.exists(file2))
  3208. def test_mixed_reset(self) -> None:
  3209. # Create initial commit
  3210. fullpath = os.path.join(self.repo.path, "foo")
  3211. with open(fullpath, "w") as f:
  3212. f.write("BAR")
  3213. porcelain.add(self.repo.path, paths=[fullpath])
  3214. first_sha = porcelain.commit(
  3215. self.repo.path,
  3216. message=b"First commit",
  3217. committer=b"Jane <jane@example.com>",
  3218. author=b"John <john@example.com>",
  3219. )
  3220. # Make second commit with modified content
  3221. with open(fullpath, "w") as f:
  3222. f.write("BAZ")
  3223. porcelain.add(self.repo.path, paths=[fullpath])
  3224. porcelain.commit(
  3225. self.repo.path,
  3226. message=b"Second commit",
  3227. committer=b"Jane <jane@example.com>",
  3228. author=b"John <john@example.com>",
  3229. )
  3230. # Modify working tree without staging
  3231. with open(fullpath, "w") as f:
  3232. f.write("MODIFIED")
  3233. # Mixed reset to first commit
  3234. porcelain.reset(self.repo, "mixed", first_sha)
  3235. # Check that HEAD points to first commit
  3236. self.assertEqual(self.repo.head(), first_sha)
  3237. # Check that index matches first commit
  3238. index = self.repo.open_index()
  3239. changes = list(
  3240. tree_changes(
  3241. self.repo.object_store,
  3242. index.commit(self.repo.object_store),
  3243. self.repo[first_sha].tree,
  3244. )
  3245. )
  3246. self.assertEqual([], changes)
  3247. # Check that working tree is unchanged (still has "MODIFIED")
  3248. with open(fullpath) as f:
  3249. self.assertEqual(f.read(), "MODIFIED")
  3250. def test_soft_reset(self) -> None:
  3251. # Create initial commit
  3252. fullpath = os.path.join(self.repo.path, "foo")
  3253. with open(fullpath, "w") as f:
  3254. f.write("BAR")
  3255. porcelain.add(self.repo.path, paths=[fullpath])
  3256. first_sha = porcelain.commit(
  3257. self.repo.path,
  3258. message=b"First commit",
  3259. committer=b"Jane <jane@example.com>",
  3260. author=b"John <john@example.com>",
  3261. )
  3262. # Make second commit with modified content
  3263. with open(fullpath, "w") as f:
  3264. f.write("BAZ")
  3265. porcelain.add(self.repo.path, paths=[fullpath])
  3266. porcelain.commit(
  3267. self.repo.path,
  3268. message=b"Second commit",
  3269. committer=b"Jane <jane@example.com>",
  3270. author=b"John <john@example.com>",
  3271. )
  3272. # Stage a new change
  3273. with open(fullpath, "w") as f:
  3274. f.write("STAGED")
  3275. porcelain.add(self.repo.path, paths=[fullpath])
  3276. # Soft reset to first commit
  3277. porcelain.reset(self.repo, "soft", first_sha)
  3278. # Check that HEAD points to first commit
  3279. self.assertEqual(self.repo.head(), first_sha)
  3280. # Check that index still has the staged change (not reset)
  3281. index = self.repo.open_index()
  3282. # The index should still contain the staged content, not the first commit's content
  3283. self.assertIn(b"foo", index)
  3284. # Check that working tree is unchanged
  3285. with open(fullpath) as f:
  3286. self.assertEqual(f.read(), "STAGED")
  3287. class ResetFileTests(PorcelainTestCase):
  3288. def test_reset_modify_file_to_commit(self) -> None:
  3289. file = "foo"
  3290. full_path = os.path.join(self.repo.path, file)
  3291. with open(full_path, "w") as f:
  3292. f.write("hello")
  3293. porcelain.add(self.repo, paths=[full_path])
  3294. sha = porcelain.commit(
  3295. self.repo,
  3296. message=b"unitest",
  3297. committer=b"Jane <jane@example.com>",
  3298. author=b"John <john@example.com>",
  3299. )
  3300. with open(full_path, "a") as f:
  3301. f.write("something new")
  3302. porcelain.reset_file(self.repo, file, target=sha)
  3303. with open(full_path) as f:
  3304. self.assertEqual("hello", f.read())
  3305. def test_reset_remove_file_to_commit(self) -> None:
  3306. file = "foo"
  3307. full_path = os.path.join(self.repo.path, file)
  3308. with open(full_path, "w") as f:
  3309. f.write("hello")
  3310. porcelain.add(self.repo, paths=[full_path])
  3311. sha = porcelain.commit(
  3312. self.repo,
  3313. message=b"unitest",
  3314. committer=b"Jane <jane@example.com>",
  3315. author=b"John <john@example.com>",
  3316. )
  3317. os.remove(full_path)
  3318. porcelain.reset_file(self.repo, file, target=sha)
  3319. with open(full_path) as f:
  3320. self.assertEqual("hello", f.read())
  3321. def test_resetfile_with_dir(self) -> None:
  3322. os.mkdir(os.path.join(self.repo.path, "new_dir"))
  3323. full_path = os.path.join(self.repo.path, "new_dir", "foo")
  3324. with open(full_path, "w") as f:
  3325. f.write("hello")
  3326. porcelain.add(self.repo, paths=[full_path])
  3327. sha = porcelain.commit(
  3328. self.repo,
  3329. message=b"unitest",
  3330. committer=b"Jane <jane@example.com>",
  3331. author=b"John <john@example.com>",
  3332. )
  3333. with open(full_path, "a") as f:
  3334. f.write("something new")
  3335. porcelain.commit(
  3336. self.repo,
  3337. message=b"unitest 2",
  3338. committer=b"Jane <jane@example.com>",
  3339. author=b"John <john@example.com>",
  3340. )
  3341. porcelain.reset_file(self.repo, os.path.join("new_dir", "foo"), target=sha)
  3342. with open(full_path) as f:
  3343. self.assertEqual("hello", f.read())
  3344. def _commit_file_with_content(repo, filename, content):
  3345. file_path = os.path.join(repo.path, filename)
  3346. with open(file_path, "w") as f:
  3347. f.write(content)
  3348. porcelain.add(repo, paths=[file_path])
  3349. sha = porcelain.commit(
  3350. repo,
  3351. message=b"add " + filename.encode(),
  3352. committer=b"Jane <jane@example.com>",
  3353. author=b"John <john@example.com>",
  3354. )
  3355. return sha, file_path
  3356. class RevertTests(PorcelainTestCase):
  3357. def test_revert_simple(self) -> None:
  3358. # Create initial commit
  3359. fullpath = os.path.join(self.repo.path, "foo")
  3360. with open(fullpath, "w") as f:
  3361. f.write("initial content\n")
  3362. porcelain.add(self.repo.path, paths=[fullpath])
  3363. porcelain.commit(
  3364. self.repo.path,
  3365. message=b"Initial commit",
  3366. committer=b"Jane <jane@example.com>",
  3367. author=b"John <john@example.com>",
  3368. )
  3369. # Make a change
  3370. with open(fullpath, "w") as f:
  3371. f.write("modified content\n")
  3372. porcelain.add(self.repo.path, paths=[fullpath])
  3373. change_sha = porcelain.commit(
  3374. self.repo.path,
  3375. message=b"Change content",
  3376. committer=b"Jane <jane@example.com>",
  3377. author=b"John <john@example.com>",
  3378. )
  3379. # Revert the change
  3380. revert_sha = porcelain.revert(self.repo.path, commits=[change_sha])
  3381. # Check the file content is back to initial
  3382. with open(fullpath) as f:
  3383. self.assertEqual("initial content\n", f.read())
  3384. # Check the revert commit message
  3385. revert_commit = self.repo[revert_sha]
  3386. self.assertIn(b'Revert "Change content"', revert_commit.message)
  3387. self.assertIn(change_sha[:7], revert_commit.message)
  3388. def test_revert_multiple(self) -> None:
  3389. # Create initial commit
  3390. fullpath = os.path.join(self.repo.path, "foo")
  3391. with open(fullpath, "w") as f:
  3392. f.write("line1\n")
  3393. porcelain.add(self.repo.path, paths=[fullpath])
  3394. porcelain.commit(
  3395. self.repo.path,
  3396. message=b"Initial commit",
  3397. committer=b"Jane <jane@example.com>",
  3398. author=b"John <john@example.com>",
  3399. )
  3400. # Add line2
  3401. with open(fullpath, "a") as f:
  3402. f.write("line2\n")
  3403. porcelain.add(self.repo.path, paths=[fullpath])
  3404. commit1 = porcelain.commit(
  3405. self.repo.path,
  3406. message=b"Add line2",
  3407. committer=b"Jane <jane@example.com>",
  3408. author=b"John <john@example.com>",
  3409. )
  3410. # Add line3
  3411. with open(fullpath, "a") as f:
  3412. f.write("line3\n")
  3413. porcelain.add(self.repo.path, paths=[fullpath])
  3414. commit2 = porcelain.commit(
  3415. self.repo.path,
  3416. message=b"Add line3",
  3417. committer=b"Jane <jane@example.com>",
  3418. author=b"John <john@example.com>",
  3419. )
  3420. # Revert both commits (in reverse order)
  3421. porcelain.revert(self.repo.path, commits=[commit2, commit1])
  3422. # Check file is back to initial state
  3423. with open(fullpath) as f:
  3424. self.assertEqual("line1\n", f.read())
  3425. def test_revert_no_commit(self) -> None:
  3426. # Create initial commit
  3427. fullpath = os.path.join(self.repo.path, "foo")
  3428. with open(fullpath, "w") as f:
  3429. f.write("initial\n")
  3430. porcelain.add(self.repo.path, paths=[fullpath])
  3431. porcelain.commit(
  3432. self.repo.path,
  3433. message=b"Initial",
  3434. committer=b"Jane <jane@example.com>",
  3435. author=b"John <john@example.com>",
  3436. )
  3437. # Make a change
  3438. with open(fullpath, "w") as f:
  3439. f.write("changed\n")
  3440. porcelain.add(self.repo.path, paths=[fullpath])
  3441. change_sha = porcelain.commit(
  3442. self.repo.path,
  3443. message=b"Change",
  3444. committer=b"Jane <jane@example.com>",
  3445. author=b"John <john@example.com>",
  3446. )
  3447. # Revert with no_commit
  3448. result = porcelain.revert(self.repo.path, commits=[change_sha], no_commit=True)
  3449. # Should return None
  3450. self.assertIsNone(result)
  3451. # File should be reverted
  3452. with open(fullpath) as f:
  3453. self.assertEqual("initial\n", f.read())
  3454. # HEAD should still point to the change commit
  3455. self.assertEqual(self.repo.refs[b"HEAD"], change_sha)
  3456. def test_revert_custom_message(self) -> None:
  3457. # Create commits
  3458. fullpath = os.path.join(self.repo.path, "foo")
  3459. with open(fullpath, "w") as f:
  3460. f.write("initial\n")
  3461. porcelain.add(self.repo.path, paths=[fullpath])
  3462. porcelain.commit(
  3463. self.repo.path,
  3464. message=b"Initial",
  3465. committer=b"Jane <jane@example.com>",
  3466. author=b"John <john@example.com>",
  3467. )
  3468. with open(fullpath, "w") as f:
  3469. f.write("changed\n")
  3470. porcelain.add(self.repo.path, paths=[fullpath])
  3471. change_sha = porcelain.commit(
  3472. self.repo.path,
  3473. message=b"Change",
  3474. committer=b"Jane <jane@example.com>",
  3475. author=b"John <john@example.com>",
  3476. )
  3477. # Revert with custom message
  3478. custom_msg = "Custom revert message"
  3479. revert_sha = porcelain.revert(
  3480. self.repo.path, commits=[change_sha], message=custom_msg
  3481. )
  3482. # Check the message
  3483. revert_commit = self.repo[revert_sha]
  3484. self.assertEqual(custom_msg.encode("utf-8"), revert_commit.message)
  3485. def test_revert_no_parent(self) -> None:
  3486. # Try to revert the initial commit (no parent)
  3487. fullpath = os.path.join(self.repo.path, "foo")
  3488. with open(fullpath, "w") as f:
  3489. f.write("content\n")
  3490. porcelain.add(self.repo.path, paths=[fullpath])
  3491. initial_sha = porcelain.commit(
  3492. self.repo.path,
  3493. message=b"Initial",
  3494. committer=b"Jane <jane@example.com>",
  3495. author=b"John <john@example.com>",
  3496. )
  3497. # Should raise an error
  3498. with self.assertRaises(porcelain.Error) as cm:
  3499. porcelain.revert(self.repo.path, commits=[initial_sha])
  3500. self.assertIn("no parents", str(cm.exception))
  3501. class CheckoutTests(PorcelainTestCase):
  3502. def setUp(self) -> None:
  3503. super().setUp()
  3504. self._sha, self._foo_path = _commit_file_with_content(
  3505. self.repo, "foo", "hello\n"
  3506. )
  3507. porcelain.branch_create(self.repo, "uni")
  3508. def test_checkout_to_existing_branch(self) -> None:
  3509. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3510. porcelain.checkout(self.repo, b"uni")
  3511. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3512. def test_checkout_to_non_existing_branch(self) -> None:
  3513. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3514. with self.assertRaises(KeyError):
  3515. porcelain.checkout(self.repo, b"bob")
  3516. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3517. def test_checkout_to_branch_with_modified_files(self) -> None:
  3518. with open(self._foo_path, "a") as f:
  3519. f.write("new message\n")
  3520. porcelain.add(self.repo, paths=[self._foo_path])
  3521. status = list(porcelain.status(self.repo))
  3522. self.assertEqual(
  3523. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  3524. )
  3525. # The new checkout behavior prevents switching with staged changes
  3526. with self.assertRaises(porcelain.CheckoutError):
  3527. porcelain.checkout(self.repo, b"uni")
  3528. # Should still be on master
  3529. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3530. # Force checkout should work
  3531. porcelain.checkout(self.repo, b"uni", force=True)
  3532. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3533. def test_checkout_with_deleted_files(self) -> None:
  3534. porcelain.remove(self.repo.path, [os.path.join(self.repo.path, "foo")])
  3535. status = list(porcelain.status(self.repo))
  3536. self.assertEqual(
  3537. [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status
  3538. )
  3539. # The new checkout behavior prevents switching with staged deletions
  3540. with self.assertRaises(porcelain.CheckoutError):
  3541. porcelain.checkout(self.repo, b"uni")
  3542. # Should still be on master
  3543. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3544. # Force checkout should work
  3545. porcelain.checkout(self.repo, b"uni", force=True)
  3546. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3547. def test_checkout_to_branch_with_added_files(self) -> None:
  3548. file_path = os.path.join(self.repo.path, "bar")
  3549. with open(file_path, "w") as f:
  3550. f.write("bar content\n")
  3551. porcelain.add(self.repo, paths=[file_path])
  3552. status = list(porcelain.status(self.repo))
  3553. self.assertEqual(
  3554. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3555. )
  3556. # Both branches have file 'foo' checkout should be fine.
  3557. porcelain.checkout(self.repo, b"uni")
  3558. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3559. status = list(porcelain.status(self.repo))
  3560. self.assertEqual(
  3561. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3562. )
  3563. def test_checkout_to_branch_with_modified_file_not_present(self) -> None:
  3564. # Commit a new file that the other branch doesn't have.
  3565. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3566. # Modify the file the other branch doesn't have.
  3567. with open(nee_path, "a") as f:
  3568. f.write("bar content\n")
  3569. porcelain.add(self.repo, paths=[nee_path])
  3570. status = list(porcelain.status(self.repo))
  3571. self.assertEqual(
  3572. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3573. )
  3574. # Checkout should fail when there are staged changes that would be lost
  3575. # This matches Git's behavior to prevent data loss
  3576. from dulwich.errors import WorkingTreeModifiedError
  3577. with self.assertRaises(WorkingTreeModifiedError) as cm:
  3578. porcelain.checkout(self.repo, b"uni")
  3579. self.assertIn("nee", str(cm.exception))
  3580. # Should still be on master branch
  3581. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3582. # The staged changes should still be present
  3583. status = list(porcelain.status(self.repo))
  3584. self.assertEqual(
  3585. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3586. )
  3587. self.assertTrue(os.path.exists(nee_path))
  3588. # Force checkout should work and lose the changes
  3589. porcelain.checkout(self.repo, b"uni", force=True)
  3590. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3591. # Now the file should be gone
  3592. self.assertFalse(os.path.exists(nee_path))
  3593. def test_checkout_to_branch_with_modified_file_not_present_forced(self) -> None:
  3594. # Commit a new file that the other branch doesn't have.
  3595. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3596. # Modify the file the other branch doesn't have.
  3597. with open(nee_path, "a") as f:
  3598. f.write("bar content\n")
  3599. porcelain.add(self.repo, paths=[nee_path])
  3600. status = list(porcelain.status(self.repo))
  3601. self.assertEqual(
  3602. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3603. )
  3604. # 'uni' branch doesn't have 'nee' and it has been modified, but we force to reset the entire index.
  3605. porcelain.checkout(self.repo, b"uni", force=True)
  3606. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3607. status = list(porcelain.status(self.repo))
  3608. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3609. def test_checkout_to_branch_with_unstaged_files(self) -> None:
  3610. # Edit `foo`.
  3611. with open(self._foo_path, "a") as f:
  3612. f.write("new message")
  3613. status = list(porcelain.status(self.repo))
  3614. self.assertEqual(
  3615. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  3616. )
  3617. # The new checkout behavior prevents switching with unstaged changes
  3618. with self.assertRaises(porcelain.CheckoutError):
  3619. porcelain.checkout(self.repo, b"uni")
  3620. # Should still be on master
  3621. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3622. # Force checkout should work
  3623. porcelain.checkout(self.repo, b"uni", force=True)
  3624. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3625. def test_checkout_to_branch_with_untracked_files(self) -> None:
  3626. with open(os.path.join(self.repo.path, "neu"), "a") as f:
  3627. f.write("new message\n")
  3628. status = list(porcelain.status(self.repo))
  3629. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3630. porcelain.checkout(self.repo, b"uni")
  3631. status = list(porcelain.status(self.repo))
  3632. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3633. def test_checkout_to_branch_with_new_files(self) -> None:
  3634. porcelain.checkout(self.repo, b"uni")
  3635. sub_directory = os.path.join(self.repo.path, "sub1")
  3636. os.mkdir(sub_directory)
  3637. for index in range(5):
  3638. _commit_file_with_content(
  3639. self.repo, "new_file_" + str(index + 1), "Some content\n"
  3640. )
  3641. _commit_file_with_content(
  3642. self.repo,
  3643. os.path.join("sub1", "new_file_" + str(index + 10)),
  3644. "Good content\n",
  3645. )
  3646. status = list(porcelain.status(self.repo))
  3647. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3648. porcelain.checkout(self.repo, b"master")
  3649. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3650. status = list(porcelain.status(self.repo))
  3651. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3652. porcelain.checkout(self.repo, b"uni")
  3653. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3654. status = list(porcelain.status(self.repo))
  3655. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3656. def test_checkout_to_branch_with_file_in_sub_directory(self) -> None:
  3657. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3658. os.makedirs(sub_directory)
  3659. sub_directory_file = os.path.join(sub_directory, "neu")
  3660. with open(sub_directory_file, "w") as f:
  3661. f.write("new message\n")
  3662. porcelain.add(self.repo, paths=[sub_directory_file])
  3663. porcelain.commit(
  3664. self.repo,
  3665. message=b"add " + sub_directory_file.encode(),
  3666. committer=b"Jane <jane@example.com>",
  3667. author=b"John <john@example.com>",
  3668. )
  3669. status = list(porcelain.status(self.repo))
  3670. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3671. self.assertTrue(os.path.isdir(sub_directory))
  3672. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3673. porcelain.checkout(self.repo, b"uni")
  3674. status = list(porcelain.status(self.repo))
  3675. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3676. self.assertFalse(os.path.isdir(sub_directory))
  3677. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3678. porcelain.checkout(self.repo, b"master")
  3679. self.assertTrue(os.path.isdir(sub_directory))
  3680. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3681. def test_checkout_to_branch_with_multiple_files_in_sub_directory(self) -> None:
  3682. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3683. os.makedirs(sub_directory)
  3684. sub_directory_file_1 = os.path.join(sub_directory, "neu")
  3685. with open(sub_directory_file_1, "w") as f:
  3686. f.write("new message\n")
  3687. sub_directory_file_2 = os.path.join(sub_directory, "gus")
  3688. with open(sub_directory_file_2, "w") as f:
  3689. f.write("alternative message\n")
  3690. porcelain.add(self.repo, paths=[sub_directory_file_1, sub_directory_file_2])
  3691. porcelain.commit(
  3692. self.repo,
  3693. message=b"add files neu and gus.",
  3694. committer=b"Jane <jane@example.com>",
  3695. author=b"John <john@example.com>",
  3696. )
  3697. status = list(porcelain.status(self.repo))
  3698. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3699. self.assertTrue(os.path.isdir(sub_directory))
  3700. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3701. porcelain.checkout(self.repo, b"uni")
  3702. status = list(porcelain.status(self.repo))
  3703. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3704. self.assertFalse(os.path.isdir(sub_directory))
  3705. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3706. def _commit_something_wrong(self):
  3707. with open(self._foo_path, "a") as f:
  3708. f.write("something wrong")
  3709. porcelain.add(self.repo, paths=[self._foo_path])
  3710. return porcelain.commit(
  3711. self.repo,
  3712. message=b"I may added something wrong",
  3713. committer=b"Jane <jane@example.com>",
  3714. author=b"John <john@example.com>",
  3715. )
  3716. def test_checkout_to_commit_sha(self) -> None:
  3717. self._commit_something_wrong()
  3718. porcelain.checkout(self.repo, self._sha)
  3719. self.assertEqual(self._sha, self.repo.head())
  3720. def test_checkout_to_head(self) -> None:
  3721. new_sha = self._commit_something_wrong()
  3722. porcelain.checkout(self.repo, b"HEAD")
  3723. self.assertEqual(new_sha, self.repo.head())
  3724. def _checkout_remote_branch(self):
  3725. errstream = BytesIO()
  3726. outstream = BytesIO()
  3727. porcelain.commit(
  3728. repo=self.repo.path,
  3729. message=b"init",
  3730. author=b"author <email>",
  3731. committer=b"committer <email>",
  3732. )
  3733. # Setup target repo cloned from temp test repo
  3734. clone_path = tempfile.mkdtemp()
  3735. self.addCleanup(shutil.rmtree, clone_path)
  3736. target_repo = porcelain.clone(
  3737. self.repo.path, target=clone_path, errstream=errstream
  3738. )
  3739. self.addCleanup(target_repo.close)
  3740. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  3741. # create a second file to be pushed back to origin
  3742. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3743. os.close(handle)
  3744. porcelain.add(repo=clone_path, paths=[fullpath])
  3745. porcelain.commit(
  3746. repo=clone_path,
  3747. message=b"push",
  3748. author=b"author <email>",
  3749. committer=b"committer <email>",
  3750. )
  3751. # Setup a non-checked out branch in the remote
  3752. refs_path = b"refs/heads/foo"
  3753. new_id = self.repo[b"HEAD"].id
  3754. self.assertNotEqual(new_id, ZERO_SHA)
  3755. self.repo.refs[refs_path] = new_id
  3756. # Push to the remote
  3757. porcelain.push(
  3758. clone_path,
  3759. "origin",
  3760. b"HEAD:" + refs_path,
  3761. outstream=outstream,
  3762. errstream=errstream,
  3763. )
  3764. self.assertEqual(
  3765. target_repo.refs[b"refs/remotes/origin/foo"],
  3766. target_repo.refs[b"HEAD"],
  3767. )
  3768. # The new checkout behavior treats origin/foo as a ref and creates detached HEAD
  3769. porcelain.checkout(target_repo, b"origin/foo")
  3770. original_id = target_repo[b"HEAD"].id
  3771. uni_id = target_repo[b"refs/remotes/origin/uni"].id
  3772. # Should be in detached HEAD state
  3773. with self.assertRaises((ValueError, IndexError)):
  3774. porcelain.active_branch(target_repo)
  3775. expected_refs = {
  3776. b"HEAD": original_id,
  3777. b"refs/heads/master": original_id,
  3778. # No local foo branch is created anymore
  3779. b"refs/remotes/origin/foo": original_id,
  3780. b"refs/remotes/origin/uni": uni_id,
  3781. b"refs/remotes/origin/HEAD": new_id,
  3782. b"refs/remotes/origin/master": new_id,
  3783. }
  3784. self.assertEqual(expected_refs, target_repo.get_refs())
  3785. return target_repo
  3786. def test_checkout_remote_branch(self) -> None:
  3787. repo = self._checkout_remote_branch()
  3788. repo.close()
  3789. def test_checkout_remote_branch_then_master_then_remote_branch_again(self) -> None:
  3790. target_repo = self._checkout_remote_branch()
  3791. # Should be in detached HEAD state
  3792. with self.assertRaises((ValueError, IndexError)):
  3793. porcelain.active_branch(target_repo)
  3794. # Save the commit SHA before adding bar
  3795. detached_commit_sha, _ = _commit_file_with_content(
  3796. target_repo, "bar", "something\n"
  3797. )
  3798. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3799. porcelain.checkout(target_repo, b"master")
  3800. self.assertEqual(b"master", porcelain.active_branch(target_repo))
  3801. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3802. # Going back to origin/foo won't have bar because the commit was made in detached state
  3803. porcelain.checkout(target_repo, b"origin/foo")
  3804. # Should be in detached HEAD state again
  3805. with self.assertRaises((ValueError, IndexError)):
  3806. porcelain.active_branch(target_repo)
  3807. # bar is NOT there because we're back at the original origin/foo commit
  3808. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3809. # But we can checkout the specific commit to get bar back
  3810. porcelain.checkout(target_repo, detached_commit_sha.decode())
  3811. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3812. target_repo.close()
  3813. def test_checkout_new_branch_from_remote_sets_tracking(self) -> None:
  3814. # Create a "remote" repository
  3815. remote_path = tempfile.mkdtemp()
  3816. self.addCleanup(shutil.rmtree, remote_path)
  3817. remote_repo = porcelain.init(remote_path)
  3818. # Add a commit to the remote
  3819. remote_sha, _ = _commit_file_with_content(
  3820. remote_repo, "bar", "remote content\n"
  3821. )
  3822. # Clone the remote repository
  3823. target_path = tempfile.mkdtemp()
  3824. self.addCleanup(shutil.rmtree, target_path)
  3825. target_repo = porcelain.clone(remote_path, target_path)
  3826. self.addCleanup(target_repo.close)
  3827. # Create a remote tracking branch reference
  3828. remote_branch_ref = b"refs/remotes/origin/feature"
  3829. target_repo.refs[remote_branch_ref] = remote_sha
  3830. # Checkout a new branch from the remote branch
  3831. porcelain.checkout(target_repo, remote_branch_ref, new_branch=b"local-feature")
  3832. # Verify the branch was created and is active
  3833. self.assertEqual(b"local-feature", porcelain.active_branch(target_repo))
  3834. # Verify tracking configuration was set
  3835. config = target_repo.get_config()
  3836. self.assertEqual(
  3837. b"origin", config.get((b"branch", b"local-feature"), b"remote")
  3838. )
  3839. self.assertEqual(
  3840. b"refs/heads/feature", config.get((b"branch", b"local-feature"), b"merge")
  3841. )
  3842. target_repo.close()
  3843. remote_repo.close()
  3844. class RestoreTests(PorcelainTestCase):
  3845. """Tests for the restore command."""
  3846. def setUp(self) -> None:
  3847. super().setUp()
  3848. self._sha, self._foo_path = _commit_file_with_content(
  3849. self.repo, "foo", "original\n"
  3850. )
  3851. def test_restore_worktree_from_index(self) -> None:
  3852. # Modify the working tree file
  3853. with open(self._foo_path, "w") as f:
  3854. f.write("modified\n")
  3855. # Restore from index (should restore to original)
  3856. porcelain.restore(self.repo, paths=["foo"])
  3857. with open(self._foo_path) as f:
  3858. content = f.read()
  3859. self.assertEqual("original\n", content)
  3860. def test_restore_worktree_from_head(self) -> None:
  3861. # Modify and stage the file
  3862. with open(self._foo_path, "w") as f:
  3863. f.write("staged\n")
  3864. porcelain.add(self.repo, paths=[self._foo_path])
  3865. # Now modify it again in worktree
  3866. with open(self._foo_path, "w") as f:
  3867. f.write("worktree\n")
  3868. # Restore from HEAD (should restore to original, not staged)
  3869. porcelain.restore(self.repo, paths=["foo"], source="HEAD")
  3870. with open(self._foo_path) as f:
  3871. content = f.read()
  3872. self.assertEqual("original\n", content)
  3873. def test_restore_staged_from_head(self) -> None:
  3874. # Modify and stage the file
  3875. with open(self._foo_path, "w") as f:
  3876. f.write("staged\n")
  3877. porcelain.add(self.repo, paths=[self._foo_path])
  3878. # Verify it's staged
  3879. status = list(porcelain.status(self.repo))
  3880. self.assertEqual(
  3881. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  3882. )
  3883. # Restore staged from HEAD
  3884. porcelain.restore(self.repo, paths=["foo"], staged=True, worktree=False)
  3885. # Verify it's no longer staged
  3886. status = list(porcelain.status(self.repo))
  3887. # Now it should show as unstaged modification
  3888. self.assertEqual(
  3889. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  3890. )
  3891. def test_restore_both_staged_and_worktree(self) -> None:
  3892. # Modify and stage the file
  3893. with open(self._foo_path, "w") as f:
  3894. f.write("staged\n")
  3895. porcelain.add(self.repo, paths=[self._foo_path])
  3896. # Now modify it again in worktree
  3897. with open(self._foo_path, "w") as f:
  3898. f.write("worktree\n")
  3899. # Restore both from HEAD
  3900. porcelain.restore(self.repo, paths=["foo"], staged=True, worktree=True)
  3901. # Verify content is restored
  3902. with open(self._foo_path) as f:
  3903. content = f.read()
  3904. self.assertEqual("original\n", content)
  3905. # Verify nothing is staged
  3906. status = list(porcelain.status(self.repo))
  3907. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3908. def test_restore_nonexistent_path(self) -> None:
  3909. with self.assertRaises(porcelain.CheckoutError):
  3910. porcelain.restore(self.repo, paths=["nonexistent"])
  3911. class SwitchTests(PorcelainTestCase):
  3912. """Tests for the switch command."""
  3913. def setUp(self) -> None:
  3914. super().setUp()
  3915. self._sha, self._foo_path = _commit_file_with_content(
  3916. self.repo, "foo", "hello\n"
  3917. )
  3918. porcelain.branch_create(self.repo, "dev")
  3919. def test_switch_to_existing_branch(self) -> None:
  3920. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3921. porcelain.switch(self.repo, "dev")
  3922. self.assertEqual(b"dev", porcelain.active_branch(self.repo))
  3923. def test_switch_to_non_existing_branch(self) -> None:
  3924. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3925. with self.assertRaises(KeyError):
  3926. porcelain.switch(self.repo, "nonexistent")
  3927. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3928. def test_switch_with_create(self) -> None:
  3929. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3930. porcelain.switch(self.repo, "master", create="feature")
  3931. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3932. def test_switch_with_detach(self) -> None:
  3933. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3934. porcelain.switch(self.repo, self._sha.decode(), detach=True)
  3935. # In detached HEAD state, active_branch raises IndexError
  3936. with self.assertRaises(IndexError):
  3937. porcelain.active_branch(self.repo)
  3938. def test_switch_with_uncommitted_changes(self) -> None:
  3939. # Modify the file
  3940. with open(self._foo_path, "a") as f:
  3941. f.write("new content\n")
  3942. porcelain.add(self.repo, paths=[self._foo_path])
  3943. # Switch should fail due to uncommitted changes
  3944. with self.assertRaises(porcelain.CheckoutError):
  3945. porcelain.switch(self.repo, "dev")
  3946. # Should still be on master
  3947. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3948. def test_switch_with_force(self) -> None:
  3949. # Modify the file
  3950. with open(self._foo_path, "a") as f:
  3951. f.write("new content\n")
  3952. porcelain.add(self.repo, paths=[self._foo_path])
  3953. # Force switch should work
  3954. porcelain.switch(self.repo, "dev", force=True)
  3955. self.assertEqual(b"dev", porcelain.active_branch(self.repo))
  3956. def test_switch_to_commit_without_detach(self) -> None:
  3957. # Switching to a commit SHA without --detach should fail
  3958. with self.assertRaises(porcelain.CheckoutError):
  3959. porcelain.switch(self.repo, self._sha.decode())
  3960. class GeneralCheckoutTests(PorcelainTestCase):
  3961. """Tests for the general checkout function that handles branches, tags, and commits."""
  3962. def setUp(self) -> None:
  3963. super().setUp()
  3964. # Create initial commit
  3965. self._sha1, self._foo_path = _commit_file_with_content(
  3966. self.repo, "foo", "initial content\n"
  3967. )
  3968. # Create a branch
  3969. porcelain.branch_create(self.repo, "feature")
  3970. # Create another commit on master
  3971. self._sha2, self._bar_path = _commit_file_with_content(
  3972. self.repo, "bar", "bar content\n"
  3973. )
  3974. # Create a tag
  3975. porcelain.tag_create(self.repo, "v1.0", objectish=self._sha1)
  3976. def test_checkout_branch(self) -> None:
  3977. """Test checking out a branch."""
  3978. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3979. # Checkout feature branch
  3980. porcelain.checkout(self.repo, "feature")
  3981. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3982. # File 'bar' should not exist in feature branch
  3983. self.assertFalse(os.path.exists(self._bar_path))
  3984. # Go back to master
  3985. porcelain.checkout(self.repo, "master")
  3986. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3987. # File 'bar' should exist again
  3988. self.assertTrue(os.path.exists(self._bar_path))
  3989. def test_checkout_commit(self) -> None:
  3990. """Test checking out a specific commit (detached HEAD)."""
  3991. # Checkout first commit by SHA
  3992. porcelain.checkout(self.repo, self._sha1.decode("ascii"))
  3993. # Should be in detached HEAD state - active_branch raises IndexError
  3994. with self.assertRaises((ValueError, IndexError)):
  3995. porcelain.active_branch(self.repo)
  3996. # File 'bar' should not exist
  3997. self.assertFalse(os.path.exists(self._bar_path))
  3998. # HEAD should point to the commit
  3999. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  4000. def test_checkout_tag(self) -> None:
  4001. """Test checking out a tag (detached HEAD)."""
  4002. # Checkout tag
  4003. porcelain.checkout(self.repo, "v1.0")
  4004. # Should be in detached HEAD state - active_branch raises IndexError
  4005. with self.assertRaises((ValueError, IndexError)):
  4006. porcelain.active_branch(self.repo)
  4007. # File 'bar' should not exist (tag points to first commit)
  4008. self.assertFalse(os.path.exists(self._bar_path))
  4009. # HEAD should point to the tagged commit
  4010. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  4011. def test_checkout_new_branch(self) -> None:
  4012. """Test creating a new branch during checkout (like git checkout -b)."""
  4013. # Create and checkout new branch from current HEAD
  4014. porcelain.checkout(self.repo, "master", new_branch="new-feature")
  4015. self.assertEqual(b"new-feature", porcelain.active_branch(self.repo))
  4016. self.assertTrue(os.path.exists(self._bar_path))
  4017. # Create and checkout new branch from specific commit
  4018. porcelain.checkout(self.repo, self._sha1.decode("ascii"), new_branch="from-old")
  4019. self.assertEqual(b"from-old", porcelain.active_branch(self.repo))
  4020. self.assertFalse(os.path.exists(self._bar_path))
  4021. def test_checkout_with_uncommitted_changes(self) -> None:
  4022. """Test checkout behavior with uncommitted changes."""
  4023. # Modify a file
  4024. with open(self._foo_path, "w") as f:
  4025. f.write("modified content\n")
  4026. # Should raise error when trying to checkout
  4027. with self.assertRaises(porcelain.CheckoutError) as cm:
  4028. porcelain.checkout(self.repo, "feature")
  4029. self.assertIn("local changes", str(cm.exception))
  4030. self.assertIn("foo", str(cm.exception))
  4031. # Should still be on master
  4032. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4033. def test_checkout_force(self) -> None:
  4034. """Test forced checkout discards local changes for files that differ between branches."""
  4035. # Modify a file
  4036. with open(self._foo_path, "w") as f:
  4037. f.write("modified content\n")
  4038. # Force checkout should succeed
  4039. porcelain.checkout(self.repo, "feature", force=True)
  4040. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4041. # Since foo has the same content in master and feature branches,
  4042. # checkout should NOT restore it - the modified content should remain
  4043. with open(self._foo_path) as f:
  4044. content = f.read()
  4045. self.assertEqual("modified content\n", content)
  4046. def test_checkout_nonexistent_ref(self) -> None:
  4047. """Test checkout of non-existent branch/commit."""
  4048. with self.assertRaises(KeyError):
  4049. porcelain.checkout(self.repo, "nonexistent")
  4050. def test_checkout_partial_sha(self) -> None:
  4051. """Test checkout with partial SHA."""
  4052. # Git typically allows checkout with partial SHA
  4053. partial_sha = self._sha1.decode("ascii")[:7]
  4054. porcelain.checkout(self.repo, partial_sha)
  4055. # Should be in detached HEAD state at the right commit
  4056. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  4057. def test_checkout_preserves_untracked_files(self) -> None:
  4058. """Test that checkout preserves untracked files."""
  4059. # Create an untracked file
  4060. untracked_path = os.path.join(self.repo.path, "untracked.txt")
  4061. with open(untracked_path, "w") as f:
  4062. f.write("untracked content\n")
  4063. # Checkout another branch
  4064. porcelain.checkout(self.repo, "feature")
  4065. # Untracked file should still exist
  4066. self.assertTrue(os.path.exists(untracked_path))
  4067. with open(untracked_path) as f:
  4068. content = f.read()
  4069. self.assertEqual("untracked content\n", content)
  4070. def test_checkout_full_ref_paths(self) -> None:
  4071. """Test checkout with full ref paths."""
  4072. # Test checkout with full branch ref path
  4073. porcelain.checkout(self.repo, "refs/heads/feature")
  4074. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4075. # Test checkout with full tag ref path
  4076. porcelain.checkout(self.repo, "refs/tags/v1.0")
  4077. # Should be in detached HEAD state
  4078. with self.assertRaises((ValueError, IndexError)):
  4079. porcelain.active_branch(self.repo)
  4080. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  4081. def test_checkout_bytes_vs_string_target(self) -> None:
  4082. """Test that checkout works with both bytes and string targets."""
  4083. # Test with string target
  4084. porcelain.checkout(self.repo, "feature")
  4085. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4086. # Test with bytes target
  4087. porcelain.checkout(self.repo, b"master")
  4088. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4089. def test_checkout_new_branch_from_commit(self) -> None:
  4090. """Test creating a new branch from a specific commit."""
  4091. # Create new branch from first commit
  4092. porcelain.checkout(self.repo, self._sha1.decode(), new_branch="from-commit")
  4093. self.assertEqual(b"from-commit", porcelain.active_branch(self.repo))
  4094. # Should be at the first commit (no bar file)
  4095. self.assertFalse(os.path.exists(self._bar_path))
  4096. def test_checkout_with_staged_addition(self) -> None:
  4097. """Test checkout behavior with staged file additions."""
  4098. # Create and stage a new file that doesn't exist in target branch
  4099. new_file_path = os.path.join(self.repo.path, "new.txt")
  4100. with open(new_file_path, "w") as f:
  4101. f.write("new file content\n")
  4102. porcelain.add(self.repo, [new_file_path])
  4103. # This should succeed because the file doesn't exist in target branch
  4104. porcelain.checkout(self.repo, "feature")
  4105. # Should be on feature branch
  4106. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4107. # The new file should still exist and be staged
  4108. self.assertTrue(os.path.exists(new_file_path))
  4109. status = porcelain.status(self.repo)
  4110. self.assertIn(b"new.txt", status.staged["add"])
  4111. def test_checkout_with_staged_modification_conflict(self) -> None:
  4112. """Test checkout behavior with staged modifications that would conflict."""
  4113. # Stage changes to a file that exists in both branches
  4114. with open(self._foo_path, "w") as f:
  4115. f.write("modified content\n")
  4116. porcelain.add(self.repo, [self._foo_path])
  4117. # Should prevent checkout due to staged changes to existing file
  4118. with self.assertRaises(porcelain.CheckoutError) as cm:
  4119. porcelain.checkout(self.repo, "feature")
  4120. self.assertIn("local changes", str(cm.exception))
  4121. self.assertIn("foo", str(cm.exception))
  4122. def test_checkout_head_reference(self) -> None:
  4123. """Test checkout of HEAD reference."""
  4124. # Move to feature branch first
  4125. porcelain.checkout(self.repo, "feature")
  4126. # Checkout HEAD creates detached HEAD state
  4127. porcelain.checkout(self.repo, "HEAD")
  4128. # Should be in detached HEAD state
  4129. with self.assertRaises((ValueError, IndexError)):
  4130. porcelain.active_branch(self.repo)
  4131. def test_checkout_error_messages(self) -> None:
  4132. """Test that checkout error messages are helpful."""
  4133. # Create uncommitted changes
  4134. with open(self._foo_path, "w") as f:
  4135. f.write("uncommitted changes\n")
  4136. # Try to checkout
  4137. with self.assertRaises(porcelain.CheckoutError) as cm:
  4138. porcelain.checkout(self.repo, "feature")
  4139. error_msg = str(cm.exception)
  4140. self.assertIn("local changes", error_msg)
  4141. self.assertIn("foo", error_msg)
  4142. self.assertIn("overwritten", error_msg)
  4143. self.assertIn("commit or stash", error_msg)
  4144. class SubmoduleTests(PorcelainTestCase):
  4145. def test_empty(self) -> None:
  4146. porcelain.commit(
  4147. repo=self.repo.path,
  4148. message=b"init",
  4149. author=b"author <email>",
  4150. committer=b"committer <email>",
  4151. )
  4152. self.assertEqual([], list(porcelain.submodule_list(self.repo)))
  4153. def test_add(self) -> None:
  4154. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  4155. with open(f"{self.repo.path}/.gitmodules") as f:
  4156. self.assertEqual(
  4157. """\
  4158. [submodule "bar"]
  4159. \turl = ../bar.git
  4160. \tpath = bar
  4161. """,
  4162. f.read(),
  4163. )
  4164. def test_init(self) -> None:
  4165. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  4166. porcelain.submodule_init(self.repo)
  4167. def test_update(self) -> None:
  4168. # Create a submodule repository
  4169. sub_repo_path = tempfile.mkdtemp()
  4170. self.addCleanup(shutil.rmtree, sub_repo_path)
  4171. sub_repo = Repo.init(sub_repo_path)
  4172. self.addCleanup(sub_repo.close)
  4173. # Add a file to the submodule repo
  4174. sub_file = os.path.join(sub_repo_path, "test.txt")
  4175. with open(sub_file, "w") as f:
  4176. f.write("submodule content")
  4177. porcelain.add(sub_repo, paths=[sub_file])
  4178. sub_commit = porcelain.commit(
  4179. sub_repo,
  4180. message=b"Initial submodule commit",
  4181. author=b"Test Author <test@example.com>",
  4182. committer=b"Test Committer <test@example.com>",
  4183. )
  4184. # Add the submodule to the main repository
  4185. porcelain.submodule_add(self.repo, sub_repo_path, "test_submodule")
  4186. # Manually add the submodule to the index
  4187. from dulwich.index import IndexEntry
  4188. from dulwich.objects import S_IFGITLINK
  4189. index = self.repo.open_index()
  4190. index[b"test_submodule"] = IndexEntry(
  4191. ctime=0,
  4192. mtime=0,
  4193. dev=0,
  4194. ino=0,
  4195. mode=S_IFGITLINK,
  4196. uid=0,
  4197. gid=0,
  4198. size=0,
  4199. sha=sub_commit,
  4200. flags=0,
  4201. )
  4202. index.write()
  4203. porcelain.add(self.repo, paths=[".gitmodules"])
  4204. porcelain.commit(
  4205. self.repo,
  4206. message=b"Add submodule",
  4207. author=b"Test Author <test@example.com>",
  4208. committer=b"Test Committer <test@example.com>",
  4209. )
  4210. # Initialize and update the submodule
  4211. porcelain.submodule_init(self.repo)
  4212. porcelain.submodule_update(self.repo)
  4213. # Check that the submodule directory exists
  4214. submodule_path = os.path.join(self.repo.path, "test_submodule")
  4215. self.assertTrue(os.path.exists(submodule_path))
  4216. # Check that the submodule file exists
  4217. submodule_file = os.path.join(submodule_path, "test.txt")
  4218. self.assertTrue(os.path.exists(submodule_file))
  4219. with open(submodule_file) as f:
  4220. self.assertEqual(f.read(), "submodule content")
  4221. def test_update_recursive(self) -> None:
  4222. # Create a nested (innermost) submodule repository
  4223. nested_repo_path = tempfile.mkdtemp()
  4224. self.addCleanup(shutil.rmtree, nested_repo_path)
  4225. nested_repo = Repo.init(nested_repo_path)
  4226. self.addCleanup(nested_repo.close)
  4227. # Add a file to the nested repo
  4228. nested_file = os.path.join(nested_repo_path, "nested.txt")
  4229. with open(nested_file, "w") as f:
  4230. f.write("nested submodule content")
  4231. porcelain.add(nested_repo, paths=[nested_file])
  4232. nested_commit = porcelain.commit(
  4233. nested_repo,
  4234. message=b"Initial nested commit",
  4235. author=b"Test Author <test@example.com>",
  4236. committer=b"Test Committer <test@example.com>",
  4237. )
  4238. # Create a middle submodule repository
  4239. middle_repo_path = tempfile.mkdtemp()
  4240. self.addCleanup(shutil.rmtree, middle_repo_path)
  4241. middle_repo = Repo.init(middle_repo_path)
  4242. self.addCleanup(middle_repo.close)
  4243. # Add a file to the middle repo
  4244. middle_file = os.path.join(middle_repo_path, "middle.txt")
  4245. with open(middle_file, "w") as f:
  4246. f.write("middle submodule content")
  4247. porcelain.add(middle_repo, paths=[middle_file])
  4248. # Add the nested submodule to the middle repository
  4249. porcelain.submodule_add(middle_repo, nested_repo_path, "nested")
  4250. # Manually add the nested submodule to the index
  4251. from dulwich.index import IndexEntry
  4252. from dulwich.objects import S_IFGITLINK
  4253. middle_index = middle_repo.open_index()
  4254. middle_index[b"nested"] = IndexEntry(
  4255. ctime=0,
  4256. mtime=0,
  4257. dev=0,
  4258. ino=0,
  4259. mode=S_IFGITLINK,
  4260. uid=0,
  4261. gid=0,
  4262. size=0,
  4263. sha=nested_commit,
  4264. flags=0,
  4265. )
  4266. middle_index.write()
  4267. porcelain.add(middle_repo, paths=[".gitmodules"])
  4268. middle_commit = porcelain.commit(
  4269. middle_repo,
  4270. message=b"Add nested submodule",
  4271. author=b"Test Author <test@example.com>",
  4272. committer=b"Test Committer <test@example.com>",
  4273. )
  4274. # Add the middle submodule to the main repository
  4275. porcelain.submodule_add(self.repo, middle_repo_path, "middle")
  4276. # Manually add the middle submodule to the index
  4277. main_index = self.repo.open_index()
  4278. main_index[b"middle"] = IndexEntry(
  4279. ctime=0,
  4280. mtime=0,
  4281. dev=0,
  4282. ino=0,
  4283. mode=S_IFGITLINK,
  4284. uid=0,
  4285. gid=0,
  4286. size=0,
  4287. sha=middle_commit,
  4288. flags=0,
  4289. )
  4290. main_index.write()
  4291. porcelain.add(self.repo, paths=[".gitmodules"])
  4292. porcelain.commit(
  4293. self.repo,
  4294. message=b"Add middle submodule",
  4295. author=b"Test Author <test@example.com>",
  4296. committer=b"Test Committer <test@example.com>",
  4297. )
  4298. # Initialize and recursively update the submodules
  4299. porcelain.submodule_init(self.repo)
  4300. porcelain.submodule_update(self.repo, recursive=True)
  4301. # Check that the middle submodule directory and file exist
  4302. middle_submodule_path = os.path.join(self.repo.path, "middle")
  4303. self.assertTrue(os.path.exists(middle_submodule_path))
  4304. middle_submodule_file = os.path.join(middle_submodule_path, "middle.txt")
  4305. self.assertTrue(os.path.exists(middle_submodule_file))
  4306. with open(middle_submodule_file) as f:
  4307. self.assertEqual(f.read(), "middle submodule content")
  4308. # Check that the nested submodule directory and file exist
  4309. nested_submodule_path = os.path.join(self.repo.path, "middle", "nested")
  4310. self.assertTrue(os.path.exists(nested_submodule_path))
  4311. nested_submodule_file = os.path.join(nested_submodule_path, "nested.txt")
  4312. self.assertTrue(os.path.exists(nested_submodule_file))
  4313. with open(nested_submodule_file) as f:
  4314. self.assertEqual(f.read(), "nested submodule content")
  4315. class PushTests(PorcelainTestCase):
  4316. def test_simple(self) -> None:
  4317. """Basic test of porcelain push where self.repo is the remote. First
  4318. clone the remote, commit a file to the clone, then push the changes
  4319. back to the remote.
  4320. """
  4321. outstream = BytesIO()
  4322. errstream = BytesIO()
  4323. porcelain.commit(
  4324. repo=self.repo.path,
  4325. message=b"init",
  4326. author=b"author <email>",
  4327. committer=b"committer <email>",
  4328. )
  4329. # Setup target repo cloned from temp test repo
  4330. clone_path = tempfile.mkdtemp()
  4331. self.addCleanup(shutil.rmtree, clone_path)
  4332. target_repo = porcelain.clone(
  4333. self.repo.path, target=clone_path, errstream=errstream
  4334. )
  4335. self.addCleanup(target_repo.close)
  4336. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  4337. # create a second file to be pushed back to origin
  4338. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4339. os.close(handle)
  4340. porcelain.add(repo=clone_path, paths=[fullpath])
  4341. porcelain.commit(
  4342. repo=clone_path,
  4343. message=b"push",
  4344. author=b"author <email>",
  4345. committer=b"committer <email>",
  4346. )
  4347. # Setup a non-checked out branch in the remote
  4348. refs_path = b"refs/heads/foo"
  4349. new_id = self.repo[b"HEAD"].id
  4350. self.assertNotEqual(new_id, ZERO_SHA)
  4351. self.repo.refs[refs_path] = new_id
  4352. # Push to the remote
  4353. porcelain.push(
  4354. clone_path,
  4355. "origin",
  4356. b"HEAD:" + refs_path,
  4357. outstream=outstream,
  4358. errstream=errstream,
  4359. )
  4360. self.assertEqual(
  4361. target_repo.refs[b"refs/remotes/origin/foo"],
  4362. target_repo.refs[b"HEAD"],
  4363. )
  4364. # Check that the target and source
  4365. with Repo(clone_path) as r_clone:
  4366. self.assertEqual(
  4367. {
  4368. b"HEAD": new_id,
  4369. b"refs/heads/foo": r_clone[b"HEAD"].id,
  4370. b"refs/heads/master": new_id,
  4371. },
  4372. self.repo.get_refs(),
  4373. )
  4374. self.assertEqual(r_clone[b"HEAD"].id, self.repo[refs_path].id)
  4375. # Get the change in the target repo corresponding to the add
  4376. # this will be in the foo branch.
  4377. change = next(
  4378. iter(
  4379. tree_changes(
  4380. self.repo.object_store,
  4381. self.repo[b"HEAD"].tree,
  4382. self.repo[b"refs/heads/foo"].tree,
  4383. )
  4384. )
  4385. )
  4386. self.assertEqual(
  4387. os.path.basename(fullpath), change.new.path.decode("ascii")
  4388. )
  4389. def test_local_missing(self) -> None:
  4390. """Pushing a new branch."""
  4391. outstream = BytesIO()
  4392. errstream = BytesIO()
  4393. # Setup target repo cloned from temp test repo
  4394. clone_path = tempfile.mkdtemp()
  4395. self.addCleanup(shutil.rmtree, clone_path)
  4396. target_repo = porcelain.init(clone_path)
  4397. target_repo.close()
  4398. self.assertRaises(
  4399. porcelain.Error,
  4400. porcelain.push,
  4401. self.repo,
  4402. clone_path,
  4403. b"HEAD:refs/heads/master",
  4404. outstream=outstream,
  4405. errstream=errstream,
  4406. )
  4407. def test_new(self) -> None:
  4408. """Pushing a new branch."""
  4409. outstream = BytesIO()
  4410. errstream = BytesIO()
  4411. # Setup target repo cloned from temp test repo
  4412. clone_path = tempfile.mkdtemp()
  4413. self.addCleanup(shutil.rmtree, clone_path)
  4414. target_repo = porcelain.init(clone_path)
  4415. target_repo.close()
  4416. # create a second file to be pushed back to origin
  4417. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4418. os.close(handle)
  4419. porcelain.add(repo=clone_path, paths=[fullpath])
  4420. new_id = porcelain.commit(
  4421. repo=self.repo,
  4422. message=b"push",
  4423. author=b"author <email>",
  4424. committer=b"committer <email>",
  4425. )
  4426. # Push to the remote
  4427. porcelain.push(
  4428. self.repo,
  4429. clone_path,
  4430. b"HEAD:refs/heads/master",
  4431. outstream=outstream,
  4432. errstream=errstream,
  4433. )
  4434. with Repo(clone_path) as r_clone:
  4435. self.assertEqual(
  4436. {
  4437. b"HEAD": new_id,
  4438. b"refs/heads/master": new_id,
  4439. },
  4440. r_clone.get_refs(),
  4441. )
  4442. def test_delete(self) -> None:
  4443. """Basic test of porcelain push, removing a branch."""
  4444. outstream = BytesIO()
  4445. errstream = BytesIO()
  4446. porcelain.commit(
  4447. repo=self.repo.path,
  4448. message=b"init",
  4449. author=b"author <email>",
  4450. committer=b"committer <email>",
  4451. )
  4452. # Setup target repo cloned from temp test repo
  4453. clone_path = tempfile.mkdtemp()
  4454. self.addCleanup(shutil.rmtree, clone_path)
  4455. target_repo = porcelain.clone(
  4456. self.repo.path, target=clone_path, errstream=errstream
  4457. )
  4458. target_repo.close()
  4459. # Setup a non-checked out branch in the remote
  4460. refs_path = b"refs/heads/foo"
  4461. new_id = self.repo[b"HEAD"].id
  4462. self.assertNotEqual(new_id, ZERO_SHA)
  4463. self.repo.refs[refs_path] = new_id
  4464. # Push to the remote
  4465. porcelain.push(
  4466. clone_path,
  4467. self.repo.path,
  4468. b":" + refs_path,
  4469. outstream=outstream,
  4470. errstream=errstream,
  4471. )
  4472. self.assertEqual(
  4473. {
  4474. b"HEAD": new_id,
  4475. b"refs/heads/master": new_id,
  4476. },
  4477. self.repo.get_refs(),
  4478. )
  4479. def test_diverged(self) -> None:
  4480. outstream = BytesIO()
  4481. errstream = BytesIO()
  4482. porcelain.commit(
  4483. repo=self.repo.path,
  4484. message=b"init",
  4485. author=b"author <email>",
  4486. committer=b"committer <email>",
  4487. )
  4488. # Setup target repo cloned from temp test repo
  4489. clone_path = tempfile.mkdtemp()
  4490. self.addCleanup(shutil.rmtree, clone_path)
  4491. target_repo = porcelain.clone(
  4492. self.repo.path, target=clone_path, errstream=errstream
  4493. )
  4494. target_repo.close()
  4495. remote_id = porcelain.commit(
  4496. repo=self.repo.path,
  4497. message=b"remote change",
  4498. author=b"author <email>",
  4499. committer=b"committer <email>",
  4500. )
  4501. local_id = porcelain.commit(
  4502. repo=clone_path,
  4503. message=b"local change",
  4504. author=b"author <email>",
  4505. committer=b"committer <email>",
  4506. )
  4507. outstream = BytesIO()
  4508. errstream = BytesIO()
  4509. # Push to the remote
  4510. self.assertRaises(
  4511. porcelain.DivergedBranches,
  4512. porcelain.push,
  4513. clone_path,
  4514. self.repo.path,
  4515. b"refs/heads/master",
  4516. outstream=outstream,
  4517. errstream=errstream,
  4518. )
  4519. self.assertEqual(
  4520. {
  4521. b"HEAD": remote_id,
  4522. b"refs/heads/master": remote_id,
  4523. },
  4524. self.repo.get_refs(),
  4525. )
  4526. self.assertEqual(b"", outstream.getvalue())
  4527. self.assertEqual(b"", errstream.getvalue())
  4528. outstream = BytesIO()
  4529. errstream = BytesIO()
  4530. # Push to the remote with --force
  4531. porcelain.push(
  4532. clone_path,
  4533. self.repo.path,
  4534. b"refs/heads/master",
  4535. outstream=outstream,
  4536. errstream=errstream,
  4537. force=True,
  4538. )
  4539. self.assertEqual(
  4540. {
  4541. b"HEAD": local_id,
  4542. b"refs/heads/master": local_id,
  4543. },
  4544. self.repo.get_refs(),
  4545. )
  4546. self.assertEqual(b"", outstream.getvalue())
  4547. self.assertTrue(re.search(b"Push to .* successful.\n", errstream.getvalue()))
  4548. def test_push_returns_sendpackresult(self) -> None:
  4549. """Test that push returns a SendPackResult with per-ref information."""
  4550. outstream = BytesIO()
  4551. errstream = BytesIO()
  4552. # Create initial commit
  4553. porcelain.commit(
  4554. repo=self.repo.path,
  4555. message=b"init",
  4556. author=b"author <email>",
  4557. committer=b"committer <email>",
  4558. )
  4559. # Setup target repo cloned from temp test repo
  4560. clone_path = tempfile.mkdtemp()
  4561. self.addCleanup(shutil.rmtree, clone_path)
  4562. target_repo = porcelain.clone(
  4563. self.repo.path, target=clone_path, errstream=errstream
  4564. )
  4565. target_repo.close()
  4566. # Create a commit in the clone
  4567. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4568. os.close(handle)
  4569. porcelain.add(repo=clone_path, paths=[fullpath])
  4570. porcelain.commit(
  4571. repo=clone_path,
  4572. message=b"push",
  4573. author=b"author <email>",
  4574. committer=b"committer <email>",
  4575. )
  4576. # Push and check the return value
  4577. result = porcelain.push(
  4578. clone_path,
  4579. "origin",
  4580. b"HEAD:refs/heads/new-branch",
  4581. outstream=outstream,
  4582. errstream=errstream,
  4583. )
  4584. # Verify that we get a SendPackResult
  4585. self.assertIsInstance(result, SendPackResult)
  4586. # Verify that it contains refs
  4587. self.assertIsNotNone(result.refs)
  4588. self.assertIn(b"refs/heads/new-branch", result.refs)
  4589. # Verify ref_status - should be None for successful updates
  4590. if result.ref_status:
  4591. self.assertIsNone(result.ref_status.get(b"refs/heads/new-branch"))
  4592. def test_mirror_mode(self) -> None:
  4593. """Test push with remote.<name>.mirror configuration."""
  4594. outstream = BytesIO()
  4595. errstream = BytesIO()
  4596. # Create initial commit
  4597. porcelain.commit(
  4598. repo=self.repo.path,
  4599. message=b"init",
  4600. author=b"author <email>",
  4601. committer=b"committer <email>",
  4602. )
  4603. # Setup target repo cloned from temp test repo
  4604. clone_path = tempfile.mkdtemp()
  4605. self.addCleanup(shutil.rmtree, clone_path)
  4606. target_repo = porcelain.clone(
  4607. self.repo.path, target=clone_path, errstream=errstream
  4608. )
  4609. target_repo.close()
  4610. # Create multiple refs in the clone
  4611. with Repo(clone_path) as r_clone:
  4612. # Create a new branch
  4613. r_clone.refs[b"refs/heads/feature"] = r_clone[b"HEAD"].id
  4614. # Create a tag
  4615. r_clone.refs[b"refs/tags/v1.0"] = r_clone[b"HEAD"].id
  4616. # Create a remote tracking branch
  4617. r_clone.refs[b"refs/remotes/upstream/main"] = r_clone[b"HEAD"].id
  4618. # Create a branch in the remote that doesn't exist in clone
  4619. self.repo.refs[b"refs/heads/to-be-deleted"] = self.repo[b"HEAD"].id
  4620. # Configure mirror mode
  4621. with Repo(clone_path) as r_clone:
  4622. config = r_clone.get_config()
  4623. config.set((b"remote", b"origin"), b"mirror", True)
  4624. config.write_to_path()
  4625. # Push with mirror mode
  4626. porcelain.push(
  4627. clone_path,
  4628. "origin",
  4629. outstream=outstream,
  4630. errstream=errstream,
  4631. )
  4632. # Verify refs were properly mirrored
  4633. with Repo(clone_path) as r_clone:
  4634. # All local branches should be pushed
  4635. self.assertEqual(
  4636. r_clone.refs[b"refs/heads/feature"],
  4637. self.repo.refs[b"refs/heads/feature"],
  4638. )
  4639. # All tags should be pushed
  4640. self.assertEqual(
  4641. r_clone.refs[b"refs/tags/v1.0"], self.repo.refs[b"refs/tags/v1.0"]
  4642. )
  4643. # Remote tracking branches should be pushed
  4644. self.assertEqual(
  4645. r_clone.refs[b"refs/remotes/upstream/main"],
  4646. self.repo.refs[b"refs/remotes/upstream/main"],
  4647. )
  4648. # Verify the extra branch was deleted
  4649. self.assertNotIn(b"refs/heads/to-be-deleted", self.repo.refs)
  4650. def test_mirror_mode_disabled(self) -> None:
  4651. """Test that mirror mode is properly disabled when set to false."""
  4652. outstream = BytesIO()
  4653. errstream = BytesIO()
  4654. # Create initial commit
  4655. porcelain.commit(
  4656. repo=self.repo.path,
  4657. message=b"init",
  4658. author=b"author <email>",
  4659. committer=b"committer <email>",
  4660. )
  4661. # Setup target repo cloned from temp test repo
  4662. clone_path = tempfile.mkdtemp()
  4663. self.addCleanup(shutil.rmtree, clone_path)
  4664. target_repo = porcelain.clone(
  4665. self.repo.path, target=clone_path, errstream=errstream
  4666. )
  4667. target_repo.close()
  4668. # Create a branch in the remote that doesn't exist in clone
  4669. self.repo.refs[b"refs/heads/should-not-be-deleted"] = self.repo[b"HEAD"].id
  4670. # Explicitly set mirror mode to false
  4671. with Repo(clone_path) as r_clone:
  4672. config = r_clone.get_config()
  4673. config.set((b"remote", b"origin"), b"mirror", False)
  4674. config.write_to_path()
  4675. # Push normally (not mirror mode)
  4676. porcelain.push(
  4677. clone_path,
  4678. "origin",
  4679. outstream=outstream,
  4680. errstream=errstream,
  4681. )
  4682. # Verify the extra branch was NOT deleted
  4683. self.assertIn(b"refs/heads/should-not-be-deleted", self.repo.refs)
  4684. class PullTests(PorcelainTestCase):
  4685. def setUp(self) -> None:
  4686. super().setUp()
  4687. # create a file for initial commit
  4688. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4689. os.close(handle)
  4690. porcelain.add(repo=self.repo.path, paths=fullpath)
  4691. porcelain.commit(
  4692. repo=self.repo.path,
  4693. message=b"test",
  4694. author=b"test <email>",
  4695. committer=b"test <email>",
  4696. )
  4697. # Setup target repo
  4698. self.target_path = tempfile.mkdtemp()
  4699. self.addCleanup(shutil.rmtree, self.target_path)
  4700. target_repo = porcelain.clone(
  4701. self.repo.path, target=self.target_path, errstream=BytesIO()
  4702. )
  4703. target_repo.close()
  4704. # create a second file to be pushed
  4705. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4706. os.close(handle)
  4707. porcelain.add(repo=self.repo.path, paths=fullpath)
  4708. porcelain.commit(
  4709. repo=self.repo.path,
  4710. message=b"test2",
  4711. author=b"test2 <email>",
  4712. committer=b"test2 <email>",
  4713. )
  4714. self.assertIn(b"refs/heads/master", self.repo.refs)
  4715. self.assertIn(b"refs/heads/master", target_repo.refs)
  4716. def test_simple(self) -> None:
  4717. outstream = BytesIO()
  4718. errstream = BytesIO()
  4719. # Pull changes into the cloned repo
  4720. porcelain.pull(
  4721. self.target_path,
  4722. self.repo.path,
  4723. b"refs/heads/master",
  4724. outstream=outstream,
  4725. errstream=errstream,
  4726. )
  4727. # Check the target repo for pushed changes
  4728. with Repo(self.target_path) as r:
  4729. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4730. def test_diverged(self) -> None:
  4731. outstream = BytesIO()
  4732. errstream = BytesIO()
  4733. c3a = porcelain.commit(
  4734. repo=self.target_path,
  4735. message=b"test3a",
  4736. author=b"test2 <email>",
  4737. committer=b"test2 <email>",
  4738. )
  4739. porcelain.commit(
  4740. repo=self.repo.path,
  4741. message=b"test3b",
  4742. author=b"test2 <email>",
  4743. committer=b"test2 <email>",
  4744. )
  4745. # Pull changes into the cloned repo
  4746. self.assertRaises(
  4747. porcelain.DivergedBranches,
  4748. porcelain.pull,
  4749. self.target_path,
  4750. self.repo.path,
  4751. b"refs/heads/master",
  4752. outstream=outstream,
  4753. errstream=errstream,
  4754. )
  4755. # Check the target repo for pushed changes
  4756. with Repo(self.target_path) as r:
  4757. self.assertEqual(r[b"refs/heads/master"].id, c3a)
  4758. # Pull with merge should now work
  4759. porcelain.pull(
  4760. self.target_path,
  4761. self.repo.path,
  4762. b"refs/heads/master",
  4763. outstream=outstream,
  4764. errstream=errstream,
  4765. fast_forward=False,
  4766. )
  4767. # Check the target repo for merged changes
  4768. with Repo(self.target_path) as r:
  4769. # HEAD should now be a merge commit
  4770. head = r[b"HEAD"]
  4771. # It should have two parents
  4772. self.assertEqual(len(head.parents), 2)
  4773. # One parent should be the previous HEAD (c3a)
  4774. self.assertIn(c3a, head.parents)
  4775. # The other parent should be from the source repo
  4776. self.assertIn(self.repo[b"HEAD"].id, head.parents)
  4777. def test_no_refspec(self) -> None:
  4778. outstream = BytesIO()
  4779. errstream = BytesIO()
  4780. # Pull changes into the cloned repo
  4781. porcelain.pull(
  4782. self.target_path,
  4783. self.repo.path,
  4784. outstream=outstream,
  4785. errstream=errstream,
  4786. )
  4787. # Check the target repo for pushed changes
  4788. with Repo(self.target_path) as r:
  4789. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4790. def test_no_remote_location(self) -> None:
  4791. outstream = BytesIO()
  4792. errstream = BytesIO()
  4793. # Pull changes into the cloned repo
  4794. porcelain.pull(
  4795. self.target_path,
  4796. refspecs=b"refs/heads/master",
  4797. outstream=outstream,
  4798. errstream=errstream,
  4799. )
  4800. # Check the target repo for pushed changes
  4801. with Repo(self.target_path) as r:
  4802. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4803. def test_pull_updates_working_tree(self) -> None:
  4804. """Test that pull updates the working tree with new files."""
  4805. outstream = BytesIO()
  4806. errstream = BytesIO()
  4807. # Create a new file with content in the source repo
  4808. new_file = os.path.join(self.repo.path, "newfile.txt")
  4809. with open(new_file, "w") as f:
  4810. f.write("This is new content")
  4811. porcelain.add(repo=self.repo.path, paths=[new_file])
  4812. porcelain.commit(
  4813. repo=self.repo.path,
  4814. message=b"Add new file",
  4815. author=b"test <email>",
  4816. committer=b"test <email>",
  4817. )
  4818. # Before pull, the file should not exist in target
  4819. target_file = os.path.join(self.target_path, "newfile.txt")
  4820. self.assertFalse(os.path.exists(target_file))
  4821. # Pull changes into the cloned repo
  4822. porcelain.pull(
  4823. self.target_path,
  4824. self.repo.path,
  4825. b"refs/heads/master",
  4826. outstream=outstream,
  4827. errstream=errstream,
  4828. )
  4829. # After pull, the file should exist with correct content
  4830. self.assertTrue(os.path.exists(target_file))
  4831. with open(target_file) as f:
  4832. self.assertEqual(f.read(), "This is new content")
  4833. # Check the HEAD is updated too
  4834. with Repo(self.target_path) as r:
  4835. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4836. def test_pull_protects_modified_files(self) -> None:
  4837. """Test that pull refuses to overwrite uncommitted changes by default."""
  4838. from dulwich.errors import WorkingTreeModifiedError
  4839. outstream = BytesIO()
  4840. errstream = BytesIO()
  4841. # Create a file with content in the source repo
  4842. test_file = os.path.join(self.repo.path, "testfile.txt")
  4843. with open(test_file, "w") as f:
  4844. f.write("original content")
  4845. porcelain.add(repo=self.repo.path, paths=[test_file])
  4846. porcelain.commit(
  4847. repo=self.repo.path,
  4848. message=b"Add test file",
  4849. author=b"test <email>",
  4850. committer=b"test <email>",
  4851. )
  4852. # Pull this change to target first
  4853. porcelain.pull(
  4854. self.target_path,
  4855. self.repo.path,
  4856. b"refs/heads/master",
  4857. outstream=outstream,
  4858. errstream=errstream,
  4859. )
  4860. # Now modify the file in source repo
  4861. with open(test_file, "w") as f:
  4862. f.write("updated content")
  4863. porcelain.add(repo=self.repo.path, paths=[test_file])
  4864. porcelain.commit(
  4865. repo=self.repo.path,
  4866. message=b"Update test file",
  4867. author=b"test <email>",
  4868. committer=b"test <email>",
  4869. )
  4870. # Modify the same file in target working directory (uncommitted)
  4871. target_file = os.path.join(self.target_path, "testfile.txt")
  4872. with open(target_file, "w") as f:
  4873. f.write("local modifications")
  4874. # Pull should fail because of uncommitted changes
  4875. with self.assertRaises(WorkingTreeModifiedError) as cm:
  4876. porcelain.pull(
  4877. self.target_path,
  4878. self.repo.path,
  4879. b"refs/heads/master",
  4880. outstream=outstream,
  4881. errstream=errstream,
  4882. )
  4883. self.assertIn("Your local changes", str(cm.exception))
  4884. self.assertIn("testfile.txt", str(cm.exception))
  4885. # Verify the file still has local modifications
  4886. with open(target_file) as f:
  4887. self.assertEqual(f.read(), "local modifications")
  4888. def test_pull_force_overwrites_modified_files(self) -> None:
  4889. """Test that pull with force=True overwrites uncommitted changes."""
  4890. outstream = BytesIO()
  4891. errstream = BytesIO()
  4892. # Create a file with content in the source repo
  4893. test_file = os.path.join(self.repo.path, "testfile.txt")
  4894. with open(test_file, "w") as f:
  4895. f.write("original content")
  4896. porcelain.add(repo=self.repo.path, paths=[test_file])
  4897. porcelain.commit(
  4898. repo=self.repo.path,
  4899. message=b"Add test file",
  4900. author=b"test <email>",
  4901. committer=b"test <email>",
  4902. )
  4903. # Pull this change to target first
  4904. porcelain.pull(
  4905. self.target_path,
  4906. self.repo.path,
  4907. b"refs/heads/master",
  4908. outstream=outstream,
  4909. errstream=errstream,
  4910. )
  4911. # Now modify the file in source repo
  4912. with open(test_file, "w") as f:
  4913. f.write("updated content")
  4914. porcelain.add(repo=self.repo.path, paths=[test_file])
  4915. porcelain.commit(
  4916. repo=self.repo.path,
  4917. message=b"Update test file",
  4918. author=b"test <email>",
  4919. committer=b"test <email>",
  4920. )
  4921. # Modify the same file in target working directory (uncommitted)
  4922. target_file = os.path.join(self.target_path, "testfile.txt")
  4923. with open(target_file, "w") as f:
  4924. f.write("local modifications")
  4925. # Pull with force=True should succeed and overwrite local changes
  4926. porcelain.pull(
  4927. self.target_path,
  4928. self.repo.path,
  4929. b"refs/heads/master",
  4930. outstream=outstream,
  4931. errstream=errstream,
  4932. force=True,
  4933. )
  4934. # Verify the file now has the remote content
  4935. with open(target_file) as f:
  4936. self.assertEqual(f.read(), "updated content")
  4937. # Check the HEAD is updated too
  4938. with Repo(self.target_path) as r:
  4939. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4940. def test_pull_allows_unmodified_files(self) -> None:
  4941. """Test that pull allows updating files that haven't been modified locally."""
  4942. outstream = BytesIO()
  4943. errstream = BytesIO()
  4944. # Create a file with content in the source repo
  4945. test_file = os.path.join(self.repo.path, "testfile.txt")
  4946. with open(test_file, "w") as f:
  4947. f.write("original content")
  4948. porcelain.add(repo=self.repo.path, paths=[test_file])
  4949. porcelain.commit(
  4950. repo=self.repo.path,
  4951. message=b"Add test file",
  4952. author=b"test <email>",
  4953. committer=b"test <email>",
  4954. )
  4955. # Pull this change to target first
  4956. porcelain.pull(
  4957. self.target_path,
  4958. self.repo.path,
  4959. b"refs/heads/master",
  4960. outstream=outstream,
  4961. errstream=errstream,
  4962. )
  4963. # Now modify the file in source repo
  4964. with open(test_file, "w") as f:
  4965. f.write("updated content")
  4966. porcelain.add(repo=self.repo.path, paths=[test_file])
  4967. porcelain.commit(
  4968. repo=self.repo.path,
  4969. message=b"Update test file",
  4970. author=b"test <email>",
  4971. committer=b"test <email>",
  4972. )
  4973. # Don't modify the file in target - it should be safe to update
  4974. target_file = os.path.join(self.target_path, "testfile.txt")
  4975. # Pull should succeed since the file wasn't modified locally
  4976. porcelain.pull(
  4977. self.target_path,
  4978. self.repo.path,
  4979. b"refs/heads/master",
  4980. outstream=outstream,
  4981. errstream=errstream,
  4982. )
  4983. # Verify the file now has the remote content
  4984. with open(target_file) as f:
  4985. self.assertEqual(f.read(), "updated content")
  4986. # Check the HEAD is updated too
  4987. with Repo(self.target_path) as r:
  4988. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4989. class StatusTests(PorcelainTestCase):
  4990. def test_empty(self) -> None:
  4991. results = porcelain.status(self.repo)
  4992. self.assertEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4993. self.assertEqual([], results.unstaged)
  4994. def test_status_base(self) -> None:
  4995. """Integration test for `status` functionality."""
  4996. # Commit a dummy file then modify it
  4997. fullpath = os.path.join(self.repo.path, "foo")
  4998. with open(fullpath, "w") as f:
  4999. f.write("origstuff")
  5000. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5001. porcelain.commit(
  5002. repo=self.repo.path,
  5003. message=b"test status",
  5004. author=b"author <email>",
  5005. committer=b"committer <email>",
  5006. )
  5007. # modify access and modify time of path
  5008. os.utime(fullpath, (0, 0))
  5009. with open(fullpath, "wb") as f:
  5010. f.write(b"stuff")
  5011. # Make a dummy file and stage it
  5012. filename_add = "bar"
  5013. fullpath = os.path.join(self.repo.path, filename_add)
  5014. with open(fullpath, "w") as f:
  5015. f.write("stuff")
  5016. porcelain.add(repo=self.repo.path, paths=fullpath)
  5017. results = porcelain.status(self.repo)
  5018. self.assertEqual(results.staged["add"][0], filename_add.encode("ascii"))
  5019. self.assertEqual(results.unstaged, [b"foo"])
  5020. def test_status_with_core_preloadindex(self) -> None:
  5021. """Test status with core.preloadIndex enabled."""
  5022. # Set core.preloadIndex to true
  5023. config = self.repo.get_config()
  5024. config.set(b"core", b"preloadIndex", b"true")
  5025. config.write_to_path()
  5026. # Create multiple files
  5027. files = []
  5028. for i in range(10):
  5029. filename = f"file{i}"
  5030. fullpath = os.path.join(self.repo.path, filename)
  5031. with open(fullpath, "w") as f:
  5032. f.write(f"content{i}")
  5033. files.append(fullpath)
  5034. porcelain.add(repo=self.repo.path, paths=files)
  5035. porcelain.commit(
  5036. repo=self.repo.path,
  5037. message=b"test preload status",
  5038. author=b"author <email>",
  5039. committer=b"committer <email>",
  5040. )
  5041. # Modify some files
  5042. modified_files = ["file1", "file3", "file5", "file7"]
  5043. for filename in modified_files:
  5044. fullpath = os.path.join(self.repo.path, filename)
  5045. with open(fullpath, "w") as f:
  5046. f.write("modified content")
  5047. os.utime(fullpath, (0, 0))
  5048. # Status should work correctly with preloadIndex enabled
  5049. results = porcelain.status(self.repo)
  5050. # Check that we detected the correct unstaged changes
  5051. unstaged_sorted = sorted(results.unstaged)
  5052. expected_sorted = sorted([f.encode("ascii") for f in modified_files])
  5053. self.assertEqual(unstaged_sorted, expected_sorted)
  5054. def test_status_all(self) -> None:
  5055. del_path = os.path.join(self.repo.path, "foo")
  5056. mod_path = os.path.join(self.repo.path, "bar")
  5057. add_path = os.path.join(self.repo.path, "baz")
  5058. us_path = os.path.join(self.repo.path, "blye")
  5059. ut_path = os.path.join(self.repo.path, "blyat")
  5060. with open(del_path, "w") as f:
  5061. f.write("origstuff")
  5062. with open(mod_path, "w") as f:
  5063. f.write("origstuff")
  5064. with open(us_path, "w") as f:
  5065. f.write("origstuff")
  5066. porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path])
  5067. porcelain.commit(
  5068. repo=self.repo.path,
  5069. message=b"test status",
  5070. author=b"author <email>",
  5071. committer=b"committer <email>",
  5072. )
  5073. porcelain.remove(self.repo.path, [del_path])
  5074. with open(add_path, "w") as f:
  5075. f.write("origstuff")
  5076. with open(mod_path, "w") as f:
  5077. f.write("more_origstuff")
  5078. with open(us_path, "w") as f:
  5079. f.write("more_origstuff")
  5080. porcelain.add(repo=self.repo.path, paths=[add_path, mod_path])
  5081. with open(us_path, "w") as f:
  5082. f.write("\norigstuff")
  5083. with open(ut_path, "w") as f:
  5084. f.write("origstuff")
  5085. results = porcelain.status(self.repo.path)
  5086. self.assertDictEqual(
  5087. {"add": [b"baz"], "delete": [b"foo"], "modify": [b"bar"]},
  5088. results.staged,
  5089. )
  5090. self.assertListEqual(results.unstaged, [b"blye"])
  5091. results_no_untracked = porcelain.status(self.repo.path, untracked_files="no")
  5092. self.assertListEqual(results_no_untracked.untracked, [])
  5093. def test_status_wrong_untracked_files_value(self) -> None:
  5094. with self.assertRaises(ValueError):
  5095. porcelain.status(self.repo.path, untracked_files="antani")
  5096. def test_status_untracked_path(self) -> None:
  5097. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  5098. os.mkdir(untracked_dir)
  5099. untracked_file = os.path.join(untracked_dir, "untracked_file")
  5100. with open(untracked_file, "w") as fh:
  5101. fh.write("untracked")
  5102. _, _, untracked = porcelain.status(self.repo.path, untracked_files="all")
  5103. self.assertEqual(untracked, ["untracked_dir/untracked_file"])
  5104. def test_status_untracked_path_normal(self) -> None:
  5105. # Create an untracked directory with multiple files
  5106. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  5107. os.mkdir(untracked_dir)
  5108. untracked_file1 = os.path.join(untracked_dir, "file1")
  5109. untracked_file2 = os.path.join(untracked_dir, "file2")
  5110. with open(untracked_file1, "w") as fh:
  5111. fh.write("untracked1")
  5112. with open(untracked_file2, "w") as fh:
  5113. fh.write("untracked2")
  5114. # Create a nested untracked directory
  5115. nested_dir = os.path.join(untracked_dir, "nested")
  5116. os.mkdir(nested_dir)
  5117. nested_file = os.path.join(nested_dir, "file3")
  5118. with open(nested_file, "w") as fh:
  5119. fh.write("untracked3")
  5120. # Test "normal" mode - should only show the directory, not individual files
  5121. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  5122. self.assertEqual(untracked, ["untracked_dir/"])
  5123. # Test "all" mode - should show all files
  5124. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  5125. self.assertEqual(
  5126. sorted(untracked_all),
  5127. [
  5128. "untracked_dir/file1",
  5129. "untracked_dir/file2",
  5130. "untracked_dir/nested/file3",
  5131. ],
  5132. )
  5133. def test_status_mixed_tracked_untracked(self) -> None:
  5134. # Create a directory with both tracked and untracked files
  5135. mixed_dir = os.path.join(self.repo_path, "mixed_dir")
  5136. os.mkdir(mixed_dir)
  5137. # Add a tracked file
  5138. tracked_file = os.path.join(mixed_dir, "tracked.txt")
  5139. with open(tracked_file, "w") as fh:
  5140. fh.write("tracked content")
  5141. porcelain.add(self.repo.path, paths=[tracked_file])
  5142. porcelain.commit(
  5143. repo=self.repo.path,
  5144. message=b"add tracked file",
  5145. author=b"author <email>",
  5146. committer=b"committer <email>",
  5147. )
  5148. # Add untracked files to the same directory
  5149. untracked_file = os.path.join(mixed_dir, "untracked.txt")
  5150. with open(untracked_file, "w") as fh:
  5151. fh.write("untracked content")
  5152. # In "normal" mode, should show individual untracked files in mixed dirs
  5153. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  5154. self.assertEqual(untracked, ["mixed_dir/untracked.txt"])
  5155. # In "all" mode, should be the same for mixed directories
  5156. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  5157. self.assertEqual(untracked_all, ["mixed_dir/untracked.txt"])
  5158. def test_status_crlf_mismatch(self) -> None:
  5159. # First make a commit as if the file has been added on a Linux system
  5160. # or with core.autocrlf=True
  5161. file_path = os.path.join(self.repo.path, "crlf")
  5162. with open(file_path, "wb") as f:
  5163. f.write(b"line1\nline2")
  5164. porcelain.add(repo=self.repo.path, paths=[file_path])
  5165. porcelain.commit(
  5166. repo=self.repo.path,
  5167. message=b"test status",
  5168. author=b"author <email>",
  5169. committer=b"committer <email>",
  5170. )
  5171. # Then update the file as if it was created by CGit on a Windows
  5172. # system with core.autocrlf=true
  5173. with open(file_path, "wb") as f:
  5174. f.write(b"line1\r\nline2")
  5175. results = porcelain.status(self.repo)
  5176. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  5177. self.assertListEqual(results.unstaged, [b"crlf"])
  5178. self.assertListEqual(results.untracked, [])
  5179. def test_status_autocrlf_true(self) -> None:
  5180. # First make a commit as if the file has been added on a Linux system
  5181. # or with core.autocrlf=True
  5182. file_path = os.path.join(self.repo.path, "crlf")
  5183. with open(file_path, "wb") as f:
  5184. f.write(b"line1\nline2")
  5185. porcelain.add(repo=self.repo.path, paths=[file_path])
  5186. porcelain.commit(
  5187. repo=self.repo.path,
  5188. message=b"test status",
  5189. author=b"author <email>",
  5190. committer=b"committer <email>",
  5191. )
  5192. # Then update the file as if it was created by CGit on a Windows
  5193. # system with core.autocrlf=true
  5194. with open(file_path, "wb") as f:
  5195. f.write(b"line1\r\nline2")
  5196. # TODO: It should be set automatically by looking at the configuration
  5197. c = self.repo.get_config()
  5198. c.set("core", "autocrlf", True)
  5199. c.write_to_path()
  5200. results = porcelain.status(self.repo)
  5201. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  5202. self.assertListEqual(results.unstaged, [])
  5203. self.assertListEqual(results.untracked, [])
  5204. def test_status_autocrlf_input(self) -> None:
  5205. # Commit existing file with CRLF
  5206. file_path = os.path.join(self.repo.path, "crlf-exists")
  5207. with open(file_path, "wb") as f:
  5208. f.write(b"line1\r\nline2")
  5209. porcelain.add(repo=self.repo.path, paths=[file_path])
  5210. porcelain.commit(
  5211. repo=self.repo.path,
  5212. message=b"test status",
  5213. author=b"author <email>",
  5214. committer=b"committer <email>",
  5215. )
  5216. c = self.repo.get_config()
  5217. c.set("core", "autocrlf", "input")
  5218. c.write_to_path()
  5219. # Add new (untracked) file
  5220. file_path = os.path.join(self.repo.path, "crlf-new")
  5221. with open(file_path, "wb") as f:
  5222. f.write(b"line1\r\nline2")
  5223. porcelain.add(repo=self.repo.path, paths=[file_path])
  5224. results = porcelain.status(self.repo)
  5225. self.assertDictEqual(
  5226. {"add": [b"crlf-new"], "delete": [], "modify": []}, results.staged
  5227. )
  5228. # File committed with CRLF before autocrlf=input was enabled
  5229. # will NOT appear as unstaged because stat matching optimization
  5230. # skips filter processing when file hasn't been modified.
  5231. # This matches Git's behavior, which uses stat matching to avoid
  5232. # expensive filter operations. Git shows a warning instead.
  5233. self.assertListEqual(results.unstaged, [])
  5234. self.assertListEqual(results.untracked, [])
  5235. def test_status_autocrlf_input_modified(self) -> None:
  5236. """Test that modified files with CRLF are correctly detected with autocrlf=input."""
  5237. # Commit existing file with CRLF
  5238. file_path = os.path.join(self.repo.path, "crlf-file.txt")
  5239. with open(file_path, "wb") as f:
  5240. f.write(b"line1\r\nline2\r\nline3\r\n")
  5241. porcelain.add(repo=self.repo.path, paths=[file_path])
  5242. porcelain.commit(
  5243. repo=self.repo.path,
  5244. message=b"initial commit",
  5245. author=b"author <email>",
  5246. committer=b"committer <email>",
  5247. )
  5248. c = self.repo.get_config()
  5249. c.set("core", "autocrlf", "input")
  5250. c.write_to_path()
  5251. # Modify the file content but keep CRLF
  5252. with open(file_path, "wb") as f:
  5253. f.write(b"line1\r\nline2 modified\r\nline3\r\n")
  5254. results = porcelain.status(self.repo)
  5255. # Modified file should be detected as unstaged
  5256. self.assertListEqual(results.unstaged, [b"crlf-file.txt"])
  5257. def test_status_autocrlf_input_binary(self) -> None:
  5258. """Test that binary files are not affected by autocrlf=input."""
  5259. # Set autocrlf=input first
  5260. c = self.repo.get_config()
  5261. c.set("core", "autocrlf", "input")
  5262. c.write_to_path()
  5263. # Commit binary file with CRLF-like sequences
  5264. file_path = os.path.join(self.repo.path, "binary.dat")
  5265. with open(file_path, "wb") as f:
  5266. f.write(b"binary\r\ndata\x00\xff\r\nmore")
  5267. porcelain.add(repo=self.repo.path, paths=[file_path])
  5268. porcelain.commit(
  5269. repo=self.repo.path,
  5270. message=b"add binary",
  5271. author=b"author <email>",
  5272. committer=b"committer <email>",
  5273. )
  5274. # Status should be clean - binary files not normalized
  5275. results = porcelain.status(self.repo)
  5276. self.assertListEqual(results.unstaged, [])
  5277. def test_status_autocrlf_input_mixed_endings(self) -> None:
  5278. """Test files with mixed line endings with autocrlf=input."""
  5279. # Set autocrlf=input
  5280. c = self.repo.get_config()
  5281. c.set("core", "autocrlf", "input")
  5282. c.write_to_path()
  5283. # Create file with mixed line endings
  5284. file_path = os.path.join(self.repo.path, "mixed.txt")
  5285. with open(file_path, "wb") as f:
  5286. f.write(b"line1\r\nline2\nline3\r\n")
  5287. porcelain.add(repo=self.repo.path, paths=[file_path])
  5288. porcelain.commit(
  5289. repo=self.repo.path,
  5290. message=b"add mixed",
  5291. author=b"author <email>",
  5292. committer=b"committer <email>",
  5293. )
  5294. # The file was normalized on commit, so working tree should match
  5295. results = porcelain.status(self.repo)
  5296. self.assertListEqual(results.unstaged, [])
  5297. def test_status_autocrlf_input_issue_1770(self) -> None:
  5298. """Test the specific scenario from issue #1770.
  5299. Files with CRLF committed with autocrlf=input should not show as unstaged
  5300. when their content hasn't changed.
  5301. """
  5302. # Set autocrlf=input BEFORE committing
  5303. c = self.repo.get_config()
  5304. c.set("core", "autocrlf", "input")
  5305. c.write_to_path()
  5306. # Create and commit file with CRLF endings
  5307. file_path = os.path.join(self.repo.path, "crlf-test.dsp")
  5308. with open(file_path, "wb") as f:
  5309. f.write(b"# Microsoft DSP file\r\n\r\nContent here\r\n")
  5310. porcelain.add(repo=self.repo.path, paths=[file_path])
  5311. porcelain.commit(
  5312. repo=self.repo.path,
  5313. message=b"add dsp file",
  5314. author=b"author <email>",
  5315. committer=b"committer <email>",
  5316. )
  5317. # File was normalized to LF in index, but working tree still has CRLF
  5318. # Status should be clean because comparison normalizes working tree too
  5319. results = porcelain.status(self.repo)
  5320. self.assertListEqual(results.unstaged, [])
  5321. def test_get_tree_changes_add(self) -> None:
  5322. """Unit test for get_tree_changes add."""
  5323. # Make a dummy file, stage
  5324. filename = "bar"
  5325. fullpath = os.path.join(self.repo.path, filename)
  5326. with open(fullpath, "w") as f:
  5327. f.write("stuff")
  5328. porcelain.add(repo=self.repo.path, paths=fullpath)
  5329. porcelain.commit(
  5330. repo=self.repo.path,
  5331. message=b"test status",
  5332. author=b"author <email>",
  5333. committer=b"committer <email>",
  5334. )
  5335. filename = "foo"
  5336. fullpath = os.path.join(self.repo.path, filename)
  5337. with open(fullpath, "w") as f:
  5338. f.write("stuff")
  5339. porcelain.add(repo=self.repo.path, paths=fullpath)
  5340. changes = porcelain.get_tree_changes(self.repo.path)
  5341. self.assertEqual(changes["add"][0], filename.encode("ascii"))
  5342. self.assertEqual(len(changes["add"]), 1)
  5343. self.assertEqual(len(changes["modify"]), 0)
  5344. self.assertEqual(len(changes["delete"]), 0)
  5345. def test_get_tree_changes_modify(self) -> None:
  5346. """Unit test for get_tree_changes modify."""
  5347. # Make a dummy file, stage, commit, modify
  5348. filename = "foo"
  5349. fullpath = os.path.join(self.repo.path, filename)
  5350. with open(fullpath, "w") as f:
  5351. f.write("stuff")
  5352. porcelain.add(repo=self.repo.path, paths=fullpath)
  5353. porcelain.commit(
  5354. repo=self.repo.path,
  5355. message=b"test status",
  5356. author=b"author <email>",
  5357. committer=b"committer <email>",
  5358. )
  5359. with open(fullpath, "w") as f:
  5360. f.write("otherstuff")
  5361. porcelain.add(repo=self.repo.path, paths=fullpath)
  5362. changes = porcelain.get_tree_changes(self.repo.path)
  5363. self.assertEqual(changes["modify"][0], filename.encode("ascii"))
  5364. self.assertEqual(len(changes["add"]), 0)
  5365. self.assertEqual(len(changes["modify"]), 1)
  5366. self.assertEqual(len(changes["delete"]), 0)
  5367. def test_get_tree_changes_delete(self) -> None:
  5368. """Unit test for get_tree_changes delete."""
  5369. # Make a dummy file, stage, commit, remove
  5370. filename = "foo"
  5371. fullpath = os.path.join(self.repo.path, filename)
  5372. with open(fullpath, "w") as f:
  5373. f.write("stuff")
  5374. porcelain.add(repo=self.repo.path, paths=fullpath)
  5375. porcelain.commit(
  5376. repo=self.repo.path,
  5377. message=b"test status",
  5378. author=b"author <email>",
  5379. committer=b"committer <email>",
  5380. )
  5381. cwd = os.getcwd()
  5382. self.addCleanup(os.chdir, cwd)
  5383. os.chdir(self.repo.path)
  5384. porcelain.remove(repo=self.repo.path, paths=[filename])
  5385. changes = porcelain.get_tree_changes(self.repo.path)
  5386. self.assertEqual(changes["delete"][0], filename.encode("ascii"))
  5387. self.assertEqual(len(changes["add"]), 0)
  5388. self.assertEqual(len(changes["modify"]), 0)
  5389. self.assertEqual(len(changes["delete"]), 1)
  5390. def test_get_untracked_paths(self) -> None:
  5391. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5392. f.write("ignored\n")
  5393. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  5394. f.write("blah\n")
  5395. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5396. f.write("blah\n")
  5397. os.symlink(
  5398. os.path.join(self.repo.path, os.pardir, "external_target"),
  5399. os.path.join(self.repo.path, "link"),
  5400. )
  5401. self.assertEqual(
  5402. {"ignored", "notignored", ".gitignore", "link"},
  5403. set(
  5404. porcelain.get_untracked_paths(
  5405. self.repo.path, self.repo.path, self.repo.open_index()
  5406. )
  5407. ),
  5408. )
  5409. self.assertEqual(
  5410. {".gitignore", "notignored", "link"},
  5411. set(porcelain.status(self.repo).untracked),
  5412. )
  5413. self.assertEqual(
  5414. {".gitignore", "notignored", "ignored", "link"},
  5415. set(porcelain.status(self.repo, ignored=True).untracked),
  5416. )
  5417. def test_get_untracked_paths_subrepo(self) -> None:
  5418. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5419. f.write("nested/\n")
  5420. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5421. f.write("blah\n")
  5422. subrepo = Repo.init(os.path.join(self.repo.path, "nested"), mkdir=True)
  5423. with open(os.path.join(subrepo.path, "ignored"), "w") as f:
  5424. f.write("bleep\n")
  5425. with open(os.path.join(subrepo.path, "with"), "w") as f:
  5426. f.write("bloop\n")
  5427. with open(os.path.join(subrepo.path, "manager"), "w") as f:
  5428. f.write("blop\n")
  5429. self.assertEqual(
  5430. {".gitignore", "notignored", os.path.join("nested", "")},
  5431. set(
  5432. porcelain.get_untracked_paths(
  5433. self.repo.path, self.repo.path, self.repo.open_index()
  5434. )
  5435. ),
  5436. )
  5437. self.assertEqual(
  5438. {".gitignore", "notignored"},
  5439. set(
  5440. porcelain.get_untracked_paths(
  5441. self.repo.path,
  5442. self.repo.path,
  5443. self.repo.open_index(),
  5444. exclude_ignored=True,
  5445. )
  5446. ),
  5447. )
  5448. self.assertEqual(
  5449. {"ignored", "with", "manager"},
  5450. set(
  5451. porcelain.get_untracked_paths(
  5452. subrepo.path, subrepo.path, subrepo.open_index()
  5453. )
  5454. ),
  5455. )
  5456. self.assertEqual(
  5457. set(),
  5458. set(
  5459. porcelain.get_untracked_paths(
  5460. subrepo.path,
  5461. self.repo.path,
  5462. self.repo.open_index(),
  5463. )
  5464. ),
  5465. )
  5466. self.assertEqual(
  5467. {
  5468. os.path.join("nested", "ignored"),
  5469. os.path.join("nested", "with"),
  5470. os.path.join("nested", "manager"),
  5471. },
  5472. set(
  5473. porcelain.get_untracked_paths(
  5474. self.repo.path,
  5475. subrepo.path,
  5476. self.repo.open_index(),
  5477. )
  5478. ),
  5479. )
  5480. def test_get_untracked_paths_nested_gitignore(self) -> None:
  5481. """Test directories with nested .gitignore files that ignore all contents."""
  5482. # Create cache directories with .gitignore files that contain "*"
  5483. cache_dirs = [".ruff_cache", ".pytest_cache", "__pycache__"]
  5484. for cache_dir in cache_dirs:
  5485. cache_path = os.path.join(self.repo.path, cache_dir)
  5486. os.mkdir(cache_path)
  5487. # Create .gitignore with * pattern (ignores everything)
  5488. with open(os.path.join(cache_path, ".gitignore"), "w") as f:
  5489. f.write("*\n")
  5490. # Create some files in the cache directory
  5491. with open(os.path.join(cache_path, "somefile.txt"), "w") as f:
  5492. f.write("cached data\n")
  5493. with open(os.path.join(cache_path, "data.json"), "w") as f:
  5494. f.write("{}\n")
  5495. # Create a normal untracked file
  5496. with open(os.path.join(self.repo.path, "untracked.txt"), "w") as f:
  5497. f.write("untracked content\n")
  5498. # Test with exclude_ignored=True (default for status)
  5499. untracked = set(
  5500. porcelain.get_untracked_paths(
  5501. self.repo.path,
  5502. self.repo.path,
  5503. self.repo.open_index(),
  5504. exclude_ignored=True,
  5505. untracked_files="normal",
  5506. )
  5507. )
  5508. # Cache directories should NOT be in untracked since all their contents are ignored
  5509. self.assertEqual({"untracked.txt"}, untracked)
  5510. # Test with exclude_ignored=False
  5511. untracked_with_ignored = set(
  5512. porcelain.get_untracked_paths(
  5513. self.repo.path,
  5514. self.repo.path,
  5515. self.repo.open_index(),
  5516. exclude_ignored=False,
  5517. untracked_files="normal",
  5518. )
  5519. )
  5520. # Cache directories should be included when not excluding ignored
  5521. expected = {"untracked.txt"}
  5522. for cache_dir in cache_dirs:
  5523. expected.add(cache_dir + os.sep)
  5524. self.assertEqual(expected, untracked_with_ignored)
  5525. # Test status() which uses exclude_ignored=True by default
  5526. status = porcelain.status(self.repo)
  5527. self.assertEqual(["untracked.txt"], status.untracked)
  5528. # Test status() with ignored=True which uses exclude_ignored=False
  5529. status_with_ignored = porcelain.status(self.repo, ignored=True)
  5530. # Should include cache directories
  5531. self.assertIn("untracked.txt", status_with_ignored.untracked)
  5532. for cache_dir in cache_dirs:
  5533. self.assertIn(cache_dir + "/", status_with_ignored.untracked)
  5534. def test_get_untracked_paths_mixed_directory(self) -> None:
  5535. """Test directory with both ignored and non-ignored files."""
  5536. # Create a directory with mixed content
  5537. mixed_dir = os.path.join(self.repo.path, "mixed")
  5538. os.mkdir(mixed_dir)
  5539. # Create .gitignore that ignores .log files
  5540. with open(os.path.join(mixed_dir, ".gitignore"), "w") as f:
  5541. f.write("*.log\n")
  5542. # Create ignored and non-ignored files
  5543. with open(os.path.join(mixed_dir, "debug.log"), "w") as f:
  5544. f.write("debug info\n")
  5545. with open(os.path.join(mixed_dir, "readme.txt"), "w") as f:
  5546. f.write("important\n")
  5547. # Test with exclude_ignored=True and normal mode
  5548. untracked = set(
  5549. porcelain.get_untracked_paths(
  5550. self.repo.path,
  5551. self.repo.path,
  5552. self.repo.open_index(),
  5553. exclude_ignored=True,
  5554. untracked_files="normal",
  5555. )
  5556. )
  5557. # In normal mode, should show the directory (matching git behavior)
  5558. self.assertEqual({os.path.join("mixed", "")}, untracked)
  5559. # Test with untracked_files="all"
  5560. untracked_all = set(
  5561. porcelain.get_untracked_paths(
  5562. self.repo.path,
  5563. self.repo.path,
  5564. self.repo.open_index(),
  5565. exclude_ignored=True,
  5566. untracked_files="all",
  5567. )
  5568. )
  5569. # Should list the non-ignored files
  5570. expected = {
  5571. os.path.join("mixed", ".gitignore"),
  5572. os.path.join("mixed", "readme.txt"),
  5573. }
  5574. self.assertEqual(expected, untracked_all)
  5575. def test_get_untracked_paths_specific_ignore_pattern(self) -> None:
  5576. """Test directory with .gitignore that ignores specific files, not all."""
  5577. # Create a directory
  5578. test_dir = os.path.join(self.repo.path, "testdir")
  5579. os.mkdir(test_dir)
  5580. # Create .gitignore that ignores only files named "test"
  5581. with open(os.path.join(test_dir, ".gitignore"), "w") as f:
  5582. f.write("test\n")
  5583. # Create files
  5584. with open(os.path.join(test_dir, "test"), "w") as f:
  5585. f.write("ignored\n")
  5586. with open(os.path.join(test_dir, "other.txt"), "w") as f:
  5587. f.write("not ignored\n")
  5588. # Test with exclude_ignored=True and normal mode
  5589. untracked = set(
  5590. porcelain.get_untracked_paths(
  5591. self.repo.path,
  5592. self.repo.path,
  5593. self.repo.open_index(),
  5594. exclude_ignored=True,
  5595. untracked_files="normal",
  5596. )
  5597. )
  5598. # Directory should be shown because it has non-ignored files
  5599. self.assertEqual({os.path.join("testdir", "")}, untracked)
  5600. def test_get_untracked_paths_nested_subdirs_all_ignored(self) -> None:
  5601. """Test directory containing only subdirectories where all files are ignored."""
  5602. # Create parent directory with .gitignore that ignores everything
  5603. parent_dir = os.path.join(self.repo.path, "parent")
  5604. os.mkdir(parent_dir)
  5605. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5606. f.write("*\n")
  5607. # Create subdirectories with files (all should be ignored by parent's .gitignore)
  5608. sub1 = os.path.join(parent_dir, "sub1")
  5609. sub2 = os.path.join(parent_dir, "sub2")
  5610. os.mkdir(sub1)
  5611. os.mkdir(sub2)
  5612. # Create files in subdirectories
  5613. with open(os.path.join(sub1, "file1.txt"), "w") as f:
  5614. f.write("content1\n")
  5615. with open(os.path.join(sub2, "file2.txt"), "w") as f:
  5616. f.write("content2\n")
  5617. # Create another normal untracked file
  5618. with open(os.path.join(self.repo.path, "normal.txt"), "w") as f:
  5619. f.write("normal\n")
  5620. # Test with exclude_ignored=True
  5621. untracked = set(
  5622. porcelain.get_untracked_paths(
  5623. self.repo.path,
  5624. self.repo.path,
  5625. self.repo.open_index(),
  5626. exclude_ignored=True,
  5627. untracked_files="normal",
  5628. )
  5629. )
  5630. # Parent directory should NOT be shown since all nested files are ignored
  5631. self.assertEqual({"normal.txt"}, untracked)
  5632. def test_get_untracked_paths_nested_subdirs_mixed(self) -> None:
  5633. """Test directory containing only subdirectories where some files are ignored, some aren't."""
  5634. # Create parent directory with .gitignore that ignores .log files
  5635. parent_dir = os.path.join(self.repo.path, "parent")
  5636. os.mkdir(parent_dir)
  5637. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5638. f.write("*.log\n")
  5639. # Create subdirectories
  5640. sub1 = os.path.join(parent_dir, "sub1")
  5641. sub2 = os.path.join(parent_dir, "sub2")
  5642. os.mkdir(sub1)
  5643. os.mkdir(sub2)
  5644. # sub1: only ignored files
  5645. with open(os.path.join(sub1, "debug.log"), "w") as f:
  5646. f.write("log content\n")
  5647. with open(os.path.join(sub1, "error.log"), "w") as f:
  5648. f.write("error log\n")
  5649. # sub2: mix of ignored and non-ignored files
  5650. with open(os.path.join(sub2, "access.log"), "w") as f:
  5651. f.write("access log\n")
  5652. with open(os.path.join(sub2, "readme.txt"), "w") as f:
  5653. f.write("important info\n")
  5654. # Test with exclude_ignored=True
  5655. untracked = set(
  5656. porcelain.get_untracked_paths(
  5657. self.repo.path,
  5658. self.repo.path,
  5659. self.repo.open_index(),
  5660. exclude_ignored=True,
  5661. untracked_files="normal",
  5662. )
  5663. )
  5664. # Parent directory SHOULD be shown since sub2 has non-ignored files
  5665. self.assertEqual({os.path.join("parent", "")}, untracked)
  5666. def test_get_untracked_paths_deeply_nested_all_ignored(self) -> None:
  5667. """Test deeply nested directories where all files are eventually ignored."""
  5668. # Create nested structure: parent/sub/subsub/
  5669. parent_dir = os.path.join(self.repo.path, "parent")
  5670. sub_dir = os.path.join(parent_dir, "sub")
  5671. subsub_dir = os.path.join(sub_dir, "subsub")
  5672. os.makedirs(subsub_dir)
  5673. # Parent has .gitignore that ignores everything
  5674. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5675. f.write("*\n")
  5676. # Create files at different levels
  5677. with open(os.path.join(subsub_dir, "deep_file.txt"), "w") as f:
  5678. f.write("deep content\n")
  5679. with open(os.path.join(sub_dir, "mid_file.txt"), "w") as f:
  5680. f.write("mid content\n")
  5681. # Test with exclude_ignored=True
  5682. untracked = set(
  5683. porcelain.get_untracked_paths(
  5684. self.repo.path,
  5685. self.repo.path,
  5686. self.repo.open_index(),
  5687. exclude_ignored=True,
  5688. untracked_files="normal",
  5689. )
  5690. )
  5691. # Parent directory should NOT be shown since all nested files are ignored
  5692. self.assertEqual(set(), untracked)
  5693. def test_get_untracked_paths_subdir(self) -> None:
  5694. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5695. f.write("subdir/\nignored")
  5696. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5697. f.write("blah\n")
  5698. os.mkdir(os.path.join(self.repo.path, "subdir"))
  5699. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  5700. f.write("foo")
  5701. with open(os.path.join(self.repo.path, "subdir", "ignored"), "w") as f:
  5702. f.write("foo")
  5703. self.assertEqual(
  5704. {
  5705. ".gitignore",
  5706. "notignored",
  5707. "ignored",
  5708. os.path.join("subdir", ""),
  5709. },
  5710. set(
  5711. porcelain.get_untracked_paths(
  5712. self.repo.path,
  5713. self.repo.path,
  5714. self.repo.open_index(),
  5715. )
  5716. ),
  5717. )
  5718. self.assertEqual(
  5719. {".gitignore", "notignored"},
  5720. set(
  5721. porcelain.get_untracked_paths(
  5722. self.repo.path,
  5723. self.repo.path,
  5724. self.repo.open_index(),
  5725. exclude_ignored=True,
  5726. )
  5727. ),
  5728. )
  5729. def test_get_untracked_paths_invalid_untracked_files(self) -> None:
  5730. with self.assertRaises(ValueError):
  5731. list(
  5732. porcelain.get_untracked_paths(
  5733. self.repo.path,
  5734. self.repo.path,
  5735. self.repo.open_index(),
  5736. untracked_files="invalid_value",
  5737. )
  5738. )
  5739. def test_get_untracked_paths_normal(self) -> None:
  5740. # Create an untracked directory with files
  5741. untracked_dir = os.path.join(self.repo.path, "untracked_dir")
  5742. os.mkdir(untracked_dir)
  5743. with open(os.path.join(untracked_dir, "file1.txt"), "w") as f:
  5744. f.write("untracked content")
  5745. with open(os.path.join(untracked_dir, "file2.txt"), "w") as f:
  5746. f.write("more untracked content")
  5747. # Test that "normal" mode works and returns only the directory
  5748. _, _, untracked = porcelain.status(
  5749. repo=self.repo.path, untracked_files="normal"
  5750. )
  5751. self.assertEqual(untracked, ["untracked_dir/"])
  5752. def test_get_untracked_paths_top_level_issue_1247(self) -> None:
  5753. """Test for issue #1247: ensure top-level untracked files are detected."""
  5754. # Create a single top-level untracked file
  5755. with open(os.path.join(self.repo.path, "sample.txt"), "w") as f:
  5756. f.write("test content")
  5757. # Test get_untracked_paths directly
  5758. untracked = list(
  5759. porcelain.get_untracked_paths(
  5760. self.repo.path, self.repo.path, self.repo.open_index()
  5761. )
  5762. )
  5763. self.assertIn(
  5764. "sample.txt",
  5765. untracked,
  5766. "Top-level file 'sample.txt' should be in untracked list",
  5767. )
  5768. # Test via status
  5769. status = porcelain.status(self.repo)
  5770. self.assertIn(
  5771. "sample.txt",
  5772. status.untracked,
  5773. "Top-level file 'sample.txt' should be in status.untracked",
  5774. )
  5775. # TODO(jelmer): Add test for dulwich.porcelain.daemon
  5776. class ShortlogTests(PorcelainTestCase):
  5777. def test_shortlog(self) -> None:
  5778. """Test porcelain.shortlog function with multiple authors and commits."""
  5779. # Create first file and commit
  5780. file_a = os.path.join(self.repo.path, "a.txt")
  5781. with open(file_a, "w") as f:
  5782. f.write("hello")
  5783. porcelain.add(self.repo.path, paths=[file_a])
  5784. porcelain.commit(
  5785. repo=self.repo.path,
  5786. message=b"Initial commit",
  5787. author=b"John <john@example.com>",
  5788. )
  5789. # Create second file and commit
  5790. file_b = os.path.join(self.repo.path, "b.txt")
  5791. with open(file_b, "w") as f:
  5792. f.write("update")
  5793. porcelain.add(self.repo.path, paths=[file_b])
  5794. porcelain.commit(
  5795. repo=self.repo.path,
  5796. message=b"Update file",
  5797. author=b"Doe <doe@example.com>",
  5798. )
  5799. # Call shortlog
  5800. output = porcelain.shortlog(self.repo.path)
  5801. expected = [
  5802. {"author": "John <john@example.com>", "messages": "Initial commit"},
  5803. {"author": "Doe <doe@example.com>", "messages": "Update file"},
  5804. ]
  5805. self.assertCountEqual(output, expected)
  5806. # Test summary output (count of messages)
  5807. output_summary = [
  5808. {"author": entry["author"], "count": len(entry["messages"].splitlines())}
  5809. for entry in output
  5810. ]
  5811. expected_summary = [
  5812. {"author": "John <john@example.com>", "count": 1},
  5813. {"author": "Doe <doe@example.com>", "count": 1},
  5814. ]
  5815. self.assertCountEqual(output_summary, expected_summary)
  5816. class UploadPackTests(PorcelainTestCase):
  5817. """Tests for upload_pack."""
  5818. def test_upload_pack(self) -> None:
  5819. outf = BytesIO()
  5820. exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf)
  5821. outlines = outf.getvalue().splitlines()
  5822. self.assertEqual([b"0000"], outlines)
  5823. self.assertEqual(0, exitcode)
  5824. class ReceivePackTests(PorcelainTestCase):
  5825. """Tests for receive_pack."""
  5826. def test_receive_pack(self) -> None:
  5827. filename = "foo"
  5828. fullpath = os.path.join(self.repo.path, filename)
  5829. with open(fullpath, "w") as f:
  5830. f.write("stuff")
  5831. porcelain.add(repo=self.repo.path, paths=fullpath)
  5832. self.repo.get_worktree().commit(
  5833. message=b"test status",
  5834. committer=b"committer <email>",
  5835. author=b"author <email>",
  5836. commit_timestamp=1402354300,
  5837. commit_timezone=0,
  5838. author_timestamp=1402354300,
  5839. author_timezone=0,
  5840. )
  5841. outf = BytesIO()
  5842. exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf)
  5843. outlines = outf.getvalue().splitlines()
  5844. self.assertEqual(
  5845. [
  5846. b"0091319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status "
  5847. b"delete-refs quiet ofs-delta side-band-64k "
  5848. b"no-done symref=HEAD:refs/heads/master",
  5849. b"003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master",
  5850. b"0000",
  5851. ],
  5852. outlines,
  5853. )
  5854. self.assertEqual(0, exitcode)
  5855. class BranchListTests(PorcelainTestCase):
  5856. def test_standard(self) -> None:
  5857. self.assertEqual(set(), set(porcelain.branch_list(self.repo)))
  5858. def test_new_branch(self) -> None:
  5859. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5860. self.repo[b"HEAD"] = c1.id
  5861. porcelain.branch_create(self.repo, b"foo")
  5862. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  5863. def test_sort_by_refname(self) -> None:
  5864. """Test branch.sort=refname (default alphabetical)."""
  5865. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5866. self.repo[b"HEAD"] = c1.id
  5867. # Create branches in non-alphabetical order
  5868. porcelain.branch_create(self.repo, b"zebra")
  5869. porcelain.branch_create(self.repo, b"alpha")
  5870. porcelain.branch_create(self.repo, b"beta")
  5871. # Set branch.sort to refname (though it's the default)
  5872. config = self.repo.get_config()
  5873. config.set((b"branch",), b"sort", b"refname")
  5874. config.write_to_path()
  5875. # Should be sorted alphabetically
  5876. branches = porcelain.branch_list(self.repo)
  5877. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5878. def test_sort_by_refname_reverse(self) -> None:
  5879. """Test branch.sort=-refname (reverse alphabetical)."""
  5880. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5881. self.repo[b"HEAD"] = c1.id
  5882. # Create branches
  5883. porcelain.branch_create(self.repo, b"zebra")
  5884. porcelain.branch_create(self.repo, b"alpha")
  5885. porcelain.branch_create(self.repo, b"beta")
  5886. # Set branch.sort to -refname
  5887. config = self.repo.get_config()
  5888. config.set((b"branch",), b"sort", b"-refname")
  5889. config.write_to_path()
  5890. # Should be sorted reverse alphabetically
  5891. branches = porcelain.branch_list(self.repo)
  5892. self.assertEqual([b"zebra", b"master", b"beta", b"alpha"], branches)
  5893. def test_sort_by_committerdate(self) -> None:
  5894. """Test branch.sort=committerdate."""
  5895. # Use build_commit_graph to create proper commits with specific times
  5896. c1, c2, c3 = build_commit_graph(
  5897. self.repo.object_store,
  5898. [[1], [2], [3]],
  5899. attrs={
  5900. 1: {"commit_time": 1000}, # oldest
  5901. 2: {"commit_time": 2000}, # newest
  5902. 3: {"commit_time": 1500}, # middle
  5903. },
  5904. )
  5905. self.repo[b"HEAD"] = c1.id
  5906. # Create branches pointing to different commits
  5907. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  5908. self.repo.refs[b"refs/heads/oldest"] = c1.id
  5909. self.repo.refs[b"refs/heads/newest"] = c2.id
  5910. self.repo.refs[b"refs/heads/middle"] = c3.id
  5911. # Set branch.sort to committerdate
  5912. config = self.repo.get_config()
  5913. config.set((b"branch",), b"sort", b"committerdate")
  5914. config.write_to_path()
  5915. # Should be sorted by commit time (oldest first)
  5916. branches = porcelain.branch_list(self.repo)
  5917. self.assertEqual([b"master", b"oldest", b"middle", b"newest"], branches)
  5918. def test_sort_by_committerdate_reverse(self) -> None:
  5919. """Test branch.sort=-committerdate."""
  5920. # Use build_commit_graph to create proper commits with specific times
  5921. c1, c2, c3 = build_commit_graph(
  5922. self.repo.object_store,
  5923. [[1], [2], [3]],
  5924. attrs={
  5925. 1: {"commit_time": 1000}, # oldest
  5926. 2: {"commit_time": 2000}, # newest
  5927. 3: {"commit_time": 1500}, # middle
  5928. },
  5929. )
  5930. self.repo[b"HEAD"] = c1.id
  5931. # Create branches pointing to different commits
  5932. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  5933. self.repo.refs[b"refs/heads/oldest"] = c1.id
  5934. self.repo.refs[b"refs/heads/newest"] = c2.id
  5935. self.repo.refs[b"refs/heads/middle"] = c3.id
  5936. # Set branch.sort to -committerdate
  5937. config = self.repo.get_config()
  5938. config.set((b"branch",), b"sort", b"-committerdate")
  5939. config.write_to_path()
  5940. # Should be sorted by commit time (newest first)
  5941. branches = porcelain.branch_list(self.repo)
  5942. self.assertEqual([b"newest", b"middle", b"master", b"oldest"], branches)
  5943. def test_sort_default(self) -> None:
  5944. """Test default sorting (no config)."""
  5945. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5946. self.repo[b"HEAD"] = c1.id
  5947. # Create branches in non-alphabetical order
  5948. porcelain.branch_create(self.repo, b"zebra")
  5949. porcelain.branch_create(self.repo, b"alpha")
  5950. porcelain.branch_create(self.repo, b"beta")
  5951. # No config set - should default to alphabetical
  5952. branches = porcelain.branch_list(self.repo)
  5953. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5954. class BranchRemoteListTests(PorcelainTestCase):
  5955. def test_no_remote_branches(self) -> None:
  5956. """Test with no remote branches."""
  5957. result = porcelain.branch_remotes_list(self.repo)
  5958. self.assertEqual([], result)
  5959. def test_remote_branches_refname_sort(self) -> None:
  5960. """Test remote branches sorting with refname (alphabetical)."""
  5961. # Create some remote branches
  5962. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5963. # Create remote branches is non-alphabetical order
  5964. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  5965. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  5966. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  5967. self.repo.refs[b"refs/remotes/origin/feature-4"] = c1.id
  5968. # Set branch.sort to refname
  5969. config = self.repo.get_config()
  5970. config.set((b"branch",), b"sort", b"refname")
  5971. config.write_to_path()
  5972. # Should return only branch names, sorted alphabetically
  5973. branches = porcelain.branch_remotes_list(self.repo)
  5974. expected = [
  5975. b"origin/feature-1",
  5976. b"origin/feature-2",
  5977. b"origin/feature-3",
  5978. b"origin/feature-4",
  5979. ]
  5980. self.assertEqual(expected, branches)
  5981. def test_remote_branches_refname_reverse_sort(self) -> None:
  5982. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5983. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  5984. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  5985. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  5986. self.repo.refs[b"refs/remotes/origin/feature-4"] = c1.id
  5987. # Set branch.sort to -refname
  5988. config = self.repo.get_config()
  5989. config.set((b"branch",), b"sort", b"-refname")
  5990. config.write_to_path()
  5991. branches = porcelain.branch_remotes_list(self.repo)
  5992. expected = [
  5993. b"origin/feature-4",
  5994. b"origin/feature-3",
  5995. b"origin/feature-2",
  5996. b"origin/feature-1",
  5997. ]
  5998. self.assertEqual(expected, branches)
  5999. def test_remote_branches_committerdate_sort(self) -> None:
  6000. """Test remote branches sorting with committerdate"""
  6001. # Create commits with different timestamps
  6002. c1, c2, c3 = build_commit_graph(
  6003. self.repo.object_store,
  6004. [[1], [2], [3]],
  6005. attrs={
  6006. 1: {"commit_time": 1000},
  6007. 2: {"commit_time": 2000},
  6008. 3: {"commit_time": 3000},
  6009. },
  6010. )
  6011. self.repo.refs[b"refs/remotes/origin/oldest"] = c1.id
  6012. self.repo.refs[b"refs/remotes/origin/middle"] = c2.id
  6013. self.repo.refs[b"refs/remotes/origin/newest"] = c3.id
  6014. # Set branch.sort to committerdate
  6015. config = self.repo.get_config()
  6016. config.set((b"branch",), b"sort", b"committerdate")
  6017. config.write_to_path()
  6018. branches = porcelain.branch_remotes_list(self.repo)
  6019. # Should be sorted by commit time (oldest first), then alphabetically for same time
  6020. expected = [b"origin/oldest", b"origin/middle", b"origin/newest"]
  6021. self.assertEqual(expected, branches)
  6022. def test_remote_branches_committerdate_reverse_sort(self) -> None:
  6023. """Test remote branches sorting with -committerdate."""
  6024. c1, c2, c3 = build_commit_graph(
  6025. self.repo.object_store,
  6026. [[1], [2], [3]],
  6027. attrs={
  6028. 1: {"commit_time": 1000},
  6029. 2: {"commit_time": 2000},
  6030. 3: {"commit_time": 1500},
  6031. },
  6032. )
  6033. self.repo.refs[b"refs/remotes/origin/oldest"] = c1.id
  6034. self.repo.refs[b"refs/remotes/origin/newest"] = c2.id
  6035. self.repo.refs[b"refs/remotes/origin/middle"] = c3.id
  6036. # Set branch.sort to -committerdate
  6037. config = self.repo.get_config()
  6038. config.set((b"branch",), b"sort", b"-committerdate")
  6039. config.write_to_path()
  6040. branches = porcelain.branch_remotes_list(self.repo)
  6041. # Should be sorted by commit time (newest first), then alphabetically for same time
  6042. expected = [b"origin/newest", b"origin/middle", b"origin/oldest"]
  6043. self.assertEqual(expected, branches)
  6044. def test_remote_branches_authordate_sort(self) -> None:
  6045. """Test remote branches sorting with authordate."""
  6046. c1, c2, c3 = build_commit_graph(
  6047. self.repo.object_store,
  6048. [[1], [2], [3]],
  6049. attrs={
  6050. 1: {"author_time": 1500},
  6051. 2: {"author_time": 2000},
  6052. 3: {"author_time": 1000},
  6053. },
  6054. )
  6055. self.repo.refs[b"refs/remotes/origin/middle"] = c1.id
  6056. self.repo.refs[b"refs/remotes/origin/newest"] = c2.id
  6057. self.repo.refs[b"refs/remotes/origin/oldest"] = c3.id
  6058. # Set branch.sort to authordate
  6059. config = self.repo.get_config()
  6060. config.set((b"branch",), b"sort", b"authordate")
  6061. config.write_to_path()
  6062. branches = porcelain.branch_remotes_list(self.repo)
  6063. expected = [b"origin/oldest", b"origin/middle", b"origin/newest"]
  6064. self.assertEqual(expected, branches)
  6065. def test_unknown_sort_key(self) -> None:
  6066. """Test that unknown sort key raises ValueError."""
  6067. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6068. self.repo.refs[b"refs/remotes/origin/master"] = c1.id
  6069. # Set branch.sort to unknown key
  6070. config = self.repo.get_config()
  6071. config.set((b"branch",), b"sort", b"unknown")
  6072. config.write_to_path()
  6073. with self.assertRaises(ValueError) as cm:
  6074. porcelain.branch_remotes_list(self.repo)
  6075. self.assertIn("Unknown sort key: unknown", str(cm.exception))
  6076. def test_default_sort_no_config(self) -> None:
  6077. """Test default sorting when no config is set."""
  6078. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6079. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  6080. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  6081. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  6082. # No config set - should default to alphabetical
  6083. branches = porcelain.branch_remotes_list(self.repo)
  6084. expected = [b"origin/feature-1", b"origin/feature-2", b"origin/feature-3"]
  6085. self.assertEqual(expected, branches)
  6086. class BranchMergedTests(PorcelainTestCase):
  6087. def test_no_merged_branches(self) -> None:
  6088. """Test with no merged branches."""
  6089. # Create complete graph: c1 → c2 (master), c1 → c3 (feature)
  6090. [_c1, c2, c3] = build_commit_graph(
  6091. self.repo.object_store,
  6092. [
  6093. [1], # c1
  6094. [2, 1], # c2 → c1 (master line)
  6095. [3, 1], # c3 → c1 (diverged feature branch)
  6096. ],
  6097. )
  6098. self.repo.refs[b"HEAD"] = c2.id
  6099. self.repo.refs[b"refs/heads/master"] = c2.id
  6100. self.repo.refs[b"refs/heads/feature"] = c3.id
  6101. result = list(porcelain.merged_branches(self.repo))
  6102. self.assertEqual([b"master"], result)
  6103. def test_all_branches_merged(self) -> None:
  6104. """Test when all branches are merged into current."""
  6105. # Create linear history: c1 → c2 → c3 (HEAD)
  6106. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  6107. self.repo.refs[b"HEAD"] = c3.id
  6108. self.repo.refs[b"refs/heads/master"] = c3.id
  6109. self.repo.refs[b"refs/heads/feature-1"] = c2.id # Merged (ancestor)
  6110. self.repo.refs[b"refs/heads/feature-2"] = c1.id # Merged (ancestor)
  6111. branches = list(porcelain.merged_branches(self.repo))
  6112. expected = [b"feature-1", b"master", b"feature-2"]
  6113. expected.sort()
  6114. branches.sort()
  6115. self.assertEqual(expected, branches)
  6116. def test_some_branches_merged(self) -> None:
  6117. """Test when some branches are merged, some are not."""
  6118. # c1 → c2 → c3 (HEAD/master)
  6119. # c1 → c4 → c5 (feature-1 - diverged)
  6120. [_c1, c2, c3, _c4, c5] = build_commit_graph(
  6121. self.repo.object_store,
  6122. [
  6123. [1], # c1
  6124. [2, 1], # c2 → c1 (master line)
  6125. [3, 2], # c3 → c2 (HEAD)
  6126. [4, 1], # c4 → c1 (feature branch)
  6127. [5, 4], # c5 → c4 (feature branch)
  6128. ],
  6129. )
  6130. self.repo.refs[b"HEAD"] = c3.id
  6131. self.repo.refs[b"refs/heads/master"] = c3.id
  6132. self.repo.refs[b"refs/heads/feature-1"] = c5.id # Not merged (diverged)
  6133. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Merged (ancestor)
  6134. branches = list(porcelain.merged_branches(self.repo))
  6135. expected = [b"feature-2", b"master"]
  6136. expected.sort()
  6137. branches.sort()
  6138. self.assertEqual(expected, branches)
  6139. def test_only_current_branch_merged(self) -> None:
  6140. """Test when only current branch exists."""
  6141. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6142. self.repo.refs[b"HEAD"] = c1.id
  6143. self.repo.refs[b"refs/heads/master"] = c1.id
  6144. result = list(porcelain.merged_branches(self.repo))
  6145. self.assertEqual([b"master"], result)
  6146. class BranchNoMergedTests(PorcelainTestCase):
  6147. def test_all_branches_merged(self) -> None:
  6148. """Test when all branches are merged - should return empty list."""
  6149. # Create linear history: c1 → c2 → c3 (HEAD)
  6150. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  6151. self.repo.refs[b"HEAD"] = c3.id
  6152. self.repo.refs[b"refs/heads/master"] = c3.id
  6153. self.repo.refs[b"refs/heads/feature-1"] = c2.id # Merged (ancestor)
  6154. self.repo.refs[b"refs/heads/feature-2"] = c1.id # Merged (ancestor)
  6155. result = list(porcelain.no_merged_branches(self.repo))
  6156. self.assertEqual([], result)
  6157. def test_no_merged_branches(self) -> None:
  6158. """Test with some non-merged branches."""
  6159. # Create complete graph: c1 → c2 (master), c1 → c3 (feature)
  6160. [_c1, c2, c3] = build_commit_graph(
  6161. self.repo.object_store,
  6162. [
  6163. [1], # c1
  6164. [2, 1], # c2 → c1 (master line)
  6165. [3, 1], # c3 → c1 (diverged feature branch)
  6166. ],
  6167. )
  6168. self.repo.refs[b"HEAD"] = c2.id
  6169. self.repo.refs[b"refs/heads/master"] = c2.id
  6170. self.repo.refs[b"refs/heads/feature"] = c3.id
  6171. result = list(porcelain.no_merged_branches(self.repo))
  6172. self.assertEqual([b"feature"], result)
  6173. def test_some_branches_not_merged(self) -> None:
  6174. """Test when some branches are merged, some are not."""
  6175. # c1 → c2 → c3 (HEAD/master)
  6176. # c1 → c4 → c5 (feature-1 - diverged)
  6177. [_c1, c2, c3, _c4, c5] = build_commit_graph(
  6178. self.repo.object_store,
  6179. [
  6180. [1], # c1
  6181. [2, 1], # c2 → c1 (master line)
  6182. [3, 2], # c3 → c2 (HEAD)
  6183. [4, 1], # c4 → c1 (feature branch)
  6184. [5, 4], # c5 → c4 (feature branch)
  6185. ],
  6186. )
  6187. self.repo.refs[b"HEAD"] = c3.id
  6188. self.repo.refs[b"refs/heads/master"] = c3.id
  6189. self.repo.refs[b"refs/heads/feature-1"] = c5.id # Not merged (diverged)
  6190. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Merged (ancestor)
  6191. result = list(porcelain.no_merged_branches(self.repo))
  6192. self.assertEqual([b"feature-1"], result)
  6193. def test_multiple_branches_not_merged(self) -> None:
  6194. """Test with multiple non-merged branches."""
  6195. # c1 → c2 (HEAD/master)
  6196. # c1 → c3 (feature-1 - diverged)
  6197. # c1 → c4 (feature-2 - diverged)
  6198. [_c1, c2, c3, c4] = build_commit_graph(
  6199. self.repo.object_store,
  6200. [
  6201. [1], # c1
  6202. [2, 1], # c2 → c1 (master line)
  6203. [3, 1], # c3 → c1 (feature-1 branch)
  6204. [4, 1], # c4 → c1 (feature-2 branch)
  6205. ],
  6206. )
  6207. self.repo.refs[b"HEAD"] = c2.id
  6208. self.repo.refs[b"refs/heads/master"] = c2.id
  6209. self.repo.refs[b"refs/heads/feature-1"] = c3.id # Not merged (diverged)
  6210. self.repo.refs[b"refs/heads/feature-2"] = c4.id # Not merged (diverged)
  6211. branches = list(porcelain.no_merged_branches(self.repo))
  6212. expected = [b"feature-1", b"feature-2"]
  6213. expected.sort()
  6214. branches.sort()
  6215. self.assertEqual(expected, branches)
  6216. def test_only_current_branch_exists(self) -> None:
  6217. """Test when only current branch exists - should return empty list."""
  6218. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6219. self.repo.refs[b"HEAD"] = c1.id
  6220. self.repo.refs[b"refs/heads/master"] = c1.id
  6221. result = list(porcelain.no_merged_branches(self.repo))
  6222. self.assertEqual([], result)
  6223. class BranchContainsTests(PorcelainTestCase):
  6224. def test_commit_in_single_branch(self) -> None:
  6225. """Test commit contained in only one branch."""
  6226. # Create: c1 → c2 (master), c1 → c3 (feature)
  6227. [_c1, c2, c3] = build_commit_graph(
  6228. self.repo.object_store,
  6229. [
  6230. [1], # c1
  6231. [2, 1], # c2 → c1 (master line)
  6232. [3, 1], # c3 → c1 (feature branch)
  6233. ],
  6234. )
  6235. self.repo.refs[b"HEAD"] = c2.id
  6236. self.repo.refs[b"refs/heads/master"] = c2.id
  6237. self.repo.refs[b"refs/heads/feature"] = c3.id
  6238. # c2 is only in master branch
  6239. result = list(porcelain.branches_containing(self.repo, c2.id.decode()))
  6240. self.assertEqual([b"master"], result)
  6241. # c3 is only in feature branch
  6242. result = list(porcelain.branches_containing(self.repo, c3.id.decode()))
  6243. self.assertEqual([b"feature"], result)
  6244. def test_commit_in_multiple_branches(self) -> None:
  6245. """Test commit contained in multiple branches."""
  6246. # Create: c1 → c2 → c3 (master), c2 → c4 (feature)
  6247. [c1, c2, c3, c4] = build_commit_graph(
  6248. self.repo.object_store,
  6249. [
  6250. [1], # c1
  6251. [2, 1], # c2 → c1
  6252. [3, 2], # c3 → c2 (master)
  6253. [4, 2], # c4 → c2 (feature)
  6254. ],
  6255. )
  6256. self.repo.refs[b"HEAD"] = c3.id
  6257. self.repo.refs[b"refs/heads/master"] = c3.id
  6258. self.repo.refs[b"refs/heads/feature"] = c4.id
  6259. # c2 is in both branches (common ancestor)
  6260. branches = list(porcelain.branches_containing(self.repo, c2.id.decode()))
  6261. expected = [b"master", b"feature"]
  6262. expected.sort()
  6263. branches.sort()
  6264. self.assertEqual(expected, branches)
  6265. # c1 is in both branches (older common ancestor)
  6266. branches = list(porcelain.branches_containing(self.repo, c1.id.decode()))
  6267. expected = [b"master", b"feature"]
  6268. expected.sort()
  6269. branches.sort()
  6270. self.assertEqual(expected, branches)
  6271. def test_commit_in_all_branches(self) -> None:
  6272. """Test commit contained in all branches."""
  6273. # Create linear history: c1 → c2 → c3 (HEAD/master)
  6274. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  6275. self.repo.refs[b"HEAD"] = c3.id
  6276. self.repo.refs[b"refs/heads/master"] = c3.id
  6277. self.repo.refs[b"refs/heads/feature-1"] = c3.id # Same as master
  6278. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Ancestor
  6279. # c1 is in all branches
  6280. branches = list(porcelain.branches_containing(self.repo, c1.id.decode()))
  6281. expected = [b"master", b"feature-1", b"feature-2"]
  6282. expected.sort()
  6283. branches.sort()
  6284. self.assertEqual(expected, branches)
  6285. def test_commit_in_no_branches(self) -> None:
  6286. """Test commit not contained in any branch."""
  6287. # Create: c1 → c2 (master), c1 → c3 (feature), orphan c4
  6288. [_c1, c2, c3, c4] = build_commit_graph(
  6289. self.repo.object_store,
  6290. [
  6291. [1], # c1
  6292. [2, 1], # c2 → c1 (master)
  6293. [3, 1], # c3 → c1 (feature)
  6294. [4], # c4 (orphan commit)
  6295. ],
  6296. )
  6297. self.repo.refs[b"HEAD"] = c2.id
  6298. self.repo.refs[b"refs/heads/master"] = c2.id
  6299. self.repo.refs[b"refs/heads/feature"] = c3.id
  6300. # c4 is not in any branch
  6301. result = list(porcelain.branches_containing(self.repo, c4.id.decode()))
  6302. self.assertEqual([], result)
  6303. def test_commit_ref_by_branch_name(self) -> None:
  6304. """Test using branch name as commit reference."""
  6305. # Create: c1 → c2 (master), c1 → c3 (feature)
  6306. [_c1, c2, c3] = build_commit_graph(
  6307. self.repo.object_store,
  6308. [
  6309. [1], # c1
  6310. [2, 1], # c2 → c1 (master)
  6311. [3, 1], # c3 → c1 (feature)
  6312. ],
  6313. )
  6314. self.repo.refs[b"HEAD"] = c2.id
  6315. self.repo.refs[b"refs/heads/master"] = c2.id
  6316. self.repo.refs[b"refs/heads/feature"] = c3.id
  6317. # Use "master" as commit reference - should find master branch
  6318. result = list(porcelain.branches_containing(self.repo, "master"))
  6319. self.assertEqual([b"master"], result)
  6320. # Use "feature" as commit reference - should find feature branch
  6321. result = list(porcelain.branches_containing(self.repo, "feature"))
  6322. self.assertEqual([b"feature"], result)
  6323. def test_commit_ref_by_head(self) -> None:
  6324. """Test using HEAD as commit reference."""
  6325. # Create: c1 → c2 → c3 (HEAD/master)
  6326. [_c1, c2, c3] = build_commit_graph(
  6327. self.repo.object_store, [[1], [2, 1], [3, 2]]
  6328. )
  6329. self.repo.refs[b"HEAD"] = c3.id
  6330. self.repo.refs[b"refs/heads/master"] = c3.id
  6331. self.repo.refs[b"refs/heads/feature"] = c2.id # Ancestor
  6332. # Use "HEAD" as commit reference
  6333. result = list(porcelain.branches_containing(self.repo, "HEAD"))
  6334. self.assertEqual([b"master"], result)
  6335. def test_invalid_commit_ref(self) -> None:
  6336. """Test with invalid commit reference."""
  6337. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6338. self.repo.refs[b"HEAD"] = c1.id
  6339. self.repo.refs[b"refs/heads/master"] = c1.id
  6340. # Test with non-existent commit
  6341. with self.assertRaises(KeyError) as cm:
  6342. list(porcelain.branches_containing(self.repo, "nonexistent"))
  6343. self.assertEqual(b"nonexistent", cm.exception.args[0])
  6344. # Test with invalid SHA
  6345. with self.assertRaises(KeyError) as cm:
  6346. list(porcelain.branches_containing(self.repo, "invalid-sha"))
  6347. self.assertEqual(b"invalid-sha", cm.exception.args[0])
  6348. def test_short_sha_reference(self) -> None:
  6349. """Test using short SHA as commit reference."""
  6350. # Create: c1 → c2 (master)
  6351. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2, 1]])
  6352. self.repo.refs[b"HEAD"] = c2.id
  6353. self.repo.refs[b"refs/heads/master"] = c2.id
  6354. # Use short SHA (first 7 characters)
  6355. short_sha = c1.id.decode()[:7]
  6356. result = list(porcelain.branches_containing(self.repo, short_sha))
  6357. self.assertEqual([b"master"], result)
  6358. class FilterBranchesByPatternTests(PorcelainTestCase):
  6359. """Tests for filter_branches_by_pattern function."""
  6360. def test_empty_branches(self) -> None:
  6361. """Test with empty branches list."""
  6362. result = porcelain.filter_branches_by_pattern([], "feature-*")
  6363. self.assertEqual([], result)
  6364. def test_star_pattern(self) -> None:
  6365. """Test wildcard pattern matching."""
  6366. branches = [b"main", b"feature-1", b"feature-2", b"develop", b"hotfix-bug"]
  6367. result = porcelain.filter_branches_by_pattern(branches, "feature-*")
  6368. expected = [b"feature-1", b"feature-2"]
  6369. self.assertEqual(expected, result)
  6370. def test_question_mark_pattern(self) -> None:
  6371. """Test single character wildcard pattern."""
  6372. branches = [b"main", b"feature-1", b"feature-2", b"feature-a", b"develop"]
  6373. result = porcelain.filter_branches_by_pattern(branches, "feature-?")
  6374. expected = [b"feature-1", b"feature-2", b"feature-a"]
  6375. self.assertEqual(expected, result)
  6376. def test_specific_pattern(self) -> None:
  6377. """Test exact match pattern."""
  6378. branches = [b"main", b"feature-1", b"feature-2", b"develop"]
  6379. result = porcelain.filter_branches_by_pattern(branches, "feature-1")
  6380. expected = [b"feature-1"]
  6381. self.assertEqual(expected, result)
  6382. def test_no_matches(self) -> None:
  6383. """Test pattern that matches no branches."""
  6384. branches = [b"main", b"feature-1", b"develop"]
  6385. result = porcelain.filter_branches_by_pattern(branches, "release-*")
  6386. self.assertEqual([], result)
  6387. def test_case_sensitive_pattern(self) -> None:
  6388. """Test case-sensitive pattern matching."""
  6389. branches = [b"Main", b"main", b"MAIN", b"develop"]
  6390. result = porcelain.filter_branches_by_pattern(branches, "main")
  6391. expected = [b"main"]
  6392. self.assertEqual(expected, result)
  6393. def test_multiple_patterns_behavior(self) -> None:
  6394. """Test that pattern works with multiple wildcards."""
  6395. branches = [
  6396. b"feature-login",
  6397. b"feature-signup",
  6398. b"bugfix-login",
  6399. b"hotfix-signup",
  6400. ]
  6401. result = porcelain.filter_branches_by_pattern(branches, "feature-*")
  6402. expected = [b"feature-login", b"feature-signup"]
  6403. self.assertEqual(expected, result)
  6404. def test_mixed_encoding_branches(self) -> None:
  6405. """Test with branches that have special characters."""
  6406. branches = [b"feature-1", b"feature/test", b"feature@prod", b"develop"]
  6407. result = porcelain.filter_branches_by_pattern(branches, "feature/*")
  6408. expected = [b"feature/test"]
  6409. self.assertEqual(expected, result)
  6410. def test_pattern_with_square_brackets(self) -> None:
  6411. """Test pattern with character classes."""
  6412. branches = [b"feature-1", b"feature-2", b"feature-a", b"feature-b", b"develop"]
  6413. result = porcelain.filter_branches_by_pattern(branches, "feature-[12]")
  6414. expected = [b"feature-1", b"feature-2"]
  6415. self.assertEqual(expected, result)
  6416. class BranchCreateTests(PorcelainTestCase):
  6417. def test_branch_exists(self) -> None:
  6418. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6419. self.repo[b"HEAD"] = c1.id
  6420. porcelain.branch_create(self.repo, b"foo")
  6421. self.assertRaises(porcelain.Error, porcelain.branch_create, self.repo, b"foo")
  6422. porcelain.branch_create(self.repo, b"foo", force=True)
  6423. def test_new_branch(self) -> None:
  6424. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6425. self.repo[b"HEAD"] = c1.id
  6426. porcelain.branch_create(self.repo, b"foo")
  6427. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  6428. def test_auto_setup_merge_true_from_remote_tracking(self) -> None:
  6429. """Test branch.autoSetupMerge=true sets up tracking from remote-tracking branch."""
  6430. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6431. self.repo[b"HEAD"] = c1.id
  6432. # Create a remote-tracking branch
  6433. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6434. # Set branch.autoSetupMerge to true (default)
  6435. config = self.repo.get_config()
  6436. config.set((b"branch",), b"autoSetupMerge", b"true")
  6437. config.write_to_path()
  6438. # Create branch from remote-tracking branch
  6439. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6440. # Verify tracking was set up
  6441. config = self.repo.get_config()
  6442. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6443. self.assertEqual(
  6444. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6445. )
  6446. def test_auto_setup_merge_false(self) -> None:
  6447. """Test branch.autoSetupMerge=false disables tracking setup."""
  6448. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6449. self.repo[b"HEAD"] = c1.id
  6450. # Create a remote-tracking branch
  6451. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6452. # Set branch.autoSetupMerge to false
  6453. config = self.repo.get_config()
  6454. config.set((b"branch",), b"autoSetupMerge", b"false")
  6455. config.write_to_path()
  6456. # Create branch from remote-tracking branch
  6457. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6458. # Verify tracking was NOT set up
  6459. config = self.repo.get_config()
  6460. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"remote")
  6461. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"merge")
  6462. def test_auto_setup_merge_always(self) -> None:
  6463. """Test branch.autoSetupMerge=always sets up tracking even from local branches."""
  6464. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6465. self.repo[b"HEAD"] = c1.id
  6466. self.repo.refs[b"refs/heads/main"] = c1.id
  6467. # Set branch.autoSetupMerge to always
  6468. config = self.repo.get_config()
  6469. config.set((b"branch",), b"autoSetupMerge", b"always")
  6470. config.write_to_path()
  6471. # Create branch from local branch - normally wouldn't set up tracking
  6472. porcelain.branch_create(self.repo, "feature", "main")
  6473. # With always, tracking should NOT be set up from local branches
  6474. # (Git only sets up tracking from remote-tracking branches even with always)
  6475. config = self.repo.get_config()
  6476. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"remote")
  6477. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"merge")
  6478. def test_auto_setup_merge_always_from_remote(self) -> None:
  6479. """Test branch.autoSetupMerge=always still sets up tracking from remote branches."""
  6480. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6481. self.repo[b"HEAD"] = c1.id
  6482. # Create a remote-tracking branch
  6483. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6484. # Set branch.autoSetupMerge to always
  6485. config = self.repo.get_config()
  6486. config.set((b"branch",), b"autoSetupMerge", b"always")
  6487. config.write_to_path()
  6488. # Create branch from remote-tracking branch
  6489. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6490. # Verify tracking was set up
  6491. config = self.repo.get_config()
  6492. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6493. self.assertEqual(
  6494. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6495. )
  6496. def test_auto_setup_merge_default(self) -> None:
  6497. """Test default behavior (no config) is same as true."""
  6498. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6499. self.repo[b"HEAD"] = c1.id
  6500. # Create a remote-tracking branch
  6501. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6502. # Don't set any config - should default to true
  6503. # Create branch from remote-tracking branch
  6504. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6505. # Verify tracking was set up
  6506. config = self.repo.get_config()
  6507. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6508. self.assertEqual(
  6509. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6510. )
  6511. class BranchDeleteTests(PorcelainTestCase):
  6512. def test_simple(self) -> None:
  6513. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6514. self.repo[b"HEAD"] = c1.id
  6515. porcelain.branch_create(self.repo, b"foo")
  6516. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  6517. porcelain.branch_delete(self.repo, b"foo")
  6518. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  6519. def test_simple_unicode(self) -> None:
  6520. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6521. self.repo[b"HEAD"] = c1.id
  6522. porcelain.branch_create(self.repo, "foo")
  6523. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  6524. porcelain.branch_delete(self.repo, "foo")
  6525. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  6526. class FetchTests(PorcelainTestCase):
  6527. def test_simple(self) -> None:
  6528. outstream = BytesIO()
  6529. errstream = BytesIO()
  6530. # create a file for initial commit
  6531. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6532. os.close(handle)
  6533. porcelain.add(repo=self.repo.path, paths=fullpath)
  6534. porcelain.commit(
  6535. repo=self.repo.path,
  6536. message=b"test",
  6537. author=b"test <email>",
  6538. committer=b"test <email>",
  6539. )
  6540. # Setup target repo
  6541. target_path = tempfile.mkdtemp()
  6542. self.addCleanup(shutil.rmtree, target_path)
  6543. target_repo = porcelain.clone(
  6544. self.repo.path, target=target_path, errstream=errstream
  6545. )
  6546. # create a second file to be pushed
  6547. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6548. os.close(handle)
  6549. porcelain.add(repo=self.repo.path, paths=fullpath)
  6550. porcelain.commit(
  6551. repo=self.repo.path,
  6552. message=b"test2",
  6553. author=b"test2 <email>",
  6554. committer=b"test2 <email>",
  6555. )
  6556. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  6557. target_repo.close()
  6558. # Fetch changes into the cloned repo
  6559. porcelain.fetch(target_path, "origin", outstream=outstream, errstream=errstream)
  6560. # Assert that fetch updated the local image of the remote
  6561. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  6562. # Check the target repo for pushed changes
  6563. with Repo(target_path) as r:
  6564. self.assertIn(self.repo[b"HEAD"].id, r)
  6565. def test_with_remote_name(self) -> None:
  6566. remote_name = "origin"
  6567. outstream = BytesIO()
  6568. errstream = BytesIO()
  6569. # create a file for initial commit
  6570. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6571. os.close(handle)
  6572. porcelain.add(repo=self.repo.path, paths=fullpath)
  6573. porcelain.commit(
  6574. repo=self.repo.path,
  6575. message=b"test",
  6576. author=b"test <email>",
  6577. committer=b"test <email>",
  6578. )
  6579. # Setup target repo
  6580. target_path = tempfile.mkdtemp()
  6581. self.addCleanup(shutil.rmtree, target_path)
  6582. target_repo = porcelain.clone(
  6583. self.repo.path, target=target_path, errstream=errstream
  6584. )
  6585. # Capture current refs
  6586. target_refs = target_repo.get_refs()
  6587. # create a second file to be pushed
  6588. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6589. os.close(handle)
  6590. porcelain.add(repo=self.repo.path, paths=fullpath)
  6591. porcelain.commit(
  6592. repo=self.repo.path,
  6593. message=b"test2",
  6594. author=b"test2 <email>",
  6595. committer=b"test2 <email>",
  6596. )
  6597. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  6598. target_config = target_repo.get_config()
  6599. target_config.set(
  6600. (b"remote", remote_name.encode()), b"url", self.repo.path.encode()
  6601. )
  6602. target_repo.close()
  6603. # Fetch changes into the cloned repo
  6604. porcelain.fetch(
  6605. target_path, remote_name, outstream=outstream, errstream=errstream
  6606. )
  6607. # Assert that fetch updated the local image of the remote
  6608. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  6609. # Check the target repo for pushed changes, as well as updates
  6610. # for the refs
  6611. with Repo(target_path) as r:
  6612. self.assertIn(self.repo[b"HEAD"].id, r)
  6613. self.assertNotEqual(self.repo.get_refs(), target_refs)
  6614. def assert_correct_remote_refs(
  6615. self, local_refs, remote_refs, remote_name=b"origin"
  6616. ) -> None:
  6617. """Assert that known remote refs corresponds to actual remote refs."""
  6618. local_ref_prefix = b"refs/heads"
  6619. remote_ref_prefix = b"refs/remotes/" + remote_name
  6620. locally_known_remote_refs = {
  6621. k[len(remote_ref_prefix) + 1 :]: v
  6622. for k, v in local_refs.items()
  6623. if k.startswith(remote_ref_prefix)
  6624. }
  6625. normalized_remote_refs = {
  6626. k[len(local_ref_prefix) + 1 :]: v
  6627. for k, v in remote_refs.items()
  6628. if k.startswith(local_ref_prefix)
  6629. }
  6630. if b"HEAD" in locally_known_remote_refs and b"HEAD" in remote_refs:
  6631. normalized_remote_refs[b"HEAD"] = remote_refs[b"HEAD"]
  6632. self.assertEqual(locally_known_remote_refs, normalized_remote_refs)
  6633. class RepackTests(PorcelainTestCase):
  6634. def test_empty(self) -> None:
  6635. porcelain.repack(self.repo)
  6636. def test_simple(self) -> None:
  6637. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6638. os.close(handle)
  6639. porcelain.add(repo=self.repo.path, paths=fullpath)
  6640. porcelain.repack(self.repo)
  6641. def test_write_bitmaps(self) -> None:
  6642. """Test that write_bitmaps generates bitmap files."""
  6643. # Create some content
  6644. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6645. os.close(handle)
  6646. with open(fullpath, "w") as f:
  6647. f.write("test content")
  6648. porcelain.add(repo=self.repo.path, paths=fullpath)
  6649. porcelain.commit(
  6650. repo=self.repo.path,
  6651. message=b"test commit",
  6652. author=b"Test Author <test@example.com>",
  6653. committer=b"Test Committer <test@example.com>",
  6654. )
  6655. # Repack with bitmaps
  6656. porcelain.repack(self.repo, write_bitmaps=True)
  6657. # Check that bitmap files were created
  6658. pack_dir = os.path.join(self.repo.path, ".git", "objects", "pack")
  6659. bitmap_files = [f for f in os.listdir(pack_dir) if f.endswith(".bitmap")]
  6660. self.assertGreater(len(bitmap_files), 0)
  6661. class LsTreeTests(PorcelainTestCase):
  6662. def test_empty(self) -> None:
  6663. porcelain.commit(
  6664. repo=self.repo.path,
  6665. message=b"test status",
  6666. author=b"author <email>",
  6667. committer=b"committer <email>",
  6668. )
  6669. f = StringIO()
  6670. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  6671. self.assertEqual(f.getvalue(), "")
  6672. def test_simple(self) -> None:
  6673. # Commit a dummy file then modify it
  6674. fullpath = os.path.join(self.repo.path, "foo")
  6675. with open(fullpath, "w") as f:
  6676. f.write("origstuff")
  6677. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6678. porcelain.commit(
  6679. repo=self.repo.path,
  6680. message=b"test status",
  6681. author=b"author <email>",
  6682. committer=b"committer <email>",
  6683. )
  6684. output = StringIO()
  6685. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  6686. self.assertEqual(
  6687. output.getvalue(),
  6688. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n",
  6689. )
  6690. def test_recursive(self) -> None:
  6691. # Create a directory then write a dummy file in it
  6692. dirpath = os.path.join(self.repo.path, "adir")
  6693. filepath = os.path.join(dirpath, "afile")
  6694. os.mkdir(dirpath)
  6695. with open(filepath, "w") as f:
  6696. f.write("origstuff")
  6697. porcelain.add(repo=self.repo.path, paths=[filepath])
  6698. porcelain.commit(
  6699. repo=self.repo.path,
  6700. message=b"test status",
  6701. author=b"author <email>",
  6702. committer=b"committer <email>",
  6703. )
  6704. output = StringIO()
  6705. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  6706. self.assertEqual(
  6707. output.getvalue(),
  6708. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n",
  6709. )
  6710. output2 = StringIO()
  6711. porcelain.ls_tree(self.repo, b"HEAD", outstream=output2, recursive=True)
  6712. self.assertEqual(
  6713. output2.getvalue(),
  6714. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n"
  6715. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir"
  6716. "/afile\n",
  6717. )
  6718. class LsRemoteTests(PorcelainTestCase):
  6719. def test_empty(self) -> None:
  6720. result = porcelain.ls_remote(self.repo.path)
  6721. self.assertEqual({}, result.refs)
  6722. self.assertEqual({}, result.symrefs)
  6723. def test_some(self) -> None:
  6724. cid = porcelain.commit(
  6725. repo=self.repo.path,
  6726. message=b"test status",
  6727. author=b"author <email>",
  6728. committer=b"committer <email>",
  6729. )
  6730. result = porcelain.ls_remote(self.repo.path)
  6731. self.assertEqual(
  6732. {b"refs/heads/master": cid, b"HEAD": cid},
  6733. result.refs,
  6734. )
  6735. # HEAD should be a symref to refs/heads/master
  6736. self.assertEqual({b"HEAD": b"refs/heads/master"}, result.symrefs)
  6737. class LsFilesTests(PorcelainTestCase):
  6738. def test_empty(self) -> None:
  6739. self.assertEqual([], list(porcelain.ls_files(self.repo)))
  6740. def test_simple(self) -> None:
  6741. # Commit a dummy file then modify it
  6742. fullpath = os.path.join(self.repo.path, "foo")
  6743. with open(fullpath, "w") as f:
  6744. f.write("origstuff")
  6745. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6746. self.assertEqual([b"foo"], list(porcelain.ls_files(self.repo)))
  6747. class RemoteAddTests(PorcelainTestCase):
  6748. def test_new(self) -> None:
  6749. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6750. c = self.repo.get_config()
  6751. self.assertEqual(
  6752. c.get((b"remote", b"jelmer"), b"url"),
  6753. b"git://jelmer.uk/code/dulwich",
  6754. )
  6755. def test_exists(self) -> None:
  6756. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6757. self.assertRaises(
  6758. porcelain.RemoteExists,
  6759. porcelain.remote_add,
  6760. self.repo,
  6761. "jelmer",
  6762. "git://jelmer.uk/code/dulwich",
  6763. )
  6764. class RemoteRemoveTests(PorcelainTestCase):
  6765. def test_remove(self) -> None:
  6766. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6767. c = self.repo.get_config()
  6768. self.assertEqual(
  6769. c.get((b"remote", b"jelmer"), b"url"),
  6770. b"git://jelmer.uk/code/dulwich",
  6771. )
  6772. porcelain.remote_remove(self.repo, "jelmer")
  6773. self.assertRaises(KeyError, porcelain.remote_remove, self.repo, "jelmer")
  6774. c = self.repo.get_config()
  6775. self.assertRaises(KeyError, c.get, (b"remote", b"jelmer"), b"url")
  6776. class CheckIgnoreTests(PorcelainTestCase):
  6777. def test_check_ignored(self) -> None:
  6778. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6779. f.write("foo")
  6780. foo_path = os.path.join(self.repo.path, "foo")
  6781. with open(foo_path, "w") as f:
  6782. f.write("BAR")
  6783. bar_path = os.path.join(self.repo.path, "bar")
  6784. with open(bar_path, "w") as f:
  6785. f.write("BAR")
  6786. self.assertEqual(["foo"], list(porcelain.check_ignore(self.repo, [foo_path])))
  6787. self.assertEqual([], list(porcelain.check_ignore(self.repo, [bar_path])))
  6788. def test_check_added_abs(self) -> None:
  6789. path = os.path.join(self.repo.path, "foo")
  6790. with open(path, "w") as f:
  6791. f.write("BAR")
  6792. self.repo.get_worktree().stage(["foo"])
  6793. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6794. f.write("foo\n")
  6795. self.assertEqual([], list(porcelain.check_ignore(self.repo, [path])))
  6796. self.assertEqual(
  6797. ["foo"],
  6798. list(porcelain.check_ignore(self.repo, [path], no_index=True)),
  6799. )
  6800. def test_check_added_rel(self) -> None:
  6801. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  6802. f.write("BAR")
  6803. self.repo.get_worktree().stage(["foo"])
  6804. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6805. f.write("foo\n")
  6806. cwd = os.getcwd()
  6807. self.addCleanup(os.chdir, cwd)
  6808. os.mkdir(os.path.join(self.repo.path, "bar"))
  6809. os.chdir(os.path.join(self.repo.path, "bar"))
  6810. self.assertEqual(list(porcelain.check_ignore(self.repo, ["../foo"])), [])
  6811. self.assertEqual(
  6812. ["../foo"],
  6813. list(porcelain.check_ignore(self.repo, ["../foo"], no_index=True)),
  6814. )
  6815. class UpdateHeadTests(PorcelainTestCase):
  6816. def test_set_to_branch(self) -> None:
  6817. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6818. self.repo.refs[b"refs/heads/blah"] = c1.id
  6819. porcelain.update_head(self.repo, "blah")
  6820. self.assertEqual(c1.id, self.repo.head())
  6821. self.assertEqual(b"ref: refs/heads/blah", self.repo.refs.read_ref(b"HEAD"))
  6822. def test_set_to_branch_detached(self) -> None:
  6823. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6824. self.repo.refs[b"refs/heads/blah"] = c1.id
  6825. porcelain.update_head(self.repo, "blah", detached=True)
  6826. self.assertEqual(c1.id, self.repo.head())
  6827. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  6828. def test_set_to_commit_detached(self) -> None:
  6829. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6830. self.repo.refs[b"refs/heads/blah"] = c1.id
  6831. porcelain.update_head(self.repo, c1.id, detached=True)
  6832. self.assertEqual(c1.id, self.repo.head())
  6833. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  6834. def test_set_new_branch(self) -> None:
  6835. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6836. self.repo.refs[b"refs/heads/blah"] = c1.id
  6837. porcelain.update_head(self.repo, "blah", new_branch="bar")
  6838. self.assertEqual(c1.id, self.repo.head())
  6839. self.assertEqual(b"ref: refs/heads/bar", self.repo.refs.read_ref(b"HEAD"))
  6840. class MailmapTests(PorcelainTestCase):
  6841. def test_no_mailmap(self) -> None:
  6842. self.assertEqual(
  6843. b"Jelmer Vernooij <jelmer@samba.org>",
  6844. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  6845. )
  6846. def test_mailmap_lookup(self) -> None:
  6847. with open(os.path.join(self.repo.path, ".mailmap"), "wb") as f:
  6848. f.write(
  6849. b"""\
  6850. Jelmer Vernooij <jelmer@debian.org>
  6851. """
  6852. )
  6853. self.assertEqual(
  6854. b"Jelmer Vernooij <jelmer@debian.org>",
  6855. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  6856. )
  6857. class FsckTests(PorcelainTestCase):
  6858. def test_none(self) -> None:
  6859. self.assertEqual([], list(porcelain.fsck(self.repo)))
  6860. def test_git_dir(self) -> None:
  6861. obj = Tree()
  6862. a = Blob()
  6863. a.data = b"foo"
  6864. obj.add(b".git", 0o100644, a.id)
  6865. self.repo.object_store.add_objects([(a, None), (obj, None)])
  6866. self.assertEqual(
  6867. [(obj.id, "invalid name .git")],
  6868. [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)],
  6869. )
  6870. class DescribeTests(PorcelainTestCase):
  6871. def test_no_commits(self) -> None:
  6872. self.assertRaises(KeyError, porcelain.describe, self.repo.path)
  6873. def test_single_commit(self) -> None:
  6874. fullpath = os.path.join(self.repo.path, "foo")
  6875. with open(fullpath, "w") as f:
  6876. f.write("BAR")
  6877. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6878. sha = porcelain.commit(
  6879. self.repo.path,
  6880. message=b"Some message",
  6881. author=b"Joe <joe@example.com>",
  6882. committer=b"Bob <bob@example.com>",
  6883. )
  6884. self.assertEqual(
  6885. "g{}".format(sha[:7].decode("ascii")),
  6886. porcelain.describe(self.repo.path),
  6887. )
  6888. def test_tag(self) -> None:
  6889. fullpath = os.path.join(self.repo.path, "foo")
  6890. with open(fullpath, "w") as f:
  6891. f.write("BAR")
  6892. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6893. porcelain.commit(
  6894. self.repo.path,
  6895. message=b"Some message",
  6896. author=b"Joe <joe@example.com>",
  6897. committer=b"Bob <bob@example.com>",
  6898. )
  6899. porcelain.tag_create(
  6900. self.repo.path,
  6901. b"tryme",
  6902. b"foo <foo@bar.com>",
  6903. b"bar",
  6904. annotated=True,
  6905. )
  6906. self.assertEqual("tryme", porcelain.describe(self.repo.path))
  6907. def test_tag_and_commit(self) -> None:
  6908. fullpath = os.path.join(self.repo.path, "foo")
  6909. with open(fullpath, "w") as f:
  6910. f.write("BAR")
  6911. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6912. porcelain.commit(
  6913. self.repo.path,
  6914. message=b"Some message",
  6915. author=b"Joe <joe@example.com>",
  6916. committer=b"Bob <bob@example.com>",
  6917. )
  6918. porcelain.tag_create(
  6919. self.repo.path,
  6920. b"tryme",
  6921. b"foo <foo@bar.com>",
  6922. b"bar",
  6923. annotated=True,
  6924. )
  6925. with open(fullpath, "w") as f:
  6926. f.write("BAR2")
  6927. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6928. sha = porcelain.commit(
  6929. self.repo.path,
  6930. message=b"Some message",
  6931. author=b"Joe <joe@example.com>",
  6932. committer=b"Bob <bob@example.com>",
  6933. )
  6934. self.assertEqual(
  6935. "tryme-1-g{}".format(sha[:7].decode("ascii")),
  6936. porcelain.describe(self.repo.path),
  6937. )
  6938. def test_tag_and_commit_full(self) -> None:
  6939. fullpath = os.path.join(self.repo.path, "foo")
  6940. with open(fullpath, "w") as f:
  6941. f.write("BAR")
  6942. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6943. porcelain.commit(
  6944. self.repo.path,
  6945. message=b"Some message",
  6946. author=b"Joe <joe@example.com>",
  6947. committer=b"Bob <bob@example.com>",
  6948. )
  6949. porcelain.tag_create(
  6950. self.repo.path,
  6951. b"tryme",
  6952. b"foo <foo@bar.com>",
  6953. b"bar",
  6954. annotated=True,
  6955. )
  6956. with open(fullpath, "w") as f:
  6957. f.write("BAR2")
  6958. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6959. sha = porcelain.commit(
  6960. self.repo.path,
  6961. message=b"Some message",
  6962. author=b"Joe <joe@example.com>",
  6963. committer=b"Bob <bob@example.com>",
  6964. )
  6965. self.assertEqual(
  6966. "tryme-1-g{}".format(sha.decode("ascii")),
  6967. porcelain.describe(self.repo.path, abbrev=40),
  6968. )
  6969. def test_untagged_commit_abbreviation(self) -> None:
  6970. _, _, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]])
  6971. self.repo.refs[b"HEAD"] = c3.id
  6972. brief_description, complete_description = (
  6973. porcelain.describe(self.repo),
  6974. porcelain.describe(self.repo, abbrev=40),
  6975. )
  6976. self.assertTrue(complete_description.startswith(brief_description))
  6977. self.assertEqual(
  6978. "g{}".format(c3.id.decode("ascii")),
  6979. complete_description,
  6980. )
  6981. def test_hash_length_dynamic(self) -> None:
  6982. """Test that hash length adjusts based on uniqueness."""
  6983. fullpath = os.path.join(self.repo.path, "foo")
  6984. with open(fullpath, "w") as f:
  6985. f.write("content")
  6986. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6987. sha = porcelain.commit(
  6988. self.repo.path,
  6989. message=b"commit",
  6990. author=b"Joe <joe@example.com>",
  6991. committer=b"Bob <bob@example.com>",
  6992. )
  6993. # When abbrev is None, it should use find_unique_abbrev
  6994. result = porcelain.describe(self.repo.path)
  6995. # Should start with 'g' and have at least 7 characters
  6996. self.assertTrue(result.startswith("g"))
  6997. self.assertGreaterEqual(len(result[1:]), 7)
  6998. # Should be a prefix of the full SHA
  6999. self.assertTrue(sha.decode("ascii").startswith(result[1:]))
  7000. class PathToTreeTests(PorcelainTestCase):
  7001. def setUp(self) -> None:
  7002. super().setUp()
  7003. self.fp = os.path.join(self.test_dir, "bar")
  7004. with open(self.fp, "w") as f:
  7005. f.write("something")
  7006. oldcwd = os.getcwd()
  7007. self.addCleanup(os.chdir, oldcwd)
  7008. os.chdir(self.test_dir)
  7009. def test_path_to_tree_path_base(self) -> None:
  7010. self.assertEqual(b"bar", porcelain.path_to_tree_path(self.test_dir, self.fp))
  7011. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  7012. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "bar"))
  7013. cwd = os.getcwd()
  7014. self.assertEqual(
  7015. b"bar", porcelain.path_to_tree_path(".", os.path.join(cwd, "bar"))
  7016. )
  7017. self.assertEqual(b"bar", porcelain.path_to_tree_path(cwd, "bar"))
  7018. def test_path_to_tree_path_syntax(self) -> None:
  7019. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  7020. def test_path_to_tree_path_error(self) -> None:
  7021. with self.assertRaises(ValueError):
  7022. with tempfile.TemporaryDirectory() as od:
  7023. porcelain.path_to_tree_path(od, self.fp)
  7024. def test_path_to_tree_path_rel(self) -> None:
  7025. cwd = os.getcwd()
  7026. self.addCleanup(os.chdir, cwd)
  7027. os.mkdir(os.path.join(self.repo.path, "foo"))
  7028. os.mkdir(os.path.join(self.repo.path, "foo/bar"))
  7029. os.chdir(os.path.join(self.repo.path, "foo/bar"))
  7030. with open("baz", "w") as f:
  7031. f.write("contents")
  7032. self.assertEqual(b"bar/baz", porcelain.path_to_tree_path("..", "baz"))
  7033. self.assertEqual(
  7034. b"bar/baz",
  7035. porcelain.path_to_tree_path(
  7036. os.path.join(os.getcwd(), ".."),
  7037. os.path.join(os.getcwd(), "baz"),
  7038. ),
  7039. )
  7040. self.assertEqual(
  7041. b"bar/baz",
  7042. porcelain.path_to_tree_path("..", os.path.join(os.getcwd(), "baz")),
  7043. )
  7044. self.assertEqual(
  7045. b"bar/baz",
  7046. porcelain.path_to_tree_path(os.path.join(os.getcwd(), ".."), "baz"),
  7047. )
  7048. class GetObjectByPathTests(PorcelainTestCase):
  7049. def test_simple(self) -> None:
  7050. fullpath = os.path.join(self.repo.path, "foo")
  7051. with open(fullpath, "w") as f:
  7052. f.write("BAR")
  7053. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7054. porcelain.commit(
  7055. self.repo.path,
  7056. message=b"Some message",
  7057. author=b"Joe <joe@example.com>",
  7058. committer=b"Bob <bob@example.com>",
  7059. )
  7060. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  7061. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  7062. def test_encoding(self) -> None:
  7063. fullpath = os.path.join(self.repo.path, "foo")
  7064. with open(fullpath, "w") as f:
  7065. f.write("BAR")
  7066. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7067. porcelain.commit(
  7068. self.repo.path,
  7069. message=b"Some message",
  7070. author=b"Joe <joe@example.com>",
  7071. committer=b"Bob <bob@example.com>",
  7072. encoding=b"utf-8",
  7073. )
  7074. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  7075. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  7076. def test_missing(self) -> None:
  7077. self.assertRaises(KeyError, porcelain.get_object_by_path, self.repo, "foo")
  7078. class WriteTreeTests(PorcelainTestCase):
  7079. def test_simple(self) -> None:
  7080. fullpath = os.path.join(self.repo.path, "foo")
  7081. with open(fullpath, "w") as f:
  7082. f.write("BAR")
  7083. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7084. self.assertEqual(
  7085. b"d2092c8a9f311f0311083bf8d177f2ca0ab5b241",
  7086. porcelain.write_tree(self.repo),
  7087. )
  7088. class ActiveBranchTests(PorcelainTestCase):
  7089. def test_simple(self) -> None:
  7090. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  7091. class BranchTrackingTests(PorcelainTestCase):
  7092. def test_get_branch_merge(self) -> None:
  7093. # Set up branch tracking configuration
  7094. config = self.repo.get_config()
  7095. config.set((b"branch", b"master"), b"remote", b"origin")
  7096. config.set((b"branch", b"master"), b"merge", b"refs/heads/main")
  7097. config.write_to_path()
  7098. # Test getting merge ref for current branch
  7099. merge_ref = porcelain.get_branch_merge(self.repo)
  7100. self.assertEqual(b"refs/heads/main", merge_ref)
  7101. # Test getting merge ref for specific branch
  7102. merge_ref = porcelain.get_branch_merge(self.repo, b"master")
  7103. self.assertEqual(b"refs/heads/main", merge_ref)
  7104. # Test branch without merge config
  7105. with self.assertRaises(KeyError):
  7106. porcelain.get_branch_merge(self.repo, b"nonexistent")
  7107. def test_set_branch_tracking(self) -> None:
  7108. # Create a new branch
  7109. _sha, _ = _commit_file_with_content(self.repo, "foo", "content\n")
  7110. porcelain.branch_create(self.repo, "feature")
  7111. # Set up tracking
  7112. porcelain.set_branch_tracking(
  7113. self.repo, b"feature", b"upstream", b"refs/heads/main"
  7114. )
  7115. # Verify configuration was written
  7116. config = self.repo.get_config()
  7117. self.assertEqual(b"upstream", config.get((b"branch", b"feature"), b"remote"))
  7118. self.assertEqual(
  7119. b"refs/heads/main", config.get((b"branch", b"feature"), b"merge")
  7120. )
  7121. class FindUniqueAbbrevTests(PorcelainTestCase):
  7122. def test_simple(self) -> None:
  7123. c1, _c2, c3 = build_commit_graph(
  7124. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  7125. )
  7126. self.repo.refs[b"HEAD"] = c3.id
  7127. self.assertEqual(
  7128. c1.id.decode("ascii")[:7],
  7129. porcelain.find_unique_abbrev(self.repo.object_store, c1.id),
  7130. )
  7131. class PackRefsTests(PorcelainTestCase):
  7132. def test_all(self) -> None:
  7133. c1, c2, c3 = build_commit_graph(
  7134. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  7135. )
  7136. self.repo.refs[b"HEAD"] = c3.id
  7137. self.repo.refs[b"refs/heads/master"] = c2.id
  7138. self.repo.refs[b"refs/tags/foo"] = c1.id
  7139. porcelain.pack_refs(self.repo, all=True)
  7140. self.assertEqual(
  7141. self.repo.refs.get_packed_refs(),
  7142. {
  7143. b"refs/heads/master": c2.id,
  7144. b"refs/tags/foo": c1.id,
  7145. },
  7146. )
  7147. def test_not_all(self) -> None:
  7148. c1, c2, c3 = build_commit_graph(
  7149. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  7150. )
  7151. self.repo.refs[b"HEAD"] = c3.id
  7152. self.repo.refs[b"refs/heads/master"] = c2.id
  7153. self.repo.refs[b"refs/tags/foo"] = c1.id
  7154. porcelain.pack_refs(self.repo)
  7155. self.assertEqual(
  7156. self.repo.refs.get_packed_refs(),
  7157. {
  7158. b"refs/tags/foo": c1.id,
  7159. },
  7160. )
  7161. class ServerTests(PorcelainTestCase):
  7162. @contextlib.contextmanager
  7163. def _serving(self):
  7164. with make_server("localhost", 0, self.app) as server:
  7165. thread = threading.Thread(target=server.serve_forever, daemon=True)
  7166. thread.start()
  7167. try:
  7168. yield f"http://localhost:{server.server_port}"
  7169. finally:
  7170. server.shutdown()
  7171. thread.join(10)
  7172. def setUp(self) -> None:
  7173. super().setUp()
  7174. self.served_repo_path = os.path.join(self.test_dir, "served_repo.git")
  7175. self.served_repo = Repo.init_bare(self.served_repo_path, mkdir=True)
  7176. self.addCleanup(self.served_repo.close)
  7177. backend = DictBackend({"/": self.served_repo})
  7178. self.app = make_wsgi_chain(backend)
  7179. def test_pull(self) -> None:
  7180. (c1,) = build_commit_graph(self.served_repo.object_store, [[1]])
  7181. self.served_repo.refs[b"refs/heads/master"] = c1.id
  7182. with self._serving() as url:
  7183. porcelain.pull(self.repo, url, "master")
  7184. def test_push(self) -> None:
  7185. (c1,) = build_commit_graph(self.repo.object_store, [[1]])
  7186. self.repo.refs[b"refs/heads/master"] = c1.id
  7187. with self._serving() as url:
  7188. porcelain.push(self.repo, url, "master")
  7189. class ForEachTests(PorcelainTestCase):
  7190. def setUp(self) -> None:
  7191. super().setUp()
  7192. c1, c2, c3, c4 = build_commit_graph(
  7193. self.repo.object_store, [[1], [2, 1], [3, 1, 2], [4]]
  7194. )
  7195. porcelain.tag_create(
  7196. self.repo.path,
  7197. b"v0.1",
  7198. objectish=c1.id,
  7199. annotated=True,
  7200. message=b"0.1",
  7201. )
  7202. porcelain.tag_create(
  7203. self.repo.path,
  7204. b"v1.0",
  7205. objectish=c2.id,
  7206. annotated=True,
  7207. message=b"1.0",
  7208. )
  7209. porcelain.tag_create(self.repo.path, b"simple-tag", objectish=c3.id)
  7210. porcelain.tag_create(
  7211. self.repo.path,
  7212. b"v1.1",
  7213. objectish=c4.id,
  7214. annotated=True,
  7215. message=b"1.1",
  7216. )
  7217. porcelain.branch_create(
  7218. self.repo.path, b"feat", objectish=c2.id.decode("ascii")
  7219. )
  7220. self.repo.refs[b"HEAD"] = c4.id
  7221. def test_for_each_ref(self) -> None:
  7222. refs = porcelain.for_each_ref(self.repo)
  7223. self.assertEqual(
  7224. [(object_type, tag) for _, object_type, tag in refs],
  7225. [
  7226. (b"commit", b"refs/heads/feat"),
  7227. (b"commit", b"refs/heads/master"),
  7228. (b"commit", b"refs/tags/simple-tag"),
  7229. (b"tag", b"refs/tags/v0.1"),
  7230. (b"tag", b"refs/tags/v1.0"),
  7231. (b"tag", b"refs/tags/v1.1"),
  7232. ],
  7233. )
  7234. def test_for_each_ref_pattern(self) -> None:
  7235. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v*")
  7236. self.assertEqual(
  7237. [(object_type, tag) for _, object_type, tag in versions],
  7238. [
  7239. (b"tag", b"refs/tags/v0.1"),
  7240. (b"tag", b"refs/tags/v1.0"),
  7241. (b"tag", b"refs/tags/v1.1"),
  7242. ],
  7243. )
  7244. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v1.?")
  7245. self.assertEqual(
  7246. [(object_type, tag) for _, object_type, tag in versions],
  7247. [
  7248. (b"tag", b"refs/tags/v1.0"),
  7249. (b"tag", b"refs/tags/v1.1"),
  7250. ],
  7251. )
  7252. class SparseCheckoutTests(PorcelainTestCase):
  7253. """Integration tests for Dulwich's sparse checkout feature."""
  7254. # NOTE: We do NOT override `setUp()` here because the parent class
  7255. # (PorcelainTestCase) already:
  7256. # 1) Creates self.test_dir = a unique temp dir
  7257. # 2) Creates a subdir named "repo"
  7258. # 3) Calls Repo.init() on that path
  7259. # Re-initializing again caused FileExistsError.
  7260. #
  7261. # Utility/Placeholder
  7262. #
  7263. def sparse_checkout(self, repo, patterns, force=False):
  7264. """Wrapper around the actual porcelain.sparse_checkout function
  7265. to handle any test-specific setup or logging.
  7266. """
  7267. return porcelain.sparse_checkout(repo, patterns, force=force)
  7268. def _write_file(self, rel_path, content):
  7269. """Helper to write a file in the repository working tree."""
  7270. abs_path = os.path.join(self.repo_path, rel_path)
  7271. os.makedirs(os.path.dirname(abs_path), exist_ok=True)
  7272. with open(abs_path, "w") as f:
  7273. f.write(content)
  7274. return abs_path
  7275. def _commit_file(self, rel_path, content):
  7276. """Helper to write, add, and commit a file."""
  7277. abs_path = self._write_file(rel_path, content)
  7278. add(self.repo_path, paths=[abs_path])
  7279. commit(self.repo_path, message=b"Added " + rel_path.encode("utf-8"))
  7280. def _list_wtree_files(self):
  7281. """Return a set of all files (not dirs) present
  7282. in the working tree, ignoring .git/.
  7283. """
  7284. found_files = set()
  7285. for root, dirs, files in os.walk(self.repo_path):
  7286. # Skip .git in the walk
  7287. if ".git" in dirs:
  7288. dirs.remove(".git")
  7289. for filename in files:
  7290. file_rel = os.path.relpath(os.path.join(root, filename), self.repo_path)
  7291. found_files.add(file_rel)
  7292. return found_files
  7293. def test_only_included_paths_appear_in_wtree(self):
  7294. """Only included paths remain in the working tree, excluded paths are removed.
  7295. Commits two files, "keep_me.txt" and "exclude_me.txt". Then applies a
  7296. sparse-checkout pattern containing only "keep_me.txt". Ensures that
  7297. the latter remains in the working tree, while "exclude_me.txt" is
  7298. removed. This verifies correct application of sparse-checkout patterns
  7299. to remove files not listed.
  7300. """
  7301. self._commit_file("keep_me.txt", "I'll stay\n")
  7302. self._commit_file("exclude_me.txt", "I'll be excluded\n")
  7303. patterns = ["keep_me.txt"]
  7304. self.sparse_checkout(self.repo, patterns)
  7305. actual_files = self._list_wtree_files()
  7306. expected_files = {"keep_me.txt"}
  7307. self.assertEqual(
  7308. expected_files,
  7309. actual_files,
  7310. f"Expected only {expected_files}, but found {actual_files}",
  7311. )
  7312. def test_previously_included_paths_become_excluded(self):
  7313. """Previously included files become excluded after pattern changes.
  7314. Verifies that files initially brought into the working tree (e.g.,
  7315. by including `data/`) can later be excluded by narrowing the
  7316. sparse-checkout pattern to just `data/included_1.txt`. Confirms that
  7317. the file `data/included_2.txt` remains in the index with
  7318. skip-worktree set (rather than being removed entirely), ensuring
  7319. data is not lost and Dulwich correctly updates the index flags.
  7320. """
  7321. self._commit_file("data/included_1.txt", "some content\n")
  7322. self._commit_file("data/included_2.txt", "other content\n")
  7323. initial_patterns = ["data/"]
  7324. self.sparse_checkout(self.repo, initial_patterns)
  7325. updated_patterns = ["data/included_1.txt"]
  7326. self.sparse_checkout(self.repo, updated_patterns)
  7327. actual_files = self._list_wtree_files()
  7328. expected_files = {os.path.join("data", "included_1.txt")}
  7329. self.assertEqual(expected_files, actual_files)
  7330. idx = self.repo.open_index()
  7331. self.assertIn(b"data/included_2.txt", idx)
  7332. entry = idx[b"data/included_2.txt"]
  7333. self.assertTrue(entry.skip_worktree)
  7334. def test_force_removes_local_changes_for_excluded_paths(self):
  7335. """Forced sparse checkout removes local modifications for newly excluded paths.
  7336. Verifies that specifying force=True allows destructive operations
  7337. which discard uncommitted changes. First, we commit "file1.txt" and
  7338. then modify it. Next, we apply a pattern that excludes the file,
  7339. using force=True. The local modifications (and the file) should
  7340. be removed, leaving the working tree empty.
  7341. """
  7342. self._commit_file("file1.txt", "original content\n")
  7343. file1_path = os.path.join(self.repo_path, "file1.txt")
  7344. with open(file1_path, "a") as f:
  7345. f.write("local changes!\n")
  7346. new_patterns = ["some_other_file.txt"]
  7347. self.sparse_checkout(self.repo, new_patterns, force=True)
  7348. actual_files = self._list_wtree_files()
  7349. self.assertEqual(
  7350. set(),
  7351. actual_files,
  7352. "Force-sparse-checkout did not remove file with local changes.",
  7353. )
  7354. def test_destructive_refuse_uncommitted_changes_without_force(self):
  7355. """Fail on uncommitted changes for newly excluded paths without force.
  7356. Ensures that a sparse checkout is blocked if it would remove local
  7357. modifications from the working tree. We commit 'config.yaml', then
  7358. modify it, and finally attempt to exclude it via new patterns without
  7359. using force=True. This should raise a CheckoutError rather than
  7360. discarding the local changes.
  7361. """
  7362. self._commit_file("config.yaml", "initial\n")
  7363. cfg_path = os.path.join(self.repo_path, "config.yaml")
  7364. with open(cfg_path, "a") as f:
  7365. f.write("local modifications\n")
  7366. exclude_patterns = ["docs/"]
  7367. with self.assertRaises(CheckoutError):
  7368. self.sparse_checkout(self.repo, exclude_patterns, force=False)
  7369. def test_fnmatch_gitignore_pattern_expansion(self):
  7370. """Reading/writing patterns align with gitignore/fnmatch expansions.
  7371. Ensures that `sparse_checkout` interprets wildcard patterns (like `*.py`)
  7372. in the same way Git's sparse-checkout would. Multiple files are committed
  7373. to `src/` (e.g. `foo.py`, `foo_test.py`, `foo_helper.py`) and to `docs/`.
  7374. Then the pattern `src/foo*.py` is applied, confirming that only the
  7375. matching Python files remain in the working tree while the Markdown file
  7376. under `docs/` is excluded.
  7377. Finally, verifies that the `.git/info/sparse-checkout` file contains the
  7378. specified wildcard pattern (`src/foo*.py`), ensuring correct round-trip
  7379. of user-supplied patterns.
  7380. """
  7381. self._commit_file("src/foo.py", "print('hello')\n")
  7382. self._commit_file("src/foo_test.py", "print('test')\n")
  7383. self._commit_file("docs/readme.md", "# docs\n")
  7384. self._commit_file("src/foo_helper.py", "print('helper')\n")
  7385. patterns = ["src/foo*.py"]
  7386. self.sparse_checkout(self.repo, patterns)
  7387. actual_files = self._list_wtree_files()
  7388. expected_files = {
  7389. os.path.join("src", "foo.py"),
  7390. os.path.join("src", "foo_test.py"),
  7391. os.path.join("src", "foo_helper.py"),
  7392. }
  7393. self.assertEqual(
  7394. expected_files,
  7395. actual_files,
  7396. "Wildcard pattern not matched as expected. Either too strict or too broad.",
  7397. )
  7398. sc_file = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7399. self.assertTrue(os.path.isfile(sc_file))
  7400. with open(sc_file) as f:
  7401. lines = f.read().strip().split()
  7402. self.assertIn("src/foo*.py", lines)
  7403. class ConeModeTests(PorcelainTestCase):
  7404. """Provide integration tests for Dulwich's cone mode sparse checkout.
  7405. This test suite verifies the expected behavior for:
  7406. * cone_mode_init
  7407. * cone_mode_set
  7408. * cone_mode_add
  7409. Although Dulwich does not yet implement cone mode, these tests are
  7410. prepared in advance to guide future development.
  7411. """
  7412. def setUp(self):
  7413. """Set up a fresh repository for each test.
  7414. This method creates a new empty repo_path and Repo object
  7415. as provided by the PorcelainTestCase base class.
  7416. """
  7417. super().setUp()
  7418. def _commit_file(self, rel_path, content=b"contents"):
  7419. """Add a file at the given relative path and commit it.
  7420. Creates necessary directories, writes the file content,
  7421. stages, and commits. The commit message and author/committer
  7422. are also provided.
  7423. """
  7424. full_path = os.path.join(self.repo_path, rel_path)
  7425. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  7426. with open(full_path, "wb") as f:
  7427. f.write(content)
  7428. porcelain.add(self.repo_path, paths=[full_path])
  7429. porcelain.commit(
  7430. self.repo_path,
  7431. message=b"Adding " + rel_path.encode("utf-8"),
  7432. author=b"Test Author <author@example.com>",
  7433. committer=b"Test Committer <committer@example.com>",
  7434. )
  7435. def _list_wtree_files(self):
  7436. """Return a set of all file paths relative to the repository root.
  7437. Walks the working tree, skipping the .git directory.
  7438. """
  7439. found_files = set()
  7440. for root, dirs, files in os.walk(self.repo_path):
  7441. if ".git" in dirs:
  7442. dirs.remove(".git")
  7443. for fn in files:
  7444. relp = os.path.relpath(os.path.join(root, fn), self.repo_path)
  7445. found_files.add(relp)
  7446. return found_files
  7447. def test_init_excludes_everything(self):
  7448. """Verify that cone_mode_init writes minimal patterns and empties the working tree.
  7449. Make some dummy files, commit them, then call cone_mode_init. Confirm
  7450. that the working tree is empty, the sparse-checkout file has the
  7451. minimal patterns (/*, !/*/), and the relevant config values are set.
  7452. """
  7453. self._commit_file("docs/readme.md", b"# doc\n")
  7454. self._commit_file("src/main.py", b"print('hello')\n")
  7455. porcelain.cone_mode_init(self.repo)
  7456. actual_files = self._list_wtree_files()
  7457. self.assertEqual(
  7458. set(),
  7459. actual_files,
  7460. "cone_mode_init did not exclude all files from the working tree.",
  7461. )
  7462. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7463. with open(sp_path) as f:
  7464. lines = [ln.strip() for ln in f if ln.strip()]
  7465. self.assertIn("/*", lines)
  7466. self.assertIn("!/*/", lines)
  7467. config = self.repo.get_config()
  7468. self.assertEqual(config.get((b"core",), b"sparseCheckout"), b"true")
  7469. self.assertEqual(config.get((b"core",), b"sparseCheckoutCone"), b"true")
  7470. def test_set_specific_dirs(self):
  7471. """Verify that cone_mode_set overwrites the included directories to only the specified ones.
  7472. Initializes cone mode, commits some files, then calls cone_mode_set with
  7473. a list of directories. Expects that only those directories remain in the
  7474. working tree.
  7475. """
  7476. porcelain.cone_mode_init(self.repo)
  7477. self._commit_file("docs/readme.md", b"# doc\n")
  7478. self._commit_file("src/main.py", b"print('hello')\n")
  7479. self._commit_file("tests/test_foo.py", b"# tests\n")
  7480. # Everything is still excluded initially by init.
  7481. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  7482. actual_files = self._list_wtree_files()
  7483. expected_files = {
  7484. os.path.join("docs", "readme.md"),
  7485. os.path.join("src", "main.py"),
  7486. }
  7487. self.assertEqual(
  7488. expected_files,
  7489. actual_files,
  7490. "Did not see only the 'docs/' and 'src/' dirs in the working tree.",
  7491. )
  7492. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7493. with open(sp_path) as f:
  7494. lines = [ln.strip() for ln in f if ln.strip()]
  7495. # For standard cone mode, we'd expect lines like:
  7496. # /* (include top-level files)
  7497. # !/*/ (exclude subdirectories)
  7498. # !/docs/ (re-include docs)
  7499. # !/src/ (re-include src)
  7500. # Instead of the wildcard-based lines the old test used.
  7501. self.assertIn("/*", lines)
  7502. self.assertIn("!/*/", lines)
  7503. self.assertIn("/docs/", lines)
  7504. self.assertIn("/src/", lines)
  7505. self.assertNotIn("/tests/", lines)
  7506. def test_set_overwrites_old_dirs(self):
  7507. """Ensure that calling cone_mode_set again overwrites old includes.
  7508. Initializes cone mode, includes two directories, then calls
  7509. cone_mode_set again with a different directory to confirm the
  7510. new set of includes replaces the old.
  7511. """
  7512. porcelain.cone_mode_init(self.repo)
  7513. self._commit_file("docs/readme.md")
  7514. self._commit_file("src/main.py")
  7515. self._commit_file("tests/test_bar.py")
  7516. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  7517. self.assertEqual(
  7518. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  7519. self._list_wtree_files(),
  7520. )
  7521. # Overwrite includes, now only 'tests'
  7522. porcelain.cone_mode_set(self.repo, dirs=["tests"], force=True)
  7523. actual_files = self._list_wtree_files()
  7524. expected_files = {os.path.join("tests", "test_bar.py")}
  7525. self.assertEqual(expected_files, actual_files)
  7526. def test_force_removal_of_local_mods(self):
  7527. """Confirm that force=True removes local changes in excluded paths.
  7528. cone_mode_init and cone_mode_set are called, a file is locally modified,
  7529. and then cone_mode_set is called again with force=True to exclude that path.
  7530. The excluded file should be removed with no CheckoutError.
  7531. """
  7532. porcelain.cone_mode_init(self.repo)
  7533. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  7534. self._commit_file("docs/readme.md", b"Docs stuff\n")
  7535. self._commit_file("src/main.py", b"print('hello')\n")
  7536. # Modify src/main.py
  7537. with open(os.path.join(self.repo_path, "src/main.py"), "ab") as f:
  7538. f.write(b"extra line\n")
  7539. # Exclude src/ with force=True
  7540. porcelain.cone_mode_set(self.repo, dirs=["docs"], force=True)
  7541. actual_files = self._list_wtree_files()
  7542. expected_files = {os.path.join("docs", "readme.md")}
  7543. self.assertEqual(expected_files, actual_files)
  7544. def test_add_and_merge_dirs(self):
  7545. """Verify that cone_mode_add merges new directories instead of overwriting them.
  7546. After initializing cone mode and including a single directory, call
  7547. cone_mode_add with a new directory. Confirm that both directories
  7548. remain included. Repeat for an additional directory to ensure it
  7549. is merged, not overwritten.
  7550. """
  7551. porcelain.cone_mode_init(self.repo)
  7552. self._commit_file("docs/readme.md", b"# doc\n")
  7553. self._commit_file("src/main.py", b"print('hello')\n")
  7554. self._commit_file("tests/test_bar.py", b"# tests\n")
  7555. # Include "docs" only
  7556. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  7557. self.assertEqual({os.path.join("docs", "readme.md")}, self._list_wtree_files())
  7558. # Add "src"
  7559. porcelain.cone_mode_add(self.repo, dirs=["src"])
  7560. actual_files = self._list_wtree_files()
  7561. self.assertEqual(
  7562. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  7563. actual_files,
  7564. )
  7565. # Add "tests" as well
  7566. porcelain.cone_mode_add(self.repo, dirs=["tests"])
  7567. actual_files = self._list_wtree_files()
  7568. expected_files = {
  7569. os.path.join("docs", "readme.md"),
  7570. os.path.join("src", "main.py"),
  7571. os.path.join("tests", "test_bar.py"),
  7572. }
  7573. self.assertEqual(expected_files, actual_files)
  7574. # Check .git/info/sparse-checkout
  7575. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7576. with open(sp_path) as f:
  7577. lines = [ln.strip() for ln in f if ln.strip()]
  7578. # Standard cone mode lines:
  7579. # "/*" -> include top-level
  7580. # "!/*/" -> exclude subdirectories
  7581. # "!/docs/", "!/src/", "!/tests/" -> re-include the directories we added
  7582. self.assertIn("/*", lines)
  7583. self.assertIn("!/*/", lines)
  7584. self.assertIn("/docs/", lines)
  7585. self.assertIn("/src/", lines)
  7586. self.assertIn("/tests/", lines)
  7587. class UnpackObjectsTest(PorcelainTestCase):
  7588. def test_unpack_objects(self):
  7589. """Test unpacking objects from a pack file."""
  7590. # Create a test repository with some objects
  7591. b1 = Blob()
  7592. b1.data = b"test content 1"
  7593. b2 = Blob()
  7594. b2.data = b"test content 2"
  7595. # Add objects to the repo
  7596. self.repo.object_store.add_object(b1)
  7597. self.repo.object_store.add_object(b2)
  7598. # Create a pack file with these objects
  7599. pack_path = os.path.join(self.test_dir, "test_pack")
  7600. with (
  7601. open(pack_path + ".pack", "wb") as pack_f,
  7602. open(pack_path + ".idx", "wb") as idx_f,
  7603. ):
  7604. porcelain.pack_objects(
  7605. self.repo,
  7606. [b1.id, b2.id],
  7607. pack_f,
  7608. idx_f,
  7609. )
  7610. # Create a new repository to unpack into
  7611. target_repo_path = os.path.join(self.test_dir, "target_repo")
  7612. target_repo = Repo.init(target_repo_path, mkdir=True)
  7613. self.addCleanup(target_repo.close)
  7614. # Unpack the objects
  7615. count = porcelain.unpack_objects(pack_path + ".pack", target_repo_path)
  7616. # Verify the objects were unpacked
  7617. self.assertEqual(2, count)
  7618. self.assertIn(b1.id, target_repo.object_store)
  7619. self.assertIn(b2.id, target_repo.object_store)
  7620. # Verify the content is correct
  7621. unpacked_b1 = target_repo.object_store[b1.id]
  7622. unpacked_b2 = target_repo.object_store[b2.id]
  7623. self.assertEqual(b1.data, unpacked_b1.data)
  7624. self.assertEqual(b2.data, unpacked_b2.data)
  7625. class CountObjectsTests(PorcelainTestCase):
  7626. def test_count_objects_empty_repo(self):
  7627. """Test counting objects in an empty repository."""
  7628. stats = porcelain.count_objects(self.repo)
  7629. self.assertEqual(0, stats.count)
  7630. self.assertEqual(0, stats.size)
  7631. def test_count_objects_verbose_empty_repo(self):
  7632. """Test verbose counting in an empty repository."""
  7633. stats = porcelain.count_objects(self.repo, verbose=True)
  7634. self.assertEqual(0, stats.count)
  7635. self.assertEqual(0, stats.size)
  7636. self.assertEqual(0, stats.in_pack)
  7637. self.assertEqual(0, stats.packs)
  7638. self.assertEqual(0, stats.size_pack)
  7639. def test_count_objects_with_loose_objects(self):
  7640. """Test counting loose objects."""
  7641. # Create some loose objects
  7642. blob1 = make_object(Blob, data=b"data1")
  7643. blob2 = make_object(Blob, data=b"data2")
  7644. self.repo.object_store.add_object(blob1)
  7645. self.repo.object_store.add_object(blob2)
  7646. stats = porcelain.count_objects(self.repo)
  7647. self.assertEqual(2, stats.count)
  7648. self.assertGreater(stats.size, 0)
  7649. def test_count_objects_verbose_with_objects(self):
  7650. """Test verbose counting with both loose and packed objects."""
  7651. # Add some loose objects
  7652. for i in range(3):
  7653. blob = make_object(Blob, data=f"data{i}".encode())
  7654. self.repo.object_store.add_object(blob)
  7655. # Create a simple commit to have some objects in a pack
  7656. tree = Tree()
  7657. c1 = make_commit(tree=tree.id, message=b"Test commit")
  7658. self.repo.object_store.add_objects([(tree, None), (c1, None)])
  7659. self.repo.refs[b"HEAD"] = c1.id
  7660. # Repack to create a pack file
  7661. porcelain.repack(self.repo)
  7662. stats = porcelain.count_objects(self.repo, verbose=True)
  7663. # After repacking, loose objects might be cleaned up
  7664. self.assertIsInstance(stats.count, int)
  7665. self.assertIsInstance(stats.size, int)
  7666. self.assertGreater(stats.in_pack, 0) # Should have packed objects
  7667. self.assertGreater(stats.packs, 0) # Should have at least one pack
  7668. self.assertGreater(stats.size_pack, 0) # Pack should have size
  7669. # Verify it's the correct dataclass type
  7670. self.assertIsInstance(stats, CountObjectsResult)
  7671. class PruneTests(PorcelainTestCase):
  7672. def test_prune_removes_old_tempfiles(self):
  7673. """Test that prune removes old temporary files."""
  7674. # Create an old temporary file in the objects directory
  7675. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7676. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_test")
  7677. with open(tmp_pack_path, "wb") as f:
  7678. f.write(b"old temporary data")
  7679. # Make it old
  7680. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  7681. os.utime(tmp_pack_path, (old_time, old_time))
  7682. # Run prune
  7683. porcelain.prune(self.repo.path)
  7684. # Verify the file was removed
  7685. self.assertFalse(os.path.exists(tmp_pack_path))
  7686. def test_prune_keeps_recent_tempfiles(self):
  7687. """Test that prune keeps recent temporary files."""
  7688. # Create a recent temporary file
  7689. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7690. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_recent")
  7691. with open(tmp_pack_path, "wb") as f:
  7692. f.write(b"recent temporary data")
  7693. self.addCleanup(os.remove, tmp_pack_path)
  7694. # Run prune
  7695. porcelain.prune(self.repo.path)
  7696. # Verify the file was NOT removed
  7697. self.assertTrue(os.path.exists(tmp_pack_path))
  7698. def test_prune_with_custom_grace_period(self):
  7699. """Test prune with custom grace period."""
  7700. # Create a 1-hour-old temporary file
  7701. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7702. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_1hour")
  7703. with open(tmp_pack_path, "wb") as f:
  7704. f.write(b"1 hour old data")
  7705. # Make it 1 hour old
  7706. old_time = time.time() - 3600
  7707. os.utime(tmp_pack_path, (old_time, old_time))
  7708. # Prune with 30-minute grace period should remove it
  7709. porcelain.prune(self.repo.path, grace_period=1800)
  7710. # Verify the file was removed
  7711. self.assertFalse(os.path.exists(tmp_pack_path))
  7712. def test_prune_dry_run(self):
  7713. """Test prune in dry-run mode."""
  7714. # Create an old temporary file
  7715. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7716. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_dryrun")
  7717. with open(tmp_pack_path, "wb") as f:
  7718. f.write(b"old temporary data")
  7719. self.addCleanup(os.remove, tmp_pack_path)
  7720. # Make it old
  7721. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  7722. os.utime(tmp_pack_path, (old_time, old_time))
  7723. # Run prune in dry-run mode
  7724. porcelain.prune(self.repo.path, dry_run=True)
  7725. # Verify the file was NOT removed (dry run)
  7726. self.assertTrue(os.path.exists(tmp_pack_path))
  7727. class FilterBranchTests(PorcelainTestCase):
  7728. def setUp(self):
  7729. super().setUp()
  7730. # Create initial commits with different authors
  7731. from dulwich.objects import Commit, Tree
  7732. # Create actual tree and blob objects
  7733. tree = Tree()
  7734. self.repo.object_store.add_object(tree)
  7735. c1 = Commit()
  7736. c1.tree = tree.id
  7737. c1.parents = []
  7738. c1.author = b"Old Author <old@example.com>"
  7739. c1.author_time = 1000
  7740. c1.author_timezone = 0
  7741. c1.committer = b"Old Committer <old@example.com>"
  7742. c1.commit_time = 1000
  7743. c1.commit_timezone = 0
  7744. c1.message = b"Initial commit"
  7745. self.repo.object_store.add_object(c1)
  7746. c2 = Commit()
  7747. c2.tree = tree.id
  7748. c2.parents = [c1.id]
  7749. c2.author = b"Another Author <another@example.com>"
  7750. c2.author_time = 2000
  7751. c2.author_timezone = 0
  7752. c2.committer = b"Another Committer <another@example.com>"
  7753. c2.commit_time = 2000
  7754. c2.commit_timezone = 0
  7755. c2.message = b"Second commit\n\nWith body"
  7756. self.repo.object_store.add_object(c2)
  7757. c3 = Commit()
  7758. c3.tree = tree.id
  7759. c3.parents = [c2.id]
  7760. c3.author = b"Third Author <third@example.com>"
  7761. c3.author_time = 3000
  7762. c3.author_timezone = 0
  7763. c3.committer = b"Third Committer <third@example.com>"
  7764. c3.commit_time = 3000
  7765. c3.commit_timezone = 0
  7766. c3.message = b"Third commit"
  7767. self.repo.object_store.add_object(c3)
  7768. self.repo.refs[b"refs/heads/master"] = c3.id
  7769. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  7770. # Store IDs for test assertions
  7771. self.c1_id = c1.id
  7772. self.c2_id = c2.id
  7773. self.c3_id = c3.id
  7774. def test_filter_branch_author(self):
  7775. """Test filtering branch with author changes."""
  7776. def filter_author(author):
  7777. # Change all authors to "New Author"
  7778. return b"New Author <new@example.com>"
  7779. result = porcelain.filter_branch(
  7780. self.repo_path, "master", filter_author=filter_author
  7781. )
  7782. # Check that we have mappings for all commits
  7783. self.assertEqual(len(result), 3)
  7784. # Verify the branch ref was updated
  7785. new_head = self.repo.refs[b"refs/heads/master"]
  7786. self.assertNotEqual(new_head, self.c3_id)
  7787. # Verify the original ref was saved
  7788. original_ref = self.repo.refs[b"refs/original/refs/heads/master"]
  7789. self.assertEqual(original_ref, self.c3_id)
  7790. # Check that authors were updated
  7791. new_commit = self.repo[new_head]
  7792. self.assertEqual(new_commit.author, b"New Author <new@example.com>")
  7793. # Check parent chain
  7794. parent = self.repo[new_commit.parents[0]]
  7795. self.assertEqual(parent.author, b"New Author <new@example.com>")
  7796. def test_filter_branch_message(self):
  7797. """Test filtering branch with message changes."""
  7798. def filter_message(message):
  7799. # Add prefix to all messages
  7800. return b"[FILTERED] " + message
  7801. porcelain.filter_branch(self.repo_path, "master", filter_message=filter_message)
  7802. # Verify messages were updated
  7803. new_head = self.repo.refs[b"refs/heads/master"]
  7804. new_commit = self.repo[new_head]
  7805. self.assertTrue(new_commit.message.startswith(b"[FILTERED] "))
  7806. def test_filter_branch_custom_filter(self):
  7807. """Test filtering branch with custom filter function."""
  7808. def custom_filter(commit):
  7809. # Change both author and message
  7810. return {
  7811. "author": b"Custom Author <custom@example.com>",
  7812. "message": b"Custom: " + commit.message,
  7813. }
  7814. porcelain.filter_branch(self.repo_path, "master", filter_fn=custom_filter)
  7815. # Verify custom filter was applied
  7816. new_head = self.repo.refs[b"refs/heads/master"]
  7817. new_commit = self.repo[new_head]
  7818. self.assertEqual(new_commit.author, b"Custom Author <custom@example.com>")
  7819. self.assertTrue(new_commit.message.startswith(b"Custom: "))
  7820. def test_filter_branch_no_changes(self):
  7821. """Test filtering branch with no changes."""
  7822. result = porcelain.filter_branch(self.repo_path, "master")
  7823. # All commits should map to themselves
  7824. for old_sha, new_sha in result.items():
  7825. self.assertEqual(old_sha, new_sha)
  7826. # HEAD should be unchanged
  7827. self.assertEqual(self.repo.refs[b"refs/heads/master"], self.c3_id)
  7828. def test_filter_branch_force(self):
  7829. """Test force filtering a previously filtered branch."""
  7830. # First filter
  7831. porcelain.filter_branch(
  7832. self.repo_path, "master", filter_message=lambda m: b"First: " + m
  7833. )
  7834. # Try again without force - should fail
  7835. with self.assertRaises(porcelain.Error):
  7836. porcelain.filter_branch(
  7837. self.repo_path, "master", filter_message=lambda m: b"Second: " + m
  7838. )
  7839. # Try again with force - should succeed
  7840. porcelain.filter_branch(
  7841. self.repo_path,
  7842. "master",
  7843. filter_message=lambda m: b"Second: " + m,
  7844. force=True,
  7845. )
  7846. # Verify second filter was applied
  7847. new_head = self.repo.refs[b"refs/heads/master"]
  7848. new_commit = self.repo[new_head]
  7849. self.assertTrue(new_commit.message.startswith(b"Second: First: "))
  7850. class StashTests(PorcelainTestCase):
  7851. def setUp(self) -> None:
  7852. super().setUp()
  7853. # Create initial commit
  7854. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  7855. f.write(b"initial content")
  7856. porcelain.add(repo=self.repo.path, paths=["initial.txt"])
  7857. porcelain.commit(
  7858. repo=self.repo.path,
  7859. message=b"Initial commit",
  7860. author=b"Test Author <test@example.com>",
  7861. committer=b"Test Committer <test@example.com>",
  7862. )
  7863. def test_stash_push_and_pop(self) -> None:
  7864. # Create a new file and stage it
  7865. new_file = os.path.join(self.repo.path, "new.txt")
  7866. with open(new_file, "wb") as f:
  7867. f.write(b"new file content")
  7868. porcelain.add(repo=self.repo.path, paths=["new.txt"])
  7869. # Modify existing file
  7870. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  7871. f.write(b"modified content")
  7872. # Push to stash
  7873. porcelain.stash_push(self.repo.path)
  7874. # Verify files are reset
  7875. self.assertFalse(os.path.exists(new_file))
  7876. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  7877. self.assertEqual(b"initial content", f.read())
  7878. # Pop the stash
  7879. porcelain.stash_pop(self.repo.path)
  7880. # Verify files are restored
  7881. self.assertTrue(os.path.exists(new_file))
  7882. with open(new_file, "rb") as f:
  7883. self.assertEqual(b"new file content", f.read())
  7884. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  7885. self.assertEqual(b"modified content", f.read())
  7886. # Verify new file is in the index
  7887. from dulwich.index import Index
  7888. index = Index(os.path.join(self.repo.path, ".git", "index"))
  7889. self.assertIn(b"new.txt", index)
  7890. def test_stash_list(self) -> None:
  7891. # Initially no stashes
  7892. stashes = list(porcelain.stash_list(self.repo.path))
  7893. self.assertEqual(0, len(stashes))
  7894. # Create a file and stash it
  7895. test_file = os.path.join(self.repo.path, "test.txt")
  7896. with open(test_file, "wb") as f:
  7897. f.write(b"test content")
  7898. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  7899. # Push first stash
  7900. porcelain.stash_push(self.repo.path)
  7901. # Create another file and stash it
  7902. test_file2 = os.path.join(self.repo.path, "test2.txt")
  7903. with open(test_file2, "wb") as f:
  7904. f.write(b"test content 2")
  7905. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  7906. # Push second stash
  7907. porcelain.stash_push(self.repo.path)
  7908. # Check stash list
  7909. stashes = list(porcelain.stash_list(self.repo.path))
  7910. self.assertEqual(2, len(stashes))
  7911. # Stashes are returned in order (most recent first)
  7912. self.assertEqual(0, stashes[0][0])
  7913. self.assertEqual(1, stashes[1][0])
  7914. def test_stash_drop(self) -> None:
  7915. # Create and stash some changes
  7916. test_file = os.path.join(self.repo.path, "test.txt")
  7917. with open(test_file, "wb") as f:
  7918. f.write(b"test content")
  7919. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  7920. porcelain.stash_push(self.repo.path)
  7921. # Create another stash
  7922. test_file2 = os.path.join(self.repo.path, "test2.txt")
  7923. with open(test_file2, "wb") as f:
  7924. f.write(b"test content 2")
  7925. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  7926. porcelain.stash_push(self.repo.path)
  7927. # Verify we have 2 stashes
  7928. stashes = list(porcelain.stash_list(self.repo.path))
  7929. self.assertEqual(2, len(stashes))
  7930. # Drop the first stash (index 0)
  7931. porcelain.stash_drop(self.repo.path, 0)
  7932. # Verify we have 1 stash left
  7933. stashes = list(porcelain.stash_list(self.repo.path))
  7934. self.assertEqual(1, len(stashes))
  7935. # The remaining stash should be the one we created first
  7936. # Pop it and verify it's the first file
  7937. porcelain.stash_pop(self.repo.path)
  7938. self.assertTrue(os.path.exists(test_file))
  7939. self.assertFalse(os.path.exists(test_file2))
  7940. def test_stash_pop_empty(self) -> None:
  7941. # Attempting to pop from empty stash should raise an error
  7942. with self.assertRaises(IndexError):
  7943. porcelain.stash_pop(self.repo.path)
  7944. def test_stash_with_untracked_files(self) -> None:
  7945. # Create an untracked file
  7946. untracked_file = os.path.join(self.repo.path, "untracked.txt")
  7947. with open(untracked_file, "wb") as f:
  7948. f.write(b"untracked content")
  7949. # Create a tracked change
  7950. tracked_file = os.path.join(self.repo.path, "tracked.txt")
  7951. with open(tracked_file, "wb") as f:
  7952. f.write(b"tracked content")
  7953. porcelain.add(repo=self.repo.path, paths=["tracked.txt"])
  7954. # Stash (by default, untracked files are not included)
  7955. porcelain.stash_push(self.repo.path)
  7956. # Untracked file should still exist
  7957. self.assertTrue(os.path.exists(untracked_file))
  7958. # Tracked file should be gone
  7959. self.assertFalse(os.path.exists(tracked_file))
  7960. # Pop the stash
  7961. porcelain.stash_pop(self.repo.path)
  7962. # Tracked file should be restored
  7963. self.assertTrue(os.path.exists(tracked_file))
  7964. class BisectTests(PorcelainTestCase):
  7965. """Tests for bisect porcelain functions."""
  7966. def test_bisect_start(self):
  7967. """Test starting a bisect session."""
  7968. # Create some commits
  7969. _c1, _c2, c3 = build_commit_graph(
  7970. self.repo.object_store,
  7971. [[1], [2, 1], [3, 2]],
  7972. attrs={
  7973. 1: {"message": b"initial"},
  7974. 2: {"message": b"second"},
  7975. 3: {"message": b"third"},
  7976. },
  7977. )
  7978. self.repo.refs[b"refs/heads/master"] = c3.id
  7979. self.repo.refs[b"HEAD"] = c3.id
  7980. # Start bisect
  7981. porcelain.bisect_start(self.repo_path)
  7982. # Check that bisect state files exist
  7983. self.assertTrue(
  7984. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  7985. )
  7986. self.assertTrue(
  7987. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_TERMS"))
  7988. )
  7989. self.assertTrue(
  7990. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_NAMES"))
  7991. )
  7992. self.assertTrue(
  7993. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_LOG"))
  7994. )
  7995. def test_bisect_workflow(self):
  7996. """Test a complete bisect workflow."""
  7997. # Create some commits
  7998. c1, c2, c3, c4 = build_commit_graph(
  7999. self.repo.object_store,
  8000. [[1], [2, 1], [3, 2], [4, 3]],
  8001. attrs={
  8002. 1: {"message": b"good commit 1"},
  8003. 2: {"message": b"good commit 2"},
  8004. 3: {"message": b"bad commit"},
  8005. 4: {"message": b"bad commit 2"},
  8006. },
  8007. )
  8008. self.repo.refs[b"refs/heads/master"] = c4.id
  8009. self.repo.refs[b"HEAD"] = c4.id
  8010. # Start bisect with bad and good
  8011. next_sha = porcelain.bisect_start(self.repo_path, bad=c4.id, good=c1.id)
  8012. # Should return the middle commit
  8013. self.assertIsNotNone(next_sha)
  8014. self.assertIn(next_sha, [c2.id, c3.id])
  8015. # Mark the middle commit as good or bad
  8016. if next_sha == c2.id:
  8017. # c2 is good, next should be c3
  8018. next_sha = porcelain.bisect_good(self.repo_path)
  8019. self.assertEqual(next_sha, c3.id)
  8020. # Mark c3 as bad - bisect complete
  8021. next_sha = porcelain.bisect_bad(self.repo_path)
  8022. self.assertIsNone(next_sha)
  8023. else:
  8024. # c3 is bad, next should be c2
  8025. next_sha = porcelain.bisect_bad(self.repo_path)
  8026. self.assertEqual(next_sha, c2.id)
  8027. # Mark c2 as good - bisect complete
  8028. next_sha = porcelain.bisect_good(self.repo_path)
  8029. self.assertIsNone(next_sha)
  8030. def test_bisect_log(self):
  8031. """Test getting bisect log."""
  8032. # Create some commits
  8033. c1, _c2, c3 = build_commit_graph(
  8034. self.repo.object_store,
  8035. [[1], [2, 1], [3, 2]],
  8036. attrs={
  8037. 1: {"message": b"initial"},
  8038. 2: {"message": b"second"},
  8039. 3: {"message": b"third"},
  8040. },
  8041. )
  8042. self.repo.refs[b"refs/heads/master"] = c3.id
  8043. self.repo.refs[b"HEAD"] = c3.id
  8044. # Start bisect and mark commits
  8045. porcelain.bisect_start(self.repo_path)
  8046. porcelain.bisect_bad(self.repo_path, c3.id)
  8047. porcelain.bisect_good(self.repo_path, c1.id)
  8048. # Get log
  8049. log = porcelain.bisect_log(self.repo_path)
  8050. self.assertIn("git bisect start", log)
  8051. self.assertIn("git bisect bad", log)
  8052. self.assertIn("git bisect good", log)
  8053. def test_bisect_reset(self):
  8054. """Test resetting bisect state."""
  8055. # Create some commits
  8056. c1, _c2, c3 = build_commit_graph(
  8057. self.repo.object_store,
  8058. [[1], [2, 1], [3, 2]],
  8059. attrs={
  8060. 1: {"message": b"initial"},
  8061. 2: {"message": b"second"},
  8062. 3: {"message": b"third"},
  8063. },
  8064. )
  8065. self.repo.refs[b"refs/heads/master"] = c3.id
  8066. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  8067. # Start bisect
  8068. porcelain.bisect_start(self.repo_path)
  8069. porcelain.bisect_bad(self.repo_path)
  8070. porcelain.bisect_good(self.repo_path, c1.id)
  8071. # Reset
  8072. porcelain.bisect_reset(self.repo_path)
  8073. # Check that bisect state files are removed
  8074. self.assertFalse(
  8075. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  8076. )
  8077. self.assertFalse(
  8078. os.path.exists(os.path.join(self.repo.controldir(), "refs", "bisect"))
  8079. )
  8080. # HEAD should be back to being a symbolic ref to master
  8081. head_target, _ = self.repo.refs.follow(b"HEAD")
  8082. self.assertEqual(head_target[-1], b"refs/heads/master")
  8083. def test_bisect_skip(self):
  8084. """Test skipping commits during bisect."""
  8085. # Create some commits
  8086. c1, c2, _c3, _c4, c5 = build_commit_graph(
  8087. self.repo.object_store,
  8088. [[1], [2, 1], [3, 2], [4, 3], [5, 4]],
  8089. attrs={
  8090. 1: {"message": b"good"},
  8091. 2: {"message": b"skip this"},
  8092. 3: {"message": b"bad"},
  8093. 4: {"message": b"bad"},
  8094. 5: {"message": b"bad"},
  8095. },
  8096. )
  8097. self.repo.refs[b"refs/heads/master"] = c5.id
  8098. self.repo.refs[b"HEAD"] = c5.id
  8099. # Start bisect
  8100. porcelain.bisect_start(self.repo_path, bad=c5.id, good=c1.id)
  8101. # Skip c2 if it's selected
  8102. next_sha = porcelain.bisect_skip(self.repo_path, [c2.id])
  8103. self.assertIsNotNone(next_sha)
  8104. class ReflogTest(PorcelainTestCase):
  8105. def test_reflog_head(self):
  8106. """Test reading HEAD reflog."""
  8107. # Create a commit
  8108. blob = Blob.from_string(b"test content")
  8109. self.repo.object_store.add_object(blob)
  8110. tree = Tree()
  8111. tree.add(b"test", 0o100644, blob.id)
  8112. self.repo.object_store.add_object(tree)
  8113. commit = Commit()
  8114. commit.tree = tree.id
  8115. commit.author = b"Test Author <test@example.com>"
  8116. commit.committer = b"Test Author <test@example.com>"
  8117. commit.commit_time = 1234567890
  8118. commit.commit_timezone = 0
  8119. commit.author_time = 1234567890
  8120. commit.author_timezone = 0
  8121. commit.message = b"Initial commit"
  8122. self.repo.object_store.add_object(commit)
  8123. # Write a reflog entry
  8124. self.repo._write_reflog(
  8125. b"HEAD",
  8126. ZERO_SHA,
  8127. commit.id,
  8128. b"Test Author <test@example.com>",
  8129. 1234567890,
  8130. 0,
  8131. b"commit (initial): Initial commit",
  8132. )
  8133. # Read reflog using porcelain
  8134. entries = list(porcelain.reflog(self.repo_path))
  8135. self.assertEqual(1, len(entries))
  8136. self.assertEqual(ZERO_SHA, entries[0].old_sha)
  8137. self.assertEqual(commit.id, entries[0].new_sha)
  8138. self.assertEqual(b"Test Author <test@example.com>", entries[0].committer)
  8139. self.assertEqual(1234567890, entries[0].timestamp)
  8140. self.assertEqual(0, entries[0].timezone)
  8141. self.assertEqual(b"commit (initial): Initial commit", entries[0].message)
  8142. def test_reflog_with_string_ref(self):
  8143. """Test reading reflog with string reference."""
  8144. # Create a commit
  8145. blob = Blob.from_string(b"test content")
  8146. self.repo.object_store.add_object(blob)
  8147. tree = Tree()
  8148. tree.add(b"test", 0o100644, blob.id)
  8149. self.repo.object_store.add_object(tree)
  8150. commit = Commit()
  8151. commit.tree = tree.id
  8152. commit.author = b"Test Author <test@example.com>"
  8153. commit.committer = b"Test Author <test@example.com>"
  8154. commit.commit_time = 1234567890
  8155. commit.commit_timezone = 0
  8156. commit.author_time = 1234567890
  8157. commit.author_timezone = 0
  8158. commit.message = b"Initial commit"
  8159. self.repo.object_store.add_object(commit)
  8160. # Write a reflog entry
  8161. self.repo._write_reflog(
  8162. b"refs/heads/master",
  8163. ZERO_SHA,
  8164. commit.id,
  8165. b"Test Author <test@example.com>",
  8166. 1234567890,
  8167. 0,
  8168. b"commit (initial): Initial commit",
  8169. )
  8170. # Read reflog using porcelain with string ref
  8171. entries = list(porcelain.reflog(self.repo_path, "refs/heads/master"))
  8172. self.assertEqual(1, len(entries))
  8173. self.assertEqual(commit.id, entries[0].new_sha)
  8174. def test_reflog_all(self):
  8175. """Test reading all reflogs."""
  8176. # Create a commit
  8177. blob = Blob.from_string(b"test content")
  8178. self.repo.object_store.add_object(blob)
  8179. tree = Tree()
  8180. tree.add(b"test", 0o100644, blob.id)
  8181. self.repo.object_store.add_object(tree)
  8182. commit = Commit()
  8183. commit.tree = tree.id
  8184. commit.author = b"Test Author <test@example.com>"
  8185. commit.committer = b"Test Author <test@example.com>"
  8186. commit.commit_time = 1234567890
  8187. commit.commit_timezone = 0
  8188. commit.author_time = 1234567890
  8189. commit.author_timezone = 0
  8190. commit.message = b"Initial commit"
  8191. self.repo.object_store.add_object(commit)
  8192. # Write reflog entries for HEAD and master
  8193. self.repo._write_reflog(
  8194. b"HEAD",
  8195. ZERO_SHA,
  8196. commit.id,
  8197. b"Test Author <test@example.com>",
  8198. 1234567890,
  8199. 0,
  8200. b"commit (initial): Initial commit",
  8201. )
  8202. self.repo._write_reflog(
  8203. b"refs/heads/master",
  8204. ZERO_SHA,
  8205. commit.id,
  8206. b"Test Author <test@example.com>",
  8207. 1234567891,
  8208. 0,
  8209. b"branch: Created from HEAD",
  8210. )
  8211. # Read all reflogs using porcelain
  8212. entries = list(porcelain.reflog(self.repo_path, all=True))
  8213. # Should have at least 2 entries (HEAD and refs/heads/master)
  8214. self.assertGreaterEqual(len(entries), 2)
  8215. # Check that we got entries from different refs
  8216. refs_seen = set()
  8217. for ref, entry in entries:
  8218. refs_seen.add(ref)
  8219. self.assertEqual(commit.id, entry.new_sha)
  8220. # Should have seen at least HEAD and refs/heads/master
  8221. self.assertIn(b"HEAD", refs_seen)
  8222. self.assertIn(b"refs/heads/master", refs_seen)
  8223. def test_reflog_expire_by_time(self):
  8224. """Test expiring reflog entries by timestamp."""
  8225. # Create commits
  8226. blob = Blob.from_string(b"test content")
  8227. self.repo.object_store.add_object(blob)
  8228. tree = Tree()
  8229. tree.add(b"test", 0o100644, blob.id)
  8230. self.repo.object_store.add_object(tree)
  8231. commit1 = Commit()
  8232. commit1.tree = tree.id
  8233. commit1.author = b"Test Author <test@example.com>"
  8234. commit1.committer = b"Test Author <test@example.com>"
  8235. commit1.commit_time = 1000000000
  8236. commit1.commit_timezone = 0
  8237. commit1.author_time = 1000000000
  8238. commit1.author_timezone = 0
  8239. commit1.message = b"Old commit"
  8240. self.repo.object_store.add_object(commit1)
  8241. commit2 = Commit()
  8242. commit2.tree = tree.id
  8243. commit2.author = b"Test Author <test@example.com>"
  8244. commit2.committer = b"Test Author <test@example.com>"
  8245. commit2.commit_time = 2000000000
  8246. commit2.commit_timezone = 0
  8247. commit2.author_time = 2000000000
  8248. commit2.author_timezone = 0
  8249. commit2.message = b"Recent commit"
  8250. self.repo.object_store.add_object(commit2)
  8251. # Write reflog entries with different timestamps
  8252. self.repo._write_reflog(
  8253. b"HEAD",
  8254. ZERO_SHA,
  8255. commit1.id,
  8256. b"Test Author <test@example.com>",
  8257. 1000000000,
  8258. 0,
  8259. b"commit: Old commit",
  8260. )
  8261. self.repo._write_reflog(
  8262. b"HEAD",
  8263. commit1.id,
  8264. commit2.id,
  8265. b"Test Author <test@example.com>",
  8266. 2000000000,
  8267. 0,
  8268. b"commit: Recent commit",
  8269. )
  8270. # Expire entries older than timestamp 1500000000
  8271. result = porcelain.reflog_expire(
  8272. self.repo_path, ref=b"HEAD", expire_time=1500000000
  8273. )
  8274. self.assertEqual(1, result[b"HEAD"])
  8275. # Check that only the recent entry remains
  8276. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8277. self.assertEqual(1, len(entries))
  8278. self.assertEqual(commit2.id, entries[0].new_sha)
  8279. def test_reflog_expire_all(self):
  8280. """Test expiring reflog entries for all refs."""
  8281. # Create a commit
  8282. blob = Blob.from_string(b"test content")
  8283. self.repo.object_store.add_object(blob)
  8284. tree = Tree()
  8285. tree.add(b"test", 0o100644, blob.id)
  8286. self.repo.object_store.add_object(tree)
  8287. commit = Commit()
  8288. commit.tree = tree.id
  8289. commit.author = b"Test Author <test@example.com>"
  8290. commit.committer = b"Test Author <test@example.com>"
  8291. commit.commit_time = 1000000000
  8292. commit.commit_timezone = 0
  8293. commit.author_time = 1000000000
  8294. commit.author_timezone = 0
  8295. commit.message = b"Test commit"
  8296. self.repo.object_store.add_object(commit)
  8297. # Write old reflog entries for multiple refs
  8298. self.repo._write_reflog(
  8299. b"HEAD",
  8300. ZERO_SHA,
  8301. commit.id,
  8302. b"Test Author <test@example.com>",
  8303. 1000000000,
  8304. 0,
  8305. b"commit: Test commit",
  8306. )
  8307. self.repo._write_reflog(
  8308. b"refs/heads/master",
  8309. ZERO_SHA,
  8310. commit.id,
  8311. b"Test Author <test@example.com>",
  8312. 1000000000,
  8313. 0,
  8314. b"commit: Test commit",
  8315. )
  8316. # Expire all old entries
  8317. result = porcelain.reflog_expire(
  8318. self.repo_path, all=True, expire_time=2000000000
  8319. )
  8320. # Should have expired entries from both refs
  8321. self.assertIn(b"HEAD", result)
  8322. self.assertIn(b"refs/heads/master", result)
  8323. self.assertEqual(1, result[b"HEAD"])
  8324. self.assertEqual(1, result[b"refs/heads/master"])
  8325. def test_reflog_expire_dry_run(self):
  8326. """Test dry-run mode for reflog expire."""
  8327. # Create a commit
  8328. blob = Blob.from_string(b"test content")
  8329. self.repo.object_store.add_object(blob)
  8330. tree = Tree()
  8331. tree.add(b"test", 0o100644, blob.id)
  8332. self.repo.object_store.add_object(tree)
  8333. commit = Commit()
  8334. commit.tree = tree.id
  8335. commit.author = b"Test Author <test@example.com>"
  8336. commit.committer = b"Test Author <test@example.com>"
  8337. commit.commit_time = 1000000000
  8338. commit.commit_timezone = 0
  8339. commit.author_time = 1000000000
  8340. commit.author_timezone = 0
  8341. commit.message = b"Test commit"
  8342. self.repo.object_store.add_object(commit)
  8343. # Write old reflog entry
  8344. self.repo._write_reflog(
  8345. b"HEAD",
  8346. ZERO_SHA,
  8347. commit.id,
  8348. b"Test Author <test@example.com>",
  8349. 1000000000,
  8350. 0,
  8351. b"commit: Test commit",
  8352. )
  8353. # Dry run expire
  8354. result = porcelain.reflog_expire(
  8355. self.repo_path, ref=b"HEAD", expire_time=2000000000, dry_run=True
  8356. )
  8357. self.assertEqual(1, result[b"HEAD"])
  8358. # Entry should still exist
  8359. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8360. self.assertEqual(1, len(entries))
  8361. def test_reflog_delete(self):
  8362. """Test deleting specific reflog entry."""
  8363. # Create commits
  8364. blob = Blob.from_string(b"test content")
  8365. self.repo.object_store.add_object(blob)
  8366. tree = Tree()
  8367. tree.add(b"test", 0o100644, blob.id)
  8368. self.repo.object_store.add_object(tree)
  8369. commit1 = Commit()
  8370. commit1.tree = tree.id
  8371. commit1.author = b"Test Author <test@example.com>"
  8372. commit1.committer = b"Test Author <test@example.com>"
  8373. commit1.commit_time = 1000000000
  8374. commit1.commit_timezone = 0
  8375. commit1.author_time = 1000000000
  8376. commit1.author_timezone = 0
  8377. commit1.message = b"First commit"
  8378. self.repo.object_store.add_object(commit1)
  8379. commit2 = Commit()
  8380. commit2.tree = tree.id
  8381. commit2.author = b"Test Author <test@example.com>"
  8382. commit2.committer = b"Test Author <test@example.com>"
  8383. commit2.commit_time = 2000000000
  8384. commit2.commit_timezone = 0
  8385. commit2.author_time = 2000000000
  8386. commit2.author_timezone = 0
  8387. commit2.message = b"Second commit"
  8388. self.repo.object_store.add_object(commit2)
  8389. # Write two reflog entries
  8390. self.repo._write_reflog(
  8391. b"HEAD",
  8392. ZERO_SHA,
  8393. commit1.id,
  8394. b"Test Author <test@example.com>",
  8395. 1000000000,
  8396. 0,
  8397. b"commit: First commit",
  8398. )
  8399. self.repo._write_reflog(
  8400. b"HEAD",
  8401. commit1.id,
  8402. commit2.id,
  8403. b"Test Author <test@example.com>",
  8404. 2000000000,
  8405. 0,
  8406. b"commit: Second commit",
  8407. )
  8408. # Delete the most recent entry (index 0)
  8409. porcelain.reflog_delete(self.repo_path, ref=b"HEAD", index=0)
  8410. # Should only have one entry left
  8411. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8412. self.assertEqual(1, len(entries))
  8413. self.assertEqual(commit1.id, entries[0].new_sha)
  8414. def test_reflog_expire_unreachable(self):
  8415. """Test expiring unreachable reflog entries."""
  8416. # Create commits
  8417. blob = Blob.from_string(b"test content")
  8418. self.repo.object_store.add_object(blob)
  8419. tree = Tree()
  8420. tree.add(b"test", 0o100644, blob.id)
  8421. self.repo.object_store.add_object(tree)
  8422. # Create commit 1 - will be reachable (pointed to by HEAD)
  8423. commit1 = Commit()
  8424. commit1.tree = tree.id
  8425. commit1.author = b"Test Author <test@example.com>"
  8426. commit1.committer = b"Test Author <test@example.com>"
  8427. commit1.commit_time = 1000000000
  8428. commit1.commit_timezone = 0
  8429. commit1.author_time = 1000000000
  8430. commit1.author_timezone = 0
  8431. commit1.message = b"Reachable commit"
  8432. self.repo.object_store.add_object(commit1)
  8433. # Create commit 2 - will be unreachable
  8434. commit2 = Commit()
  8435. commit2.tree = tree.id
  8436. commit2.author = b"Test Author <test@example.com>"
  8437. commit2.committer = b"Test Author <test@example.com>"
  8438. commit2.commit_time = 1500000000
  8439. commit2.commit_timezone = 0
  8440. commit2.author_time = 1500000000
  8441. commit2.author_timezone = 0
  8442. commit2.message = b"Unreachable commit"
  8443. self.repo.object_store.add_object(commit2)
  8444. # Create commit 3 - will also be reachable (pointed to by master)
  8445. commit3 = Commit()
  8446. commit3.tree = tree.id
  8447. commit3.author = b"Test Author <test@example.com>"
  8448. commit3.committer = b"Test Author <test@example.com>"
  8449. commit3.commit_time = 2000000000
  8450. commit3.commit_timezone = 0
  8451. commit3.author_time = 2000000000
  8452. commit3.author_timezone = 0
  8453. commit3.message = b"Another reachable commit"
  8454. self.repo.object_store.add_object(commit3)
  8455. # Set up refs to make commit1 and commit3 reachable
  8456. # HEAD is a symbolic ref to refs/heads/master by default, so we set master first
  8457. self.repo.refs[b"refs/heads/master"] = commit1.id
  8458. # Create another branch pointing to commit3
  8459. self.repo.refs[b"refs/heads/feature"] = commit3.id
  8460. # Write reflog entries for all three commits
  8461. self.repo._write_reflog(
  8462. b"HEAD",
  8463. ZERO_SHA,
  8464. commit1.id,
  8465. b"Test Author <test@example.com>",
  8466. 1000000000,
  8467. 0,
  8468. b"commit: Reachable commit",
  8469. )
  8470. self.repo._write_reflog(
  8471. b"HEAD",
  8472. commit1.id,
  8473. commit2.id,
  8474. b"Test Author <test@example.com>",
  8475. 1500000000,
  8476. 0,
  8477. b"commit: Unreachable commit",
  8478. )
  8479. self.repo._write_reflog(
  8480. b"HEAD",
  8481. commit2.id,
  8482. commit3.id,
  8483. b"Test Author <test@example.com>",
  8484. 2000000000,
  8485. 0,
  8486. b"commit: Another reachable commit",
  8487. )
  8488. # Expire unreachable entries older than a time that includes commit2
  8489. # but not the reachable commits
  8490. result = porcelain.reflog_expire(
  8491. self.repo_path,
  8492. ref=b"HEAD",
  8493. expire_unreachable_time=1600000000, # After commit2, before commit3
  8494. )
  8495. # Should have expired only commit2
  8496. self.assertEqual(1, result[b"HEAD"])
  8497. # Verify the remaining entries
  8498. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8499. self.assertEqual(2, len(entries))
  8500. # commit1 and commit3 should remain (both reachable)
  8501. self.assertEqual(commit1.id, entries[0].new_sha)
  8502. self.assertEqual(commit3.id, entries[1].new_sha)
  8503. class WriteCommitGraphTests(PorcelainTestCase):
  8504. """Tests for the write_commit_graph porcelain function."""
  8505. def test_write_commit_graph_empty_repo(self):
  8506. """Test writing commit graph on empty repository."""
  8507. # Should not fail on empty repo
  8508. porcelain.write_commit_graph(self.repo_path)
  8509. # No commit graph should be created for empty repo
  8510. graph_path = os.path.join(
  8511. self.repo_path, ".git", "objects", "info", "commit-graph"
  8512. )
  8513. self.assertFalse(os.path.exists(graph_path))
  8514. def test_write_commit_graph_with_commits(self):
  8515. """Test writing commit graph with commits."""
  8516. # Create some commits
  8517. c1, c2, c3 = build_commit_graph(
  8518. self.repo.object_store,
  8519. [[1], [2, 1], [3, 1, 2]],
  8520. attrs={
  8521. 1: {"message": b"First commit"},
  8522. 2: {"message": b"Second commit"},
  8523. 3: {"message": b"Merge commit"},
  8524. },
  8525. )
  8526. self.repo.refs[b"refs/heads/master"] = c3.id
  8527. self.repo.refs[b"refs/heads/branch"] = c2.id
  8528. # Write commit graph
  8529. porcelain.write_commit_graph(self.repo_path)
  8530. # Verify commit graph was created
  8531. graph_path = os.path.join(
  8532. self.repo_path, ".git", "objects", "info", "commit-graph"
  8533. )
  8534. self.assertTrue(os.path.exists(graph_path))
  8535. # Load and verify the commit graph
  8536. from dulwich.commit_graph import read_commit_graph
  8537. commit_graph = read_commit_graph(graph_path)
  8538. self.assertIsNotNone(commit_graph)
  8539. self.assertEqual(3, len(commit_graph))
  8540. # Verify all commits are in the graph
  8541. for commit_obj in [c1, c2, c3]:
  8542. entry = commit_graph.get_entry_by_oid(commit_obj.id)
  8543. self.assertIsNotNone(entry)
  8544. def test_write_commit_graph_config_disabled(self):
  8545. """Test that commit graph is not written when disabled by config."""
  8546. # Create a commit
  8547. (c1,) = build_commit_graph(
  8548. self.repo.object_store, [[1]], attrs={1: {"message": b"First commit"}}
  8549. )
  8550. self.repo.refs[b"refs/heads/master"] = c1.id
  8551. # Disable commit graph in config
  8552. config = self.repo.get_config()
  8553. config.set((b"core",), b"commitGraph", b"false")
  8554. config.write_to_path()
  8555. # Write commit graph (should respect config)
  8556. porcelain.write_commit_graph(self.repo_path)
  8557. # Verify commit graph still gets written
  8558. # (porcelain.write_commit_graph explicitly writes regardless of config)
  8559. graph_path = os.path.join(
  8560. self.repo_path, ".git", "objects", "info", "commit-graph"
  8561. )
  8562. self.assertTrue(os.path.exists(graph_path))
  8563. def test_write_commit_graph_reachable_false(self):
  8564. """Test writing commit graph with reachable=False."""
  8565. # Create commits
  8566. _c1, _c2, c3 = build_commit_graph(
  8567. self.repo.object_store,
  8568. [[1], [2, 1], [3, 2]],
  8569. attrs={
  8570. 1: {"message": b"First commit"},
  8571. 2: {"message": b"Second commit"},
  8572. 3: {"message": b"Third commit"},
  8573. },
  8574. )
  8575. # Only reference the third commit
  8576. self.repo.refs[b"refs/heads/master"] = c3.id
  8577. # Write commit graph with reachable=False
  8578. porcelain.write_commit_graph(self.repo_path, reachable=False)
  8579. # Verify commit graph was created
  8580. graph_path = os.path.join(
  8581. self.repo_path, ".git", "objects", "info", "commit-graph"
  8582. )
  8583. self.assertTrue(os.path.exists(graph_path))
  8584. # Load and verify the commit graph
  8585. from dulwich.commit_graph import read_commit_graph
  8586. commit_graph = read_commit_graph(graph_path)
  8587. self.assertIsNotNone(commit_graph)
  8588. # With reachable=False, only directly referenced commits should be included
  8589. # In this case, only c3 (from refs/heads/master)
  8590. self.assertEqual(1, len(commit_graph))
  8591. entry = commit_graph.get_entry_by_oid(c3.id)
  8592. self.assertIsNotNone(entry)
  8593. class WorktreePorcelainTests(PorcelainTestCase):
  8594. """Tests for porcelain worktree functions."""
  8595. def test_worktree_list_single(self):
  8596. """Test listing worktrees when only main worktree exists."""
  8597. # Create initial commit
  8598. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8599. f.write("test content")
  8600. porcelain.add(self.repo_path, ["test.txt"])
  8601. porcelain.commit(self.repo_path, message=b"Initial commit")
  8602. # List worktrees
  8603. worktrees = porcelain.worktree_list(self.repo_path)
  8604. self.assertEqual(len(worktrees), 1)
  8605. self.assertEqual(worktrees[0].path, self.repo_path)
  8606. self.assertFalse(worktrees[0].bare)
  8607. self.assertIsNotNone(worktrees[0].head)
  8608. self.assertIsNotNone(worktrees[0].branch)
  8609. def test_worktree_add_branch(self):
  8610. """Test adding a worktree with a new branch."""
  8611. # Create initial commit
  8612. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8613. f.write("test content")
  8614. porcelain.add(self.repo_path, ["test.txt"])
  8615. porcelain.commit(self.repo_path, message=b"Initial commit")
  8616. # Add worktree
  8617. wt_path = os.path.join(self.test_dir, "worktree1")
  8618. result_path = porcelain.worktree_add(self.repo_path, wt_path, branch=b"feature")
  8619. self.assertEqual(result_path, wt_path)
  8620. self.assertTrue(os.path.exists(wt_path))
  8621. self.assertTrue(os.path.exists(os.path.join(wt_path, ".git")))
  8622. # Check it appears in the list
  8623. worktrees = porcelain.worktree_list(self.repo_path)
  8624. self.assertEqual(len(worktrees), 2)
  8625. # Find the new worktree
  8626. new_wt = None
  8627. for wt in worktrees:
  8628. if wt.path == wt_path:
  8629. new_wt = wt
  8630. break
  8631. self.assertIsNotNone(new_wt)
  8632. self.assertEqual(new_wt.branch, b"refs/heads/feature")
  8633. self.assertFalse(new_wt.detached)
  8634. def test_worktree_add_detached(self):
  8635. """Test adding a detached worktree."""
  8636. # Create initial commit
  8637. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8638. f.write("test content")
  8639. porcelain.add(self.repo_path, ["test.txt"])
  8640. sha = porcelain.commit(self.repo_path, message=b"Initial commit")
  8641. # Add detached worktree
  8642. wt_path = os.path.join(self.test_dir, "detached")
  8643. porcelain.worktree_add(self.repo_path, wt_path, commit=sha, detach=True)
  8644. # Check it's detached
  8645. worktrees = porcelain.worktree_list(self.repo_path)
  8646. for wt in worktrees:
  8647. if wt.path == wt_path:
  8648. self.assertTrue(wt.detached)
  8649. self.assertIsNone(wt.branch)
  8650. self.assertEqual(wt.head, sha)
  8651. def test_worktree_remove(self):
  8652. """Test removing a worktree."""
  8653. # Create initial commit
  8654. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8655. f.write("test content")
  8656. porcelain.add(self.repo_path, ["test.txt"])
  8657. porcelain.commit(self.repo_path, message=b"Initial commit")
  8658. # Add and remove worktree
  8659. wt_path = os.path.join(self.test_dir, "to-remove")
  8660. porcelain.worktree_add(self.repo_path, wt_path)
  8661. # Verify it exists
  8662. self.assertTrue(os.path.exists(wt_path))
  8663. self.assertEqual(len(porcelain.worktree_list(self.repo_path)), 2)
  8664. # Remove it
  8665. porcelain.worktree_remove(self.repo_path, wt_path)
  8666. # Verify it's gone
  8667. self.assertFalse(os.path.exists(wt_path))
  8668. self.assertEqual(len(porcelain.worktree_list(self.repo_path)), 1)
  8669. def test_worktree_prune(self):
  8670. """Test pruning worktrees."""
  8671. # Create initial commit
  8672. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8673. f.write("test content")
  8674. porcelain.add(self.repo_path, ["test.txt"])
  8675. porcelain.commit(self.repo_path, message=b"Initial commit")
  8676. # Add worktree
  8677. wt_path = os.path.join(self.test_dir, "to-prune")
  8678. porcelain.worktree_add(self.repo_path, wt_path)
  8679. # Manually remove directory
  8680. shutil.rmtree(wt_path)
  8681. # Prune should remove the administrative files
  8682. pruned = porcelain.worktree_prune(self.repo_path)
  8683. self.assertEqual(len(pruned), 1)
  8684. # Verify it's gone from the list
  8685. worktrees = porcelain.worktree_list(self.repo_path)
  8686. self.assertEqual(len(worktrees), 1)
  8687. def test_worktree_lock_unlock(self):
  8688. """Test locking and unlocking worktrees."""
  8689. # Create initial commit
  8690. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8691. f.write("test content")
  8692. porcelain.add(self.repo_path, ["test.txt"])
  8693. porcelain.commit(self.repo_path, message=b"Initial commit")
  8694. # Add worktree
  8695. wt_path = os.path.join(self.test_dir, "lockable")
  8696. porcelain.worktree_add(self.repo_path, wt_path)
  8697. # Lock it
  8698. porcelain.worktree_lock(self.repo_path, wt_path, reason="Testing")
  8699. # Verify it's locked
  8700. worktrees = porcelain.worktree_list(self.repo_path)
  8701. for wt in worktrees:
  8702. if wt.path == wt_path:
  8703. self.assertTrue(wt.locked)
  8704. # Unlock it
  8705. porcelain.worktree_unlock(self.repo_path, wt_path)
  8706. # Verify it's unlocked
  8707. worktrees = porcelain.worktree_list(self.repo_path)
  8708. for wt in worktrees:
  8709. if wt.path == wt_path:
  8710. self.assertFalse(wt.locked)
  8711. def test_worktree_move(self):
  8712. """Test moving a worktree."""
  8713. # Create initial commit
  8714. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8715. f.write("test content")
  8716. porcelain.add(self.repo_path, ["test.txt"])
  8717. porcelain.commit(self.repo_path, message=b"Initial commit")
  8718. # Add worktree
  8719. old_path = os.path.join(self.test_dir, "old-location")
  8720. porcelain.worktree_add(self.repo_path, old_path)
  8721. # Create a file in the worktree
  8722. test_file = os.path.join(old_path, "workspace.txt")
  8723. with open(test_file, "w") as f:
  8724. f.write("workspace content")
  8725. # Move it
  8726. new_path = os.path.join(self.test_dir, "new-location")
  8727. porcelain.worktree_move(self.repo_path, old_path, new_path)
  8728. # Verify old path doesn't exist, new path does
  8729. self.assertFalse(os.path.exists(old_path))
  8730. self.assertTrue(os.path.exists(new_path))
  8731. self.assertTrue(os.path.exists(os.path.join(new_path, "workspace.txt")))
  8732. # Verify it's in the list at new location
  8733. worktrees = porcelain.worktree_list(self.repo_path)
  8734. paths = [wt.path for wt in worktrees]
  8735. self.assertIn(new_path, paths)
  8736. self.assertNotIn(old_path, paths)
  8737. class VarTests(PorcelainTestCase):
  8738. """Tests for the var command."""
  8739. def test_var_author_ident(self):
  8740. """Test getting GIT_AUTHOR_IDENT."""
  8741. # Set up user config
  8742. config = self.repo.get_config()
  8743. config.set((b"user",), b"name", b"Test Author")
  8744. config.set((b"user",), b"email", b"author@example.com")
  8745. config.write_to_path()
  8746. result = porcelain.var(self.repo_path, variable="GIT_AUTHOR_IDENT")
  8747. self.assertIn("Test Author <author@example.com>", result)
  8748. # Check that timestamp and timezone are included
  8749. # Format: Name <email> timestamp timezone
  8750. # "Test Author" is 2 words, so we have: Test, Author, <email>, timestamp, timezone
  8751. parts = result.split()
  8752. self.assertGreaterEqual(
  8753. len(parts), 4
  8754. ) # At least name, <email>, timestamp, timezone
  8755. # Check last two parts are timestamp and timezone
  8756. self.assertTrue(parts[-2].isdigit()) # timestamp
  8757. self.assertRegex(parts[-1], r"[+-]\d{4}") # timezone
  8758. def test_var_committer_ident(self):
  8759. """Test getting GIT_COMMITTER_IDENT."""
  8760. # Set up user config
  8761. config = self.repo.get_config()
  8762. config.set((b"user",), b"name", b"Test Committer")
  8763. config.set((b"user",), b"email", b"committer@example.com")
  8764. config.write_to_path()
  8765. result = porcelain.var(self.repo_path, variable="GIT_COMMITTER_IDENT")
  8766. self.assertIn("Test Committer <committer@example.com>", result)
  8767. # Check that timestamp and timezone are included
  8768. parts = result.split()
  8769. self.assertGreaterEqual(
  8770. len(parts), 4
  8771. ) # At least name, <email>, timestamp, timezone
  8772. # Check last two parts are timestamp and timezone
  8773. self.assertTrue(parts[-2].isdigit()) # timestamp
  8774. self.assertRegex(parts[-1], r"[+-]\d{4}") # timezone
  8775. def test_var_editor(self):
  8776. """Test getting GIT_EDITOR."""
  8777. # Test with environment variable
  8778. self.overrideEnv("GIT_EDITOR", "vim")
  8779. result = porcelain.var(self.repo_path, variable="GIT_EDITOR")
  8780. self.assertEqual(result, "vim")
  8781. def test_var_editor_from_config(self):
  8782. """Test getting GIT_EDITOR from config."""
  8783. # Set up editor in config
  8784. config = self.repo.get_config()
  8785. config.set((b"core",), b"editor", b"emacs")
  8786. config.write_to_path()
  8787. # Make sure env var is not set
  8788. self.overrideEnv("GIT_EDITOR", None)
  8789. result = porcelain.var(self.repo_path, variable="GIT_EDITOR")
  8790. self.assertEqual(result, "emacs")
  8791. def test_var_pager(self):
  8792. """Test getting GIT_PAGER."""
  8793. # Test with environment variable
  8794. self.overrideEnv("GIT_PAGER", "less")
  8795. result = porcelain.var(self.repo_path, variable="GIT_PAGER")
  8796. self.assertEqual(result, "less")
  8797. def test_var_pager_from_config(self):
  8798. """Test getting GIT_PAGER from config."""
  8799. # Set up pager in config
  8800. config = self.repo.get_config()
  8801. config.set((b"core",), b"pager", b"more")
  8802. config.write_to_path()
  8803. # Make sure env var is not set
  8804. self.overrideEnv("GIT_PAGER", None)
  8805. result = porcelain.var(self.repo_path, variable="GIT_PAGER")
  8806. self.assertEqual(result, "more")
  8807. def test_var_default_branch(self):
  8808. """Test getting GIT_DEFAULT_BRANCH."""
  8809. # Set up default branch in config
  8810. config = self.repo.get_config()
  8811. config.set((b"init",), b"defaultBranch", b"main")
  8812. config.write_to_path()
  8813. result = porcelain.var(self.repo_path, variable="GIT_DEFAULT_BRANCH")
  8814. self.assertEqual(result, "main")
  8815. def test_var_default_branch_default(self):
  8816. """Test getting GIT_DEFAULT_BRANCH with default value."""
  8817. result = porcelain.var(self.repo_path, variable="GIT_DEFAULT_BRANCH")
  8818. self.assertEqual(result, "master")
  8819. def test_var_list_all(self):
  8820. """Test listing all logical variables."""
  8821. # Set up some config
  8822. config = self.repo.get_config()
  8823. config.set((b"user",), b"name", b"Test User")
  8824. config.set((b"user",), b"email", b"test@example.com")
  8825. config.write_to_path()
  8826. result = porcelain.var_list(self.repo_path)
  8827. self.assertIsInstance(result, dict)
  8828. # Check that logical variables are present
  8829. self.assertIn("GIT_AUTHOR_IDENT", result)
  8830. self.assertIn("GIT_COMMITTER_IDENT", result)
  8831. self.assertIn("GIT_DEFAULT_BRANCH", result)
  8832. # Config variables should NOT be included (deprecated feature)
  8833. self.assertNotIn("user.name", result)
  8834. self.assertNotIn("user.email", result)
  8835. # Verify only logical variables are present
  8836. for key in result.keys():
  8837. self.assertTrue(key.startswith("GIT_"))
  8838. def test_var_unknown_variable(self):
  8839. """Test requesting an unknown variable."""
  8840. with self.assertRaises(KeyError):
  8841. porcelain.var(self.repo_path, variable="UNKNOWN_VARIABLE")
  8842. class MergeBaseTests(PorcelainTestCase):
  8843. """Tests for merge-base, is_ancestor, and independent_commits."""
  8844. def test_merge_base_linear_history(self):
  8845. """Test merge-base with linear history."""
  8846. # Create linear history: c1 <- c2 <- c3
  8847. _c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8848. self.repo.refs[b"refs/heads/branch1"] = c2.id
  8849. self.repo.refs[b"refs/heads/branch2"] = c3.id
  8850. result = porcelain.merge_base(
  8851. self.repo.path, committishes=["refs/heads/branch1", "refs/heads/branch2"]
  8852. )
  8853. self.assertEqual([c2.id], result)
  8854. def test_merge_base_diverged(self):
  8855. """Test merge-base with diverged branches."""
  8856. # Create diverged history: c1 <- c2a, c1 <- c2b
  8857. c1, c2a, c2b = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1]])
  8858. self.repo.refs[b"refs/heads/branch-a"] = c2a.id
  8859. self.repo.refs[b"refs/heads/branch-b"] = c2b.id
  8860. result = porcelain.merge_base(
  8861. self.repo.path, committishes=["refs/heads/branch-a", "refs/heads/branch-b"]
  8862. )
  8863. self.assertEqual([c1.id], result)
  8864. def test_merge_base_all(self):
  8865. """Test merge-base with --all flag."""
  8866. # Create history with multiple common ancestors
  8867. commits = build_commit_graph(
  8868. self.repo.object_store,
  8869. [[1], [2, 1], [3, 1], [4, 2, 3], [5, 2, 3]],
  8870. )
  8871. _c1, c2, c3, c4, c5 = commits
  8872. self.repo.refs[b"refs/heads/branch1"] = c4.id
  8873. self.repo.refs[b"refs/heads/branch2"] = c5.id
  8874. # Without --all, should return only first result
  8875. result = porcelain.merge_base(
  8876. self.repo.path,
  8877. committishes=["refs/heads/branch1", "refs/heads/branch2"],
  8878. all=False,
  8879. )
  8880. self.assertEqual(1, len(result))
  8881. # With --all, should return all merge bases
  8882. result_all = porcelain.merge_base(
  8883. self.repo.path,
  8884. committishes=["refs/heads/branch1", "refs/heads/branch2"],
  8885. all=True,
  8886. )
  8887. self.assertEqual(2, len(result_all))
  8888. self.assertIn(c2.id, result_all)
  8889. self.assertIn(c3.id, result_all)
  8890. def test_merge_base_octopus(self):
  8891. """Test merge-base with --octopus flag."""
  8892. # Create three-way diverged history
  8893. commits = build_commit_graph(
  8894. self.repo.object_store, [[1], [2, 1], [3, 1], [4, 1]]
  8895. )
  8896. c1, c2, c3, c4 = commits
  8897. self.repo.refs[b"refs/heads/a"] = c2.id
  8898. self.repo.refs[b"refs/heads/b"] = c3.id
  8899. self.repo.refs[b"refs/heads/c"] = c4.id
  8900. result = porcelain.merge_base(
  8901. self.repo.path,
  8902. committishes=["refs/heads/a", "refs/heads/b", "refs/heads/c"],
  8903. octopus=True,
  8904. )
  8905. self.assertEqual([c1.id], result)
  8906. def test_merge_base_requires_two_commits(self):
  8907. """Test merge-base requires at least two commits."""
  8908. with self.assertRaises(ValueError):
  8909. porcelain.merge_base(self.repo.path, committishes=["HEAD"])
  8910. def test_is_ancestor_true(self):
  8911. """Test is_ancestor returns True when commit is an ancestor."""
  8912. # Create linear history: c1 <- c2 <- c3
  8913. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8914. self.repo.refs[b"refs/heads/main"] = c3.id
  8915. # c1 is ancestor of c3
  8916. result = porcelain.is_ancestor(
  8917. self.repo.path, ancestor=c1.id.decode(), descendant=c3.id.decode()
  8918. )
  8919. self.assertTrue(result)
  8920. # c2 is ancestor of c3
  8921. result = porcelain.is_ancestor(
  8922. self.repo.path, ancestor=c2.id.decode(), descendant=c3.id.decode()
  8923. )
  8924. self.assertTrue(result)
  8925. def test_is_ancestor_false(self):
  8926. """Test is_ancestor returns False when commit is not an ancestor."""
  8927. # Create diverged history: c1 <- c2a, c1 <- c2b
  8928. _c1, c2a, c2b = build_commit_graph(
  8929. self.repo.object_store, [[1], [2, 1], [3, 1]]
  8930. )
  8931. # c2a is not ancestor of c2b
  8932. result = porcelain.is_ancestor(
  8933. self.repo.path, ancestor=c2a.id.decode(), descendant=c2b.id.decode()
  8934. )
  8935. self.assertFalse(result)
  8936. # c2b is not ancestor of c2a
  8937. result = porcelain.is_ancestor(
  8938. self.repo.path, ancestor=c2b.id.decode(), descendant=c2a.id.decode()
  8939. )
  8940. self.assertFalse(result)
  8941. def test_is_ancestor_requires_both(self):
  8942. """Test is_ancestor requires both ancestor and descendant."""
  8943. with self.assertRaises(ValueError):
  8944. porcelain.is_ancestor(self.repo.path, ancestor="HEAD", descendant=None)
  8945. with self.assertRaises(ValueError):
  8946. porcelain.is_ancestor(self.repo.path, ancestor=None, descendant="HEAD")
  8947. def test_independent_commits_linear(self):
  8948. """Test independent_commits with linear history."""
  8949. # Create linear history: c1 <- c2 <- c3
  8950. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8951. # Only c3 is independent (c1 and c2 are ancestors)
  8952. result = porcelain.independent_commits(
  8953. self.repo.path,
  8954. committishes=[c1.id.decode(), c2.id.decode(), c3.id.decode()],
  8955. )
  8956. self.assertEqual([c3.id], result)
  8957. def test_independent_commits_diverged(self):
  8958. """Test independent_commits with diverged branches."""
  8959. # Create diverged history: c1 <- c2a, c1 <- c2b
  8960. _c1, c2a, c2b = build_commit_graph(
  8961. self.repo.object_store, [[1], [2, 1], [3, 1]]
  8962. )
  8963. # c2a and c2b are both independent (neither is ancestor of the other)
  8964. result = porcelain.independent_commits(
  8965. self.repo.path, committishes=[c2a.id.decode(), c2b.id.decode()]
  8966. )
  8967. self.assertEqual(2, len(result))
  8968. self.assertIn(c2a.id, result)
  8969. self.assertIn(c2b.id, result)
  8970. def test_independent_commits_mixed(self):
  8971. """Test independent_commits with mixed history."""
  8972. # Create mixed history
  8973. commits = build_commit_graph(
  8974. self.repo.object_store, [[1], [2, 1], [3, 1], [4, 2]]
  8975. )
  8976. _c1, c2, c3, c4 = commits
  8977. # c4 and c3 are independent; c2 is ancestor of c4
  8978. result = porcelain.independent_commits(
  8979. self.repo.path,
  8980. committishes=[c2.id.decode(), c3.id.decode(), c4.id.decode()],
  8981. )
  8982. self.assertEqual(2, len(result))
  8983. self.assertIn(c3.id, result)
  8984. self.assertIn(c4.id, result)
  8985. self.assertNotIn(c2.id, result)
  8986. def test_independent_commits_empty(self):
  8987. """Test independent_commits with empty list."""
  8988. result = porcelain.independent_commits(self.repo.path, committishes=[])
  8989. self.assertEqual([], result)
  8990. class CherryTests(PorcelainTestCase):
  8991. """Tests for cherry command."""
  8992. def test_cherry_no_changes(self):
  8993. """Test cherry when head and upstream are the same."""
  8994. # Create a simple commit
  8995. commit_sha = self.repo.get_worktree().commit(
  8996. b"Initial commit", committer=b"Test <test@example.com>"
  8997. )
  8998. # Cherry should return empty when comparing a commit to itself
  8999. results = porcelain.cherry(
  9000. self.repo.path, upstream=commit_sha.decode(), head=commit_sha.decode()
  9001. )
  9002. self.assertEqual([], results)
  9003. def test_cherry_unique_commits(self):
  9004. """Test cherry with commits unique to head."""
  9005. # Create initial commit
  9006. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  9007. f.write("base content\n")
  9008. self.repo.get_worktree().stage(["file1.txt"])
  9009. base_commit = self.repo.get_worktree().commit(
  9010. b"Base commit", committer=b"Test <test@example.com>"
  9011. )
  9012. # Create a new commit on head
  9013. with open(os.path.join(self.repo_path, "file2.txt"), "w") as f:
  9014. f.write("new content\n")
  9015. self.repo.get_worktree().stage(["file2.txt"])
  9016. head_commit = self.repo.get_worktree().commit(
  9017. b"New commit", committer=b"Test <test@example.com>"
  9018. )
  9019. # Cherry should show the new commit as unique
  9020. results = porcelain.cherry(
  9021. self.repo.path, upstream=base_commit.decode(), head=head_commit.decode()
  9022. )
  9023. self.assertEqual(1, len(results))
  9024. status, commit_sha, message = results[0]
  9025. self.assertEqual("+", status)
  9026. self.assertEqual(head_commit, commit_sha)
  9027. self.assertIsNone(message)
  9028. def test_cherry_verbose(self):
  9029. """Test cherry with verbose flag."""
  9030. # Create initial commit
  9031. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  9032. f.write("base content\n")
  9033. self.repo.get_worktree().stage(["file1.txt"])
  9034. base_commit = self.repo.get_worktree().commit(
  9035. b"Base commit", committer=b"Test <test@example.com>"
  9036. )
  9037. # Create a new commit on head
  9038. with open(os.path.join(self.repo_path, "file2.txt"), "w") as f:
  9039. f.write("new content\n")
  9040. self.repo.get_worktree().stage(["file2.txt"])
  9041. head_commit = self.repo.get_worktree().commit(
  9042. b"New commit on head", committer=b"Test <test@example.com>"
  9043. )
  9044. # Cherry with verbose should include commit message
  9045. results = porcelain.cherry(
  9046. self.repo.path,
  9047. upstream=base_commit.decode(),
  9048. head=head_commit.decode(),
  9049. verbose=True,
  9050. )
  9051. self.assertEqual(1, len(results))
  9052. status, commit_sha, message = results[0]
  9053. self.assertEqual("+", status)
  9054. self.assertEqual(head_commit, commit_sha)
  9055. self.assertEqual(b"New commit on head", message)
  9056. def test_cherry_equivalent_patches(self):
  9057. """Test cherry with equivalent patches (cherry-picked commits)."""
  9058. # Create base commit
  9059. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  9060. f.write("line1\n")
  9061. self.repo.get_worktree().stage(["file.txt"])
  9062. base_commit = self.repo.get_worktree().commit(
  9063. b"Base commit", committer=b"Test <test@example.com>"
  9064. )
  9065. # Create upstream branch with a change
  9066. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  9067. f.write("line1\nline2\n")
  9068. self.repo.get_worktree().stage(["file.txt"])
  9069. upstream_commit = self.repo.get_worktree().commit(
  9070. b"Add line2", committer=b"Test <test@example.com>"
  9071. )
  9072. # Reset to base and create same change on head branch
  9073. self.repo.refs[b"HEAD"] = base_commit
  9074. self.repo.get_worktree().reset_index()
  9075. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  9076. f.write("line1\nline2\n")
  9077. self.repo.get_worktree().stage(["file.txt"])
  9078. head_commit = self.repo.get_worktree().commit(
  9079. b"Add line2 (different metadata)",
  9080. committer=b"Different <different@example.com>",
  9081. )
  9082. # Cherry should mark this as equivalent (-)
  9083. results = porcelain.cherry(
  9084. self.repo.path,
  9085. upstream=upstream_commit.decode(),
  9086. head=head_commit.decode(),
  9087. )
  9088. self.assertEqual(1, len(results))
  9089. status, commit_sha, _message = results[0]
  9090. self.assertEqual("-", status)
  9091. self.assertEqual(head_commit, commit_sha)
  9092. class GrepTests(PorcelainTestCase):
  9093. def test_basic_grep(self) -> None:
  9094. """Test basic pattern matching in files."""
  9095. # Create some test files
  9096. with open(os.path.join(self.repo_path, "foo.txt"), "w") as f:
  9097. f.write("hello world\ngoodbye world\n")
  9098. with open(os.path.join(self.repo_path, "bar.txt"), "w") as f:
  9099. f.write("foo bar\nbaz qux\n")
  9100. porcelain.add(self.repo, paths=["foo.txt", "bar.txt"])
  9101. porcelain.commit(self.repo, message=b"Add test files")
  9102. # Search for "world"
  9103. outstream = StringIO()
  9104. porcelain.grep(self.repo, "world", outstream=outstream)
  9105. output = outstream.getvalue().replace("\r\n", "\n")
  9106. self.assertEqual("foo.txt:hello world\nfoo.txt:goodbye world\n", output)
  9107. def test_grep_with_line_numbers(self) -> None:
  9108. """Test grep with line numbers."""
  9109. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  9110. f.write("line one\nline two\nline three\n")
  9111. porcelain.add(self.repo, paths=["test.txt"])
  9112. porcelain.commit(self.repo, message=b"Add test file")
  9113. outstream = StringIO()
  9114. porcelain.grep(self.repo, "line", outstream=outstream, line_number=True)
  9115. output = outstream.getvalue().replace("\r\n", "\n")
  9116. self.assertEqual(
  9117. "test.txt:1:line one\ntest.txt:2:line two\ntest.txt:3:line three\n",
  9118. output,
  9119. )
  9120. def test_grep_case_insensitive(self) -> None:
  9121. """Test case-insensitive grep."""
  9122. with open(os.path.join(self.repo_path, "case.txt"), "w") as f:
  9123. f.write("Hello WORLD\nGoodbye world\n")
  9124. porcelain.add(self.repo, paths=["case.txt"])
  9125. porcelain.commit(self.repo, message=b"Add case file")
  9126. outstream = StringIO()
  9127. porcelain.grep(self.repo, "HELLO", outstream=outstream, ignore_case=True)
  9128. output = outstream.getvalue().replace("\r\n", "\n")
  9129. self.assertEqual("case.txt:Hello WORLD\n", output)
  9130. def test_grep_with_pathspec(self) -> None:
  9131. """Test grep with pathspec filtering."""
  9132. os.makedirs(os.path.join(self.repo_path, "subdir"))
  9133. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  9134. f.write("pattern match\n")
  9135. with open(os.path.join(self.repo_path, "subdir", "file2.txt"), "w") as f:
  9136. f.write("pattern match\n")
  9137. porcelain.add(self.repo, paths=["file1.txt", "subdir/file2.txt"])
  9138. porcelain.commit(self.repo, message=b"Add files")
  9139. # Search only in subdir
  9140. outstream = StringIO()
  9141. porcelain.grep(self.repo, "pattern", outstream=outstream, pathspecs=["subdir/"])
  9142. output = outstream.getvalue().replace("\r\n", "\n")
  9143. self.assertEqual("subdir/file2.txt:pattern match\n", output)
  9144. def test_grep_no_matches(self) -> None:
  9145. """Test grep with no matches."""
  9146. with open(os.path.join(self.repo_path, "empty.txt"), "w") as f:
  9147. f.write("nothing to see here\n")
  9148. porcelain.add(self.repo, paths=["empty.txt"])
  9149. porcelain.commit(self.repo, message=b"Add empty file")
  9150. outstream = StringIO()
  9151. porcelain.grep(self.repo, "nonexistent", outstream=outstream)
  9152. output = outstream.getvalue()
  9153. self.assertEqual("", output)
  9154. def test_grep_regex_pattern(self) -> None:
  9155. """Test grep with regex patterns."""
  9156. with open(os.path.join(self.repo_path, "regex.txt"), "w") as f:
  9157. f.write("test123\ntest456\nnotest\n")
  9158. porcelain.add(self.repo, paths=["regex.txt"])
  9159. porcelain.commit(self.repo, message=b"Add regex file")
  9160. # Search for "test" followed by digits
  9161. outstream = StringIO()
  9162. porcelain.grep(self.repo, r"test\d+", outstream=outstream)
  9163. output = outstream.getvalue().replace("\r\n", "\n")
  9164. self.assertEqual("regex.txt:test123\nregex.txt:test456\n", output)
  9165. def test_grep_invalid_pattern(self) -> None:
  9166. """Test grep with invalid regex pattern."""
  9167. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  9168. f.write("test\n")
  9169. porcelain.add(self.repo, paths=["test.txt"])
  9170. porcelain.commit(self.repo, message=b"Add test file")
  9171. outstream = StringIO()
  9172. with self.assertRaises(ValueError):
  9173. porcelain.grep(self.repo, "[invalid", outstream=outstream)
  9174. def test_grep_no_head(self) -> None:
  9175. """Test grep fails when there's no HEAD commit."""
  9176. # Create a fresh repo with no commits
  9177. empty_repo_path = os.path.join(self.test_dir, "empty_repo")
  9178. empty_repo = Repo.init(empty_repo_path, mkdir=True)
  9179. self.addCleanup(empty_repo.close)
  9180. outstream = StringIO()
  9181. with self.assertRaises(ValueError):
  9182. porcelain.grep(empty_repo, "pattern", outstream=outstream)
  9183. class ReplaceListTests(PorcelainTestCase):
  9184. def test_empty(self) -> None:
  9185. """Test listing replacements when there are none."""
  9186. replacements = porcelain.replace_list(self.repo)
  9187. self.assertEqual([], replacements)
  9188. def test_list_replacements(self) -> None:
  9189. """Test listing replacement refs."""
  9190. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9191. self.repo[b"HEAD"] = c1.id
  9192. # Create a replacement
  9193. porcelain.replace_create(self.repo, c1.id, c2.id)
  9194. # List replacements
  9195. replacements = porcelain.replace_list(self.repo)
  9196. self.assertEqual(1, len(replacements))
  9197. self.assertEqual((c1.id, c2.id), replacements[0])
  9198. class ReplaceCreateTests(PorcelainTestCase):
  9199. def test_create_replacement(self) -> None:
  9200. """Test creating a replacement ref."""
  9201. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9202. self.repo[b"HEAD"] = c1.id
  9203. # Create a replacement
  9204. porcelain.replace_create(self.repo, c1.id, c2.id)
  9205. # Verify the replacement ref was created (c1.id is already 40-char hex bytes)
  9206. replace_ref = b"refs/replace/" + c1.id
  9207. self.assertIn(replace_ref, self.repo.refs)
  9208. self.assertEqual(c2.id, self.repo.refs[replace_ref])
  9209. def test_create_replacement_with_bytes(self) -> None:
  9210. """Test creating a replacement ref with bytes arguments."""
  9211. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9212. self.repo[b"HEAD"] = c1.id
  9213. # Create a replacement using bytes arguments
  9214. porcelain.replace_create(self.repo, c1.id, c2.id)
  9215. # Verify the replacement ref was created
  9216. replace_ref = b"refs/replace/" + c1.id
  9217. self.assertIn(replace_ref, self.repo.refs)
  9218. self.assertEqual(c2.id, self.repo.refs[replace_ref])
  9219. class ReplaceDeleteTests(PorcelainTestCase):
  9220. def test_delete_replacement(self) -> None:
  9221. """Test deleting a replacement ref."""
  9222. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9223. self.repo[b"HEAD"] = c1.id
  9224. # Create a replacement
  9225. porcelain.replace_create(self.repo, c1.id, c2.id)
  9226. # Verify it exists
  9227. replacements = porcelain.replace_list(self.repo)
  9228. self.assertEqual(1, len(replacements))
  9229. # Delete the replacement
  9230. porcelain.replace_delete(self.repo, c1.id)
  9231. # Verify it's gone
  9232. replacements = porcelain.replace_list(self.repo)
  9233. self.assertEqual(0, len(replacements))
  9234. def test_delete_replacement_with_bytes(self) -> None:
  9235. """Test deleting a replacement ref with bytes argument."""
  9236. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9237. self.repo[b"HEAD"] = c1.id
  9238. # Create a replacement
  9239. porcelain.replace_create(self.repo, c1.id, c2.id)
  9240. # Delete using bytes argument
  9241. porcelain.replace_delete(self.repo, c1.id)
  9242. # Verify it's gone
  9243. replacements = porcelain.replace_list(self.repo)
  9244. self.assertEqual(0, len(replacements))
  9245. def test_delete_nonexistent_replacement(self) -> None:
  9246. """Test deleting a replacement ref that doesn't exist raises KeyError."""
  9247. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9248. self.repo[b"HEAD"] = c1.id
  9249. # Try to delete a non-existent replacement
  9250. with self.assertRaises(KeyError):
  9251. porcelain.replace_delete(self.repo, c1.id)
  9252. class GitReflogActionTests(PorcelainTestCase):
  9253. """Tests for GIT_REFLOG_ACTION environment variable support."""
  9254. def test_reset_with_git_reflog_action(self) -> None:
  9255. """Test that reset respects GIT_REFLOG_ACTION environment variable."""
  9256. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9257. self.repo.refs[b"HEAD"] = c2.id
  9258. # Set GIT_REFLOG_ACTION environment variable
  9259. self.overrideEnv("GIT_REFLOG_ACTION", "custom reset action")
  9260. # Reset to c1
  9261. porcelain.reset(self.repo, "hard", c1.id.decode())
  9262. # Check reflog message - HEAD is a symref to refs/heads/master
  9263. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/master"))
  9264. self.assertEqual(1, len(entries))
  9265. self.assertEqual(b"custom reset action", entries[0].message)
  9266. def test_commit_amend_with_git_reflog_action(self) -> None:
  9267. """Test that commit --amend respects GIT_REFLOG_ACTION environment variable."""
  9268. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9269. self.repo.refs[b"HEAD"] = c1.id
  9270. # Set GIT_REFLOG_ACTION environment variable
  9271. self.overrideEnv("GIT_REFLOG_ACTION", "custom amend action")
  9272. # Amend the commit
  9273. porcelain.commit(self.repo, b"amended message", amend=True)
  9274. # Check reflog message - HEAD is a symref to refs/heads/master
  9275. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/master"))
  9276. self.assertEqual(1, len(entries))
  9277. self.assertEqual(b"custom amend action", entries[0].message)
  9278. def test_branch_create_with_git_reflog_action(self) -> None:
  9279. """Test that branch_create respects GIT_REFLOG_ACTION environment variable."""
  9280. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9281. self.repo.refs[b"HEAD"] = c1.id
  9282. # Set GIT_REFLOG_ACTION environment variable
  9283. self.overrideEnv("GIT_REFLOG_ACTION", "custom branch action")
  9284. # Create a new branch
  9285. porcelain.branch_create(self.repo, b"test-branch")
  9286. # Check reflog message
  9287. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/test-branch"))
  9288. self.assertEqual(1, len(entries))
  9289. self.assertEqual(b"custom branch action", entries[0].message)
  9290. def test_reset_without_git_reflog_action(self) -> None:
  9291. """Test that reset uses default message when GIT_REFLOG_ACTION is not set."""
  9292. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9293. self.repo.refs[b"HEAD"] = c2.id
  9294. # Reset to c1 without GIT_REFLOG_ACTION
  9295. porcelain.reset(self.repo, "hard", c1.id.decode())
  9296. # Check reflog message contains default format - HEAD is a symref to refs/heads/master
  9297. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/master"))
  9298. self.assertEqual(1, len(entries))
  9299. self.assertTrue(entries[0].message.startswith(b"reset: moving to"))
  9300. def test_branch_create_without_git_reflog_action(self) -> None:
  9301. """Test that branch_create uses default message when GIT_REFLOG_ACTION is not set."""
  9302. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9303. self.repo.refs[b"HEAD"] = c1.id
  9304. # Create a new branch without GIT_REFLOG_ACTION
  9305. porcelain.branch_create(self.repo, b"test-branch")
  9306. # Check reflog message contains default format
  9307. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/test-branch"))
  9308. self.assertEqual(1, len(entries))
  9309. self.assertTrue(entries[0].message.startswith(b"branch: Created from"))
  9310. class PorcelainMailinfoTests(TestCase):
  9311. """Tests for porcelain.mailinfo function."""
  9312. def test_mailinfo_basic(self) -> None:
  9313. """Test basic mailinfo functionality."""
  9314. from io import BytesIO
  9315. email_content = b"""From: Test User <test@example.com>
  9316. Subject: [PATCH] Add feature
  9317. Date: Mon, 1 Jan 2024 12:00:00 +0000
  9318. Commit message here.
  9319. ---
  9320. diff --git a/file.txt b/file.txt
  9321. """
  9322. result = porcelain.mailinfo(BytesIO(email_content))
  9323. self.assertEqual("Test User", result.author_name)
  9324. self.assertEqual("test@example.com", result.author_email)
  9325. self.assertEqual("Add feature", result.subject)
  9326. self.assertIn("Commit message here.", result.message)
  9327. self.assertIn("diff --git", result.patch)
  9328. def test_mailinfo_write_to_files(self) -> None:
  9329. """Test mailinfo writing message and patch to files."""
  9330. from io import BytesIO
  9331. email_content = b"""From: Test <test@example.com>
  9332. Subject: Test
  9333. Message content
  9334. ---
  9335. Patch content
  9336. """
  9337. with tempfile.TemporaryDirectory() as tmpdir:
  9338. msg_file = os.path.join(tmpdir, "msg")
  9339. patch_file = os.path.join(tmpdir, "patch")
  9340. result = porcelain.mailinfo(
  9341. BytesIO(email_content), msg_file=msg_file, patch_file=patch_file
  9342. )
  9343. # Check that files were written
  9344. self.assertTrue(os.path.exists(msg_file))
  9345. self.assertTrue(os.path.exists(patch_file))
  9346. # Check file contents
  9347. with open(msg_file) as f:
  9348. msg_content = f.read()
  9349. self.assertIn("Message content", msg_content)
  9350. with open(patch_file) as f:
  9351. patch_content = f.read()
  9352. self.assertIn("Patch content", patch_content)
  9353. # Check return value
  9354. self.assertEqual("Test", result.subject)
  9355. def test_mailinfo_with_options(self) -> None:
  9356. """Test mailinfo with various options."""
  9357. from io import BytesIO
  9358. email_content = b"""From: Test <test@example.com>
  9359. Subject: [RFC][PATCH] Feature
  9360. Message-ID: <id@example.com>
  9361. Text before scissors
  9362. -- >8 --
  9363. Text after scissors
  9364. """
  9365. # Test with keep_non_patch, scissors, and message_id
  9366. result = porcelain.mailinfo(
  9367. BytesIO(email_content),
  9368. keep_non_patch=True,
  9369. scissors=True,
  9370. message_id=True,
  9371. )
  9372. self.assertEqual("[RFC] Feature", result.subject)
  9373. self.assertIn("Text after scissors", result.message)
  9374. self.assertNotIn("Text before scissors", result.message)
  9375. self.assertIn("Message-ID:", result.message)
  9376. def test_mailinfo_from_file_path(self) -> None:
  9377. """Test mailinfo reading from file path."""
  9378. email_content = b"""From: Test <test@example.com>
  9379. Subject: Test
  9380. Body
  9381. """
  9382. with tempfile.TemporaryDirectory() as tmpdir:
  9383. email_path = os.path.join(tmpdir, "email.txt")
  9384. with open(email_path, "wb") as f:
  9385. f.write(email_content)
  9386. result = porcelain.mailinfo(input_path=email_path)
  9387. self.assertEqual("Test", result.subject)
  9388. self.assertEqual("test@example.com", result.author_email)