__init__.py 414 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309
  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. from dulwich.signature import (
  562. BadSignature,
  563. UntrustedSignature,
  564. get_signature_vendor_for_signature,
  565. )
  566. self.assertIsNotNone(commit.gpgsig)
  567. vendor = get_signature_vendor_for_signature(commit.gpgsig)
  568. vendor.verify(commit.raw_without_sig(), commit.gpgsig)
  569. vendor.verify(
  570. commit.raw_without_sig(),
  571. commit.gpgsig,
  572. keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID],
  573. )
  574. self.import_non_default_key()
  575. self.assertRaises(
  576. UntrustedSignature,
  577. vendor.verify,
  578. commit.raw_without_sig(),
  579. commit.gpgsig,
  580. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  581. )
  582. assert isinstance(commit, Commit)
  583. commit.committer = b"Alice <alice@example.com>"
  584. self.assertRaises(
  585. BadSignature,
  586. vendor.verify,
  587. commit.raw_without_sig(),
  588. commit.gpgsig,
  589. )
  590. def test_non_default_key(self) -> None:
  591. _c1, _c2, c3 = build_commit_graph(
  592. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  593. )
  594. self.repo.refs[b"HEAD"] = c3.id
  595. cfg = self.repo.get_config()
  596. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  597. self.import_non_default_key()
  598. sha = porcelain.commit(
  599. self.repo.path,
  600. message="Some message",
  601. author="Joe <joe@example.com>",
  602. committer="Bob <bob@example.com>",
  603. sign=PorcelainGpgTestCase.NON_DEFAULT_KEY_ID,
  604. )
  605. self.assertIsInstance(sha, bytes)
  606. self.assertEqual(len(sha), 40)
  607. commit = self.repo.get_object(sha)
  608. assert isinstance(commit, Commit)
  609. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  610. from dulwich.signature import get_signature_vendor_for_signature
  611. self.assertIsNotNone(commit.gpgsig)
  612. vendor = get_signature_vendor_for_signature(commit.gpgsig)
  613. vendor.verify(commit.raw_without_sig(), commit.gpgsig)
  614. def test_sign_uses_config_signingkey(self) -> None:
  615. """Test that sign=True uses user.signingKey from config."""
  616. _c1, _c2, c3 = build_commit_graph(
  617. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  618. )
  619. self.repo.refs[b"HEAD"] = c3.id
  620. # Set up user.signingKey in config
  621. cfg = self.repo.get_config()
  622. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  623. cfg.write_to_path()
  624. self.import_default_key()
  625. # Create commit with sign=True (should use signingKey from config)
  626. sha = porcelain.commit(
  627. self.repo.path,
  628. message="Signed with configured key",
  629. author="Joe <joe@example.com>",
  630. committer="Bob <bob@example.com>",
  631. sign=True, # This should read user.signingKey from config
  632. )
  633. self.assertIsInstance(sha, bytes)
  634. self.assertEqual(len(sha), 40)
  635. commit = self.repo.get_object(sha)
  636. assert isinstance(commit, Commit)
  637. # Verify the commit is signed with the configured key
  638. from dulwich.signature import get_signature_vendor_for_signature
  639. self.assertIsNotNone(commit.gpgsig)
  640. vendor = get_signature_vendor_for_signature(commit.gpgsig)
  641. vendor.verify(commit.raw_without_sig(), commit.gpgsig)
  642. vendor.verify(
  643. commit.raw_without_sig(),
  644. commit.gpgsig,
  645. keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID],
  646. )
  647. def test_commit_gpg_sign_config_enabled(self) -> None:
  648. """Test that commit.gpgSign=true automatically signs commits."""
  649. _c1, _c2, c3 = build_commit_graph(
  650. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  651. )
  652. self.repo.refs[b"HEAD"] = c3.id
  653. # Set up user.signingKey and commit.gpgSign in config
  654. cfg = self.repo.get_config()
  655. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  656. cfg.set(("commit",), "gpgSign", True)
  657. cfg.write_to_path()
  658. self.import_default_key()
  659. # Create commit without explicit signoff parameter (should auto-sign due to config)
  660. sha = porcelain.commit(
  661. self.repo.path,
  662. message="Auto-signed commit",
  663. author="Joe <joe@example.com>",
  664. committer="Bob <bob@example.com>",
  665. # No signoff parameter - should use commit.gpgSign config
  666. )
  667. self.assertIsInstance(sha, bytes)
  668. self.assertEqual(len(sha), 40)
  669. commit = self.repo.get_object(sha)
  670. assert isinstance(commit, Commit)
  671. # Verify the commit is signed due to config
  672. from dulwich.signature import get_signature_vendor_for_signature
  673. self.assertIsNotNone(commit.gpgsig)
  674. vendor = get_signature_vendor_for_signature(commit.gpgsig)
  675. vendor.verify(commit.raw_without_sig(), commit.gpgsig)
  676. vendor.verify(
  677. commit.raw_without_sig(),
  678. commit.gpgsig,
  679. keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID],
  680. )
  681. def test_commit_gpg_sign_config_disabled(self) -> None:
  682. """Test that commit.gpgSign=false does not sign commits."""
  683. _c1, _c2, c3 = build_commit_graph(
  684. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  685. )
  686. self.repo.refs[b"HEAD"] = c3.id
  687. # Set up user.signingKey and commit.gpgSign=false in config
  688. cfg = self.repo.get_config()
  689. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  690. cfg.set(("commit",), "gpgSign", False)
  691. cfg.write_to_path()
  692. self.import_default_key()
  693. # Create commit without explicit signoff parameter (should not sign)
  694. sha = porcelain.commit(
  695. self.repo.path,
  696. message="Unsigned commit",
  697. author="Joe <joe@example.com>",
  698. committer="Bob <bob@example.com>",
  699. # No signoff parameter - should use commit.gpgSign=false config
  700. )
  701. self.assertIsInstance(sha, bytes)
  702. self.assertEqual(len(sha), 40)
  703. commit = self.repo.get_object(sha)
  704. assert isinstance(commit, Commit)
  705. # Verify the commit is not signed
  706. self.assertIsNone(commit._gpgsig)
  707. def test_commit_gpg_sign_config_no_signing_key(self) -> None:
  708. """Test that commit.gpgSign=true works without user.signingKey (uses default)."""
  709. _c1, _c2, c3 = build_commit_graph(
  710. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  711. )
  712. self.repo.refs[b"HEAD"] = c3.id
  713. # Set up commit.gpgSign but no user.signingKey
  714. cfg = self.repo.get_config()
  715. cfg.set(("commit",), "gpgSign", True)
  716. cfg.write_to_path()
  717. self.import_default_key()
  718. # Create commit without explicit signoff parameter (should auto-sign with default key)
  719. sha = porcelain.commit(
  720. self.repo.path,
  721. message="Default signed commit",
  722. author="Joe <joe@example.com>",
  723. committer="Bob <bob@example.com>",
  724. # No signoff parameter - should use commit.gpgSign config with default key
  725. )
  726. self.assertIsInstance(sha, bytes)
  727. self.assertEqual(len(sha), 40)
  728. commit = self.repo.get_object(sha)
  729. assert isinstance(commit, Commit)
  730. # Verify the commit is signed with default key
  731. from dulwich.signature import get_signature_vendor_for_signature
  732. self.assertIsNotNone(commit.gpgsig)
  733. vendor = get_signature_vendor_for_signature(commit.gpgsig)
  734. vendor.verify(commit.raw_without_sig(), commit.gpgsig)
  735. def test_explicit_signoff_overrides_config(self) -> None:
  736. """Test that explicit signoff parameter overrides commit.gpgSign config."""
  737. _c1, _c2, c3 = build_commit_graph(
  738. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  739. )
  740. self.repo.refs[b"HEAD"] = c3.id
  741. # Set up commit.gpgSign=false but explicitly pass sign=True
  742. cfg = self.repo.get_config()
  743. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  744. cfg.set(("commit",), "gpgSign", False)
  745. cfg.write_to_path()
  746. self.import_default_key()
  747. # Create commit with explicit sign=True (should override config)
  748. sha = porcelain.commit(
  749. self.repo.path,
  750. message="Explicitly signed commit",
  751. author="Joe <joe@example.com>",
  752. committer="Bob <bob@example.com>",
  753. sign=True, # This should override commit.gpgSign=false
  754. )
  755. self.assertIsInstance(sha, bytes)
  756. self.assertEqual(len(sha), 40)
  757. commit = self.repo.get_object(sha)
  758. assert isinstance(commit, Commit)
  759. # Verify the commit is signed despite config=false
  760. from dulwich.signature import get_signature_vendor_for_signature
  761. self.assertIsNotNone(commit.gpgsig)
  762. vendor = get_signature_vendor_for_signature(commit.gpgsig)
  763. vendor.verify(commit.raw_without_sig(), commit.gpgsig)
  764. vendor.verify(
  765. commit.raw_without_sig(),
  766. commit.gpgsig,
  767. keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID],
  768. )
  769. def test_explicit_false_disables_signing(self) -> None:
  770. """Test that explicit signoff=False disables signing even with config=true."""
  771. _c1, _c2, c3 = build_commit_graph(
  772. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  773. )
  774. self.repo.refs[b"HEAD"] = c3.id
  775. # Set up commit.gpgSign=true but explicitly pass sign=False
  776. cfg = self.repo.get_config()
  777. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  778. cfg.set(("commit",), "gpgSign", True)
  779. cfg.write_to_path()
  780. self.import_default_key()
  781. # Create commit with explicit sign=False (should disable signing)
  782. sha = porcelain.commit(
  783. self.repo.path,
  784. message="Explicitly unsigned commit",
  785. author="Joe <joe@example.com>",
  786. committer="Bob <bob@example.com>",
  787. sign=False, # This should override commit.gpgSign=true
  788. )
  789. self.assertIsInstance(sha, bytes)
  790. self.assertEqual(len(sha), 40)
  791. commit = self.repo.get_object(sha)
  792. assert isinstance(commit, Commit)
  793. # Verify the commit is NOT signed despite config=true
  794. self.assertIsNone(commit._gpgsig)
  795. @skipIf(
  796. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  797. "gpgme not easily available or supported on Windows and PyPy",
  798. )
  799. class VerifyCommitTests(PorcelainGpgTestCase):
  800. def test_verify_commit_valid_signature(self) -> None:
  801. """Test verifying a commit with a valid GPG signature."""
  802. _c1, _c2, c3 = build_commit_graph(
  803. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  804. )
  805. self.repo.refs[b"HEAD"] = c3.id
  806. cfg = self.repo.get_config()
  807. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  808. cfg.write_to_path()
  809. self.import_default_key()
  810. # Create a signed commit
  811. sha = porcelain.commit(
  812. self.repo.path,
  813. message="Signed commit",
  814. author="Joe <joe@example.com>",
  815. committer="Bob <bob@example.com>",
  816. sign=True,
  817. )
  818. # Verify should not raise
  819. porcelain.verify_commit(self.repo.path, sha)
  820. porcelain.verify_commit(
  821. self.repo.path, sha, keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID]
  822. )
  823. def test_verify_commit_with_wrong_key(self) -> None:
  824. """Test that verifying with wrong keyid raises UntrustedSignature."""
  825. from dulwich.signature import UntrustedSignature
  826. _c1, _c2, c3 = build_commit_graph(
  827. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  828. )
  829. self.repo.refs[b"HEAD"] = c3.id
  830. cfg = self.repo.get_config()
  831. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  832. cfg.write_to_path()
  833. self.import_default_key()
  834. sha = porcelain.commit(
  835. self.repo.path,
  836. message="Signed commit",
  837. author="Joe <joe@example.com>",
  838. committer="Bob <bob@example.com>",
  839. sign=True,
  840. )
  841. self.import_non_default_key()
  842. self.assertRaises(
  843. UntrustedSignature,
  844. porcelain.verify_commit,
  845. self.repo.path,
  846. sha,
  847. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  848. )
  849. def test_verify_commit_unsigned(self) -> None:
  850. """Test that verifying an unsigned commit succeeds (no signature to verify)."""
  851. _c1, _c2, c3 = build_commit_graph(
  852. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  853. )
  854. self.repo.refs[b"HEAD"] = c3.id
  855. sha = porcelain.commit(
  856. self.repo.path,
  857. message="Unsigned commit",
  858. author="Joe <joe@example.com>",
  859. committer="Bob <bob@example.com>",
  860. sign=False,
  861. )
  862. # Verify should not raise for unsigned commits
  863. porcelain.verify_commit(self.repo.path, sha)
  864. @skipIf(
  865. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  866. "gpgme not easily available or supported on Windows and PyPy",
  867. )
  868. class VerifyTagTests(PorcelainGpgTestCase):
  869. def test_verify_tag_valid_signature(self) -> None:
  870. """Test verifying a tag with a valid GPG signature."""
  871. _c1, _c2, c3 = build_commit_graph(
  872. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  873. )
  874. self.repo.refs[b"HEAD"] = c3.id
  875. cfg = self.repo.get_config()
  876. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  877. cfg.write_to_path()
  878. self.import_default_key()
  879. # Create a signed tag
  880. porcelain.tag_create(
  881. self.repo.path,
  882. b"signed-tag",
  883. b"Tagger <tagger@example.com>",
  884. b"Signed tag message",
  885. annotated=True,
  886. sign=True,
  887. )
  888. # Verify should not raise
  889. porcelain.verify_tag(self.repo.path, b"signed-tag")
  890. porcelain.verify_tag(
  891. self.repo.path, b"signed-tag", keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID]
  892. )
  893. def test_verify_tag_with_wrong_key(self) -> None:
  894. """Test that verifying with wrong keyid raises UntrustedSignature."""
  895. from dulwich.signature import UntrustedSignature
  896. _c1, _c2, c3 = build_commit_graph(
  897. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  898. )
  899. self.repo.refs[b"HEAD"] = c3.id
  900. cfg = self.repo.get_config()
  901. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  902. cfg.write_to_path()
  903. self.import_default_key()
  904. porcelain.tag_create(
  905. self.repo.path,
  906. b"signed-tag",
  907. b"Tagger <tagger@example.com>",
  908. b"Signed tag message",
  909. annotated=True,
  910. sign=True,
  911. )
  912. self.import_non_default_key()
  913. self.assertRaises(
  914. UntrustedSignature,
  915. porcelain.verify_tag,
  916. self.repo.path,
  917. b"signed-tag",
  918. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  919. )
  920. def test_verify_tag_unsigned(self) -> None:
  921. """Test that verifying an unsigned tag succeeds (no signature to verify)."""
  922. _c1, _c2, c3 = build_commit_graph(
  923. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  924. )
  925. self.repo.refs[b"HEAD"] = c3.id
  926. porcelain.tag_create(
  927. self.repo.path,
  928. b"unsigned-tag",
  929. b"Tagger <tagger@example.com>",
  930. b"Unsigned tag message",
  931. annotated=True,
  932. sign=False,
  933. )
  934. # Verify should not raise for unsigned tags
  935. porcelain.verify_tag(self.repo.path, b"unsigned-tag")
  936. class TimezoneTests(PorcelainTestCase):
  937. def put_envs(self, value) -> None:
  938. self.overrideEnv("GIT_AUTHOR_DATE", value)
  939. self.overrideEnv("GIT_COMMITTER_DATE", value)
  940. def fallback(self, value) -> None:
  941. self.put_envs(value)
  942. self.assertRaises(porcelain.TimezoneFormatError, porcelain.get_user_timezones)
  943. def test_internal_format(self) -> None:
  944. self.put_envs("0 +0500")
  945. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  946. def test_rfc_2822(self) -> None:
  947. self.put_envs("Mon, 20 Nov 1995 19:12:08 -0500")
  948. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  949. self.put_envs("Mon, 20 Nov 1995 19:12:08")
  950. self.assertTupleEqual((0, 0), porcelain.get_user_timezones())
  951. def test_iso8601(self) -> None:
  952. self.put_envs("1995-11-20T19:12:08-0501")
  953. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  954. self.put_envs("1995-11-20T19:12:08+0501")
  955. self.assertTupleEqual((18060, 18060), porcelain.get_user_timezones())
  956. self.put_envs("1995-11-20T19:12:08-05:01")
  957. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  958. self.put_envs("1995-11-20 19:12:08-05")
  959. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  960. # https://github.com/git/git/blob/96b2d4fa927c5055adc5b1d08f10a5d7352e2989/t/t6300-for-each-ref.sh#L128
  961. self.put_envs("2006-07-03 17:18:44 +0200")
  962. self.assertTupleEqual((7200, 7200), porcelain.get_user_timezones())
  963. def test_missing_or_malformed(self) -> None:
  964. # TODO: add more here
  965. self.fallback("0 + 0500")
  966. self.fallback("a +0500")
  967. self.fallback("1995-11-20T19:12:08")
  968. self.fallback("1995-11-20T19:12:08-05:")
  969. self.fallback("1995.11.20")
  970. self.fallback("11/20/1995")
  971. self.fallback("20.11.1995")
  972. def test_different_envs(self) -> None:
  973. self.overrideEnv("GIT_AUTHOR_DATE", "0 +0500")
  974. self.overrideEnv("GIT_COMMITTER_DATE", "0 +0501")
  975. self.assertTupleEqual((18000, 18060), porcelain.get_user_timezones())
  976. def test_no_envs(self) -> None:
  977. local_timezone = time.localtime().tm_gmtoff
  978. self.put_envs("0 +0500")
  979. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  980. self.overrideEnv("GIT_COMMITTER_DATE", None)
  981. self.assertTupleEqual((18000, local_timezone), porcelain.get_user_timezones())
  982. self.put_envs("0 +0500")
  983. self.overrideEnv("GIT_AUTHOR_DATE", None)
  984. self.assertTupleEqual((local_timezone, 18000), porcelain.get_user_timezones())
  985. self.put_envs("0 +0500")
  986. self.overrideEnv("GIT_AUTHOR_DATE", None)
  987. self.overrideEnv("GIT_COMMITTER_DATE", None)
  988. self.assertTupleEqual(
  989. (local_timezone, local_timezone), porcelain.get_user_timezones()
  990. )
  991. class CleanTests(PorcelainTestCase):
  992. def put_files(self, tracked, ignored, untracked, empty_dirs) -> None:
  993. """Put the described files in the wd."""
  994. all_files = tracked | ignored | untracked
  995. for file_path in all_files:
  996. abs_path = os.path.join(self.repo.path, file_path)
  997. # File may need to be written in a dir that doesn't exist yet, so
  998. # create the parent dir(s) as necessary
  999. parent_dir = os.path.dirname(abs_path)
  1000. try:
  1001. os.makedirs(parent_dir)
  1002. except FileExistsError:
  1003. pass
  1004. with open(abs_path, "w") as f:
  1005. f.write("")
  1006. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1007. f.writelines(ignored)
  1008. for dir_path in empty_dirs:
  1009. os.mkdir(os.path.join(self.repo.path, "empty_dir"))
  1010. files_to_add = [os.path.join(self.repo.path, t) for t in tracked]
  1011. porcelain.add(repo=self.repo.path, paths=files_to_add)
  1012. porcelain.commit(repo=self.repo.path, message="init commit")
  1013. def assert_wd(self, expected_paths) -> None:
  1014. """Assert paths of files and dirs in wd are same as expected_paths."""
  1015. control_dir_rel = os.path.relpath(self.repo._controldir, self.repo.path)
  1016. # normalize paths to simplify comparison across platforms
  1017. found_paths = {
  1018. os.path.normpath(p)
  1019. for p in flat_walk_dir(self.repo.path)
  1020. if not p.split(os.sep)[0] == control_dir_rel
  1021. }
  1022. norm_expected_paths = {os.path.normpath(p) for p in expected_paths}
  1023. self.assertEqual(found_paths, norm_expected_paths)
  1024. def test_from_root(self) -> None:
  1025. self.put_files(
  1026. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  1027. ignored={"ignored_file"},
  1028. untracked={
  1029. "untracked_file",
  1030. "tracked_dir/untracked_dir/untracked_file",
  1031. "untracked_dir/untracked_dir/untracked_file",
  1032. },
  1033. empty_dirs={"empty_dir"},
  1034. )
  1035. porcelain.clean(repo=self.repo.path, target_dir=self.repo.path)
  1036. self.assert_wd(
  1037. {
  1038. "tracked_file",
  1039. "tracked_dir/tracked_file",
  1040. ".gitignore",
  1041. "ignored_file",
  1042. "tracked_dir",
  1043. }
  1044. )
  1045. def test_from_subdir(self) -> None:
  1046. self.put_files(
  1047. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  1048. ignored={"ignored_file"},
  1049. untracked={
  1050. "untracked_file",
  1051. "tracked_dir/untracked_dir/untracked_file",
  1052. "untracked_dir/untracked_dir/untracked_file",
  1053. },
  1054. empty_dirs={"empty_dir"},
  1055. )
  1056. porcelain.clean(
  1057. repo=self.repo,
  1058. target_dir=os.path.join(self.repo.path, "untracked_dir"),
  1059. )
  1060. self.assert_wd(
  1061. {
  1062. "tracked_file",
  1063. "tracked_dir/tracked_file",
  1064. ".gitignore",
  1065. "ignored_file",
  1066. "untracked_file",
  1067. "tracked_dir/untracked_dir/untracked_file",
  1068. "empty_dir",
  1069. "untracked_dir",
  1070. "tracked_dir",
  1071. "tracked_dir/untracked_dir",
  1072. }
  1073. )
  1074. class CloneTests(PorcelainTestCase):
  1075. def test_simple_local(self) -> None:
  1076. f1_1 = make_object(Blob, data=b"f1")
  1077. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1078. trees = {
  1079. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1080. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1081. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1082. }
  1083. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1084. self.repo.refs[b"refs/heads/master"] = c3.id
  1085. self.repo.refs[b"refs/tags/foo"] = c3.id
  1086. target_path = tempfile.mkdtemp()
  1087. errstream = BytesIO()
  1088. self.addCleanup(shutil.rmtree, target_path)
  1089. r = porcelain.clone(
  1090. self.repo.path, target_path, checkout=False, errstream=errstream
  1091. )
  1092. self.addCleanup(r.close)
  1093. self.assertEqual(r.path, target_path)
  1094. target_repo = Repo(target_path)
  1095. self.addCleanup(target_repo.close)
  1096. self.assertEqual(0, len(target_repo.open_index()))
  1097. self.assertEqual(c3.id, target_repo.refs[b"refs/tags/foo"])
  1098. self.assertNotIn(b"f1", os.listdir(target_path))
  1099. self.assertNotIn(b"f2", os.listdir(target_path))
  1100. c = r.get_config()
  1101. encoded_path = self.repo.path
  1102. if not isinstance(encoded_path, bytes):
  1103. encoded_path_bytes = encoded_path.encode("utf-8")
  1104. else:
  1105. encoded_path_bytes = encoded_path
  1106. self.assertEqual(encoded_path_bytes, c.get((b"remote", b"origin"), b"url"))
  1107. self.assertEqual(
  1108. b"+refs/heads/*:refs/remotes/origin/*",
  1109. c.get((b"remote", b"origin"), b"fetch"),
  1110. )
  1111. def test_simple_local_with_checkout(self) -> None:
  1112. f1_1 = make_object(Blob, data=b"f1")
  1113. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1114. trees = {
  1115. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1116. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1117. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1118. }
  1119. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1120. self.repo.refs[b"refs/heads/master"] = c3.id
  1121. target_path = tempfile.mkdtemp()
  1122. errstream = BytesIO()
  1123. self.addCleanup(shutil.rmtree, target_path)
  1124. with porcelain.clone(
  1125. self.repo.path, target_path, checkout=True, errstream=errstream
  1126. ) as r:
  1127. self.assertEqual(r.path, target_path)
  1128. with Repo(target_path) as r:
  1129. self.assertEqual(r.head(), c3.id)
  1130. self.assertIn("f1", os.listdir(target_path))
  1131. self.assertIn("f2", os.listdir(target_path))
  1132. def test_bare_local_with_checkout(self) -> None:
  1133. f1_1 = make_object(Blob, data=b"f1")
  1134. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1135. trees = {
  1136. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1137. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1138. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1139. }
  1140. _c1, _c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1141. self.repo.refs[b"refs/heads/master"] = c3.id
  1142. target_path = tempfile.mkdtemp()
  1143. errstream = BytesIO()
  1144. self.addCleanup(shutil.rmtree, target_path)
  1145. with porcelain.clone(
  1146. self.repo.path, target_path, bare=True, errstream=errstream
  1147. ) as r:
  1148. self.assertEqual(r.path, target_path)
  1149. with Repo(target_path) as r:
  1150. r.head()
  1151. self.assertRaises(NoIndexPresent, r.open_index)
  1152. self.assertNotIn(b"f1", os.listdir(target_path))
  1153. self.assertNotIn(b"f2", os.listdir(target_path))
  1154. def test_no_checkout_with_bare(self) -> None:
  1155. f1_1 = make_object(Blob, data=b"f1")
  1156. commit_spec = [[1]]
  1157. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1158. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1159. self.repo.refs[b"refs/heads/master"] = c1.id
  1160. self.repo.refs[b"HEAD"] = c1.id
  1161. target_path = tempfile.mkdtemp()
  1162. errstream = BytesIO()
  1163. self.addCleanup(shutil.rmtree, target_path)
  1164. self.assertRaises(
  1165. porcelain.Error,
  1166. porcelain.clone,
  1167. self.repo.path,
  1168. target_path,
  1169. checkout=True,
  1170. bare=True,
  1171. errstream=errstream,
  1172. )
  1173. def test_no_head_no_checkout(self) -> None:
  1174. f1_1 = make_object(Blob, data=b"f1")
  1175. commit_spec = [[1]]
  1176. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1177. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1178. self.repo.refs[b"refs/heads/master"] = c1.id
  1179. target_path = tempfile.mkdtemp()
  1180. self.addCleanup(shutil.rmtree, target_path)
  1181. errstream = BytesIO()
  1182. r = porcelain.clone(
  1183. self.repo.path, target_path, checkout=True, errstream=errstream
  1184. )
  1185. r.close()
  1186. def test_no_head_no_checkout_outstream_errstream_autofallback(self) -> None:
  1187. f1_1 = make_object(Blob, data=b"f1")
  1188. commit_spec = [[1]]
  1189. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1190. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1191. self.repo.refs[b"refs/heads/master"] = c1.id
  1192. target_path = tempfile.mkdtemp()
  1193. self.addCleanup(shutil.rmtree, target_path)
  1194. errstream = porcelain.NoneStream()
  1195. r = porcelain.clone(
  1196. self.repo.path, target_path, checkout=True, errstream=errstream
  1197. )
  1198. r.close()
  1199. def test_source_broken(self) -> None:
  1200. with tempfile.TemporaryDirectory() as parent:
  1201. target_path = os.path.join(parent, "target")
  1202. self.assertRaises(
  1203. Exception, porcelain.clone, "/nonexistent/repo", target_path
  1204. )
  1205. self.assertFalse(os.path.exists(target_path))
  1206. def test_fetch_symref(self) -> None:
  1207. f1_1 = make_object(Blob, data=b"f1")
  1208. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1209. [c1] = build_commit_graph(self.repo.object_store, [[1]], trees)
  1210. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/else")
  1211. self.repo.refs[b"refs/heads/else"] = c1.id
  1212. target_path = tempfile.mkdtemp()
  1213. errstream = BytesIO()
  1214. self.addCleanup(shutil.rmtree, target_path)
  1215. r = porcelain.clone(
  1216. self.repo.path, target_path, checkout=False, errstream=errstream
  1217. )
  1218. self.addCleanup(r.close)
  1219. self.assertEqual(r.path, target_path)
  1220. target_repo = Repo(target_path)
  1221. self.addCleanup(target_repo.close)
  1222. self.assertEqual(0, len(target_repo.open_index()))
  1223. self.assertEqual(c1.id, target_repo.refs[b"refs/heads/else"])
  1224. self.assertEqual(c1.id, target_repo.refs[b"HEAD"])
  1225. self.assertEqual(
  1226. {
  1227. b"HEAD": b"refs/heads/else",
  1228. b"refs/remotes/origin/HEAD": b"refs/remotes/origin/else",
  1229. },
  1230. target_repo.refs.get_symrefs(),
  1231. )
  1232. def test_detached_head(self) -> None:
  1233. f1_1 = make_object(Blob, data=b"f1")
  1234. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1235. trees = {
  1236. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1237. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1238. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1239. }
  1240. _c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1241. self.repo.refs[b"refs/heads/master"] = c2.id
  1242. self.repo.refs.remove_if_equals(b"HEAD", None)
  1243. self.repo.refs[b"HEAD"] = c3.id
  1244. target_path = tempfile.mkdtemp()
  1245. self.addCleanup(shutil.rmtree, target_path)
  1246. errstream = porcelain.NoneStream()
  1247. with porcelain.clone(
  1248. self.repo.path, target_path, checkout=True, errstream=errstream
  1249. ) as r:
  1250. self.assertEqual(c3.id, r.refs[b"HEAD"])
  1251. def test_clone_pathlib(self) -> None:
  1252. from pathlib import Path
  1253. f1_1 = make_object(Blob, data=b"f1")
  1254. commit_spec = [[1]]
  1255. trees = {1: [(b"f1", f1_1)]}
  1256. c1 = build_commit_graph(self.repo.object_store, commit_spec, trees)[0]
  1257. self.repo.refs[b"refs/heads/master"] = c1.id
  1258. target_dir = tempfile.mkdtemp()
  1259. self.addCleanup(shutil.rmtree, target_dir)
  1260. target_path = Path(target_dir) / "clone_repo"
  1261. errstream = BytesIO()
  1262. r = porcelain.clone(
  1263. self.repo.path, target_path, checkout=False, errstream=errstream
  1264. )
  1265. self.addCleanup(r.close)
  1266. self.assertEqual(r.path, str(target_path))
  1267. self.assertTrue(os.path.exists(str(target_path)))
  1268. def test_clone_with_recurse_submodules(self) -> None:
  1269. # Create a submodule repository
  1270. sub_repo_path = tempfile.mkdtemp()
  1271. self.addCleanup(shutil.rmtree, sub_repo_path)
  1272. sub_repo = Repo.init(sub_repo_path)
  1273. self.addCleanup(sub_repo.close)
  1274. # Add a file to the submodule repo
  1275. sub_file = os.path.join(sub_repo_path, "subfile.txt")
  1276. with open(sub_file, "w") as f:
  1277. f.write("submodule content")
  1278. porcelain.add(sub_repo, paths=[sub_file])
  1279. sub_commit = porcelain.commit(
  1280. sub_repo,
  1281. message=b"Initial submodule commit",
  1282. author=b"Test Author <test@example.com>",
  1283. committer=b"Test Committer <test@example.com>",
  1284. )
  1285. # Create main repository with submodule
  1286. main_file = os.path.join(self.repo.path, "main.txt")
  1287. with open(main_file, "w") as f:
  1288. f.write("main content")
  1289. porcelain.add(self.repo, paths=[main_file])
  1290. porcelain.submodule_add(self.repo, sub_repo_path, "sub")
  1291. # Manually add the submodule to the index since submodule_add doesn't do it
  1292. # when the repository is local (to maintain backward compatibility)
  1293. from dulwich.index import IndexEntry
  1294. from dulwich.objects import S_IFGITLINK
  1295. index = self.repo.open_index()
  1296. index[b"sub"] = IndexEntry(
  1297. ctime=0,
  1298. mtime=0,
  1299. dev=0,
  1300. ino=0,
  1301. mode=S_IFGITLINK,
  1302. uid=0,
  1303. gid=0,
  1304. size=0,
  1305. sha=sub_commit,
  1306. flags=0,
  1307. )
  1308. index.write()
  1309. porcelain.add(self.repo, paths=[".gitmodules"])
  1310. porcelain.commit(
  1311. self.repo,
  1312. message=b"Add submodule",
  1313. author=b"Test Author <test@example.com>",
  1314. committer=b"Test Committer <test@example.com>",
  1315. )
  1316. # Clone with recurse_submodules
  1317. target_path = tempfile.mkdtemp()
  1318. self.addCleanup(shutil.rmtree, target_path)
  1319. cloned = porcelain.clone(
  1320. self.repo.path,
  1321. target_path,
  1322. recurse_submodules=True,
  1323. )
  1324. self.addCleanup(cloned.close)
  1325. # Check main file exists
  1326. cloned_main = os.path.join(target_path, "main.txt")
  1327. self.assertTrue(os.path.exists(cloned_main))
  1328. with open(cloned_main) as f:
  1329. self.assertEqual(f.read(), "main content")
  1330. # Check submodule file exists
  1331. cloned_sub_file = os.path.join(target_path, "sub", "subfile.txt")
  1332. self.assertTrue(os.path.exists(cloned_sub_file))
  1333. with open(cloned_sub_file) as f:
  1334. self.assertEqual(f.read(), "submodule content")
  1335. def test_clone_with_refspec_kwarg(self) -> None:
  1336. """Test that clone accepts refspec as a kwarg without TypeError.
  1337. This reproduces a bug where passing refspec as a kwarg to clone()
  1338. would cause a TypeError because it was being passed to
  1339. get_transport_and_path() which doesn't accept that parameter.
  1340. """
  1341. f1_1 = make_object(Blob, data=b"f1")
  1342. commit_spec = [[1]]
  1343. trees = {1: [(b"f1", f1_1)]}
  1344. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1345. self.repo.refs[b"refs/heads/master"] = c1.id
  1346. target_path = tempfile.mkdtemp()
  1347. errstream = BytesIO()
  1348. self.addCleanup(shutil.rmtree, target_path)
  1349. # This should not raise TypeError
  1350. r = porcelain.clone(
  1351. self.repo.path,
  1352. target_path,
  1353. checkout=False,
  1354. errstream=errstream,
  1355. refspec="refs/heads/master",
  1356. )
  1357. self.addCleanup(r.close)
  1358. self.assertEqual(r.path, target_path)
  1359. class InitTests(TestCase):
  1360. def test_non_bare(self) -> None:
  1361. repo_dir = tempfile.mkdtemp()
  1362. self.addCleanup(shutil.rmtree, repo_dir)
  1363. porcelain.init(repo_dir)
  1364. def test_bare(self) -> None:
  1365. repo_dir = tempfile.mkdtemp()
  1366. self.addCleanup(shutil.rmtree, repo_dir)
  1367. porcelain.init(repo_dir, bare=True)
  1368. def test_init_pathlib(self) -> None:
  1369. from pathlib import Path
  1370. repo_dir = tempfile.mkdtemp()
  1371. self.addCleanup(shutil.rmtree, repo_dir)
  1372. repo_path = Path(repo_dir)
  1373. # Test non-bare repo with pathlib
  1374. repo = porcelain.init(repo_path)
  1375. self.assertTrue(os.path.exists(os.path.join(repo_dir, ".git")))
  1376. repo.close()
  1377. def test_init_bare_pathlib(self) -> None:
  1378. from pathlib import Path
  1379. repo_dir = tempfile.mkdtemp()
  1380. self.addCleanup(shutil.rmtree, repo_dir)
  1381. repo_path = Path(repo_dir)
  1382. # Test bare repo with pathlib
  1383. repo = porcelain.init(repo_path, bare=True)
  1384. self.assertTrue(os.path.exists(os.path.join(repo_dir, "refs")))
  1385. repo.close()
  1386. class AddTests(PorcelainTestCase):
  1387. def test_add_default_paths(self) -> None:
  1388. # create a file for initial commit
  1389. fullpath = os.path.join(self.repo.path, "blah")
  1390. with open(fullpath, "w") as f:
  1391. f.write("\n")
  1392. porcelain.add(repo=self.repo.path, paths=[fullpath])
  1393. porcelain.commit(
  1394. repo=self.repo.path,
  1395. message=b"test",
  1396. author=b"test <email>",
  1397. committer=b"test <email>",
  1398. )
  1399. # Add a second test file and a file in a directory
  1400. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1401. f.write("\n")
  1402. os.mkdir(os.path.join(self.repo.path, "adir"))
  1403. with open(os.path.join(self.repo.path, "adir", "afile"), "w") as f:
  1404. f.write("\n")
  1405. cwd = os.getcwd()
  1406. self.addCleanup(os.chdir, cwd)
  1407. os.chdir(self.repo.path)
  1408. self.assertEqual({"foo", "blah", "adir", ".git"}, set(os.listdir(".")))
  1409. added, ignored = porcelain.add(self.repo.path)
  1410. # Normalize paths to use forward slashes for comparison
  1411. added_normalized = [path.replace(os.sep, "/") for path in added]
  1412. self.assertEqual(
  1413. (added_normalized, ignored),
  1414. (["foo", "adir/afile"], set()),
  1415. )
  1416. # Check that foo was added and nothing in .git was modified
  1417. index = self.repo.open_index()
  1418. self.assertEqual(sorted(index), [b"adir/afile", b"blah", b"foo"])
  1419. def test_add_default_paths_subdir(self) -> None:
  1420. os.mkdir(os.path.join(self.repo.path, "foo"))
  1421. with open(os.path.join(self.repo.path, "blah"), "w") as f:
  1422. f.write("\n")
  1423. with open(os.path.join(self.repo.path, "foo", "blie"), "w") as f:
  1424. f.write("\n")
  1425. cwd = os.getcwd()
  1426. self.addCleanup(os.chdir, cwd)
  1427. os.chdir(os.path.join(self.repo.path, "foo"))
  1428. porcelain.add(repo=self.repo.path)
  1429. porcelain.commit(
  1430. repo=self.repo.path,
  1431. message=b"test",
  1432. author=b"test <email>",
  1433. committer=b"test <email>",
  1434. )
  1435. index = self.repo.open_index()
  1436. # After fix: add() with no paths should behave like git add -A (add everything)
  1437. self.assertEqual(sorted(index), [b"blah", b"foo/blie"])
  1438. def test_add_file(self) -> None:
  1439. fullpath = os.path.join(self.repo.path, "foo")
  1440. with open(fullpath, "w") as f:
  1441. f.write("BAR")
  1442. porcelain.add(self.repo.path, paths=[fullpath])
  1443. self.assertIn(b"foo", self.repo.open_index())
  1444. def test_add_ignored(self) -> None:
  1445. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1446. f.write("foo\nsubdir/")
  1447. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1448. f.write("BAR")
  1449. with open(os.path.join(self.repo.path, "bar"), "w") as f:
  1450. f.write("BAR")
  1451. os.mkdir(os.path.join(self.repo.path, "subdir"))
  1452. with open(os.path.join(self.repo.path, "subdir", "baz"), "w") as f:
  1453. f.write("BAZ")
  1454. (added, ignored) = porcelain.add(
  1455. self.repo.path,
  1456. paths=[
  1457. os.path.join(self.repo.path, "foo"),
  1458. os.path.join(self.repo.path, "bar"),
  1459. os.path.join(self.repo.path, "subdir"),
  1460. ],
  1461. )
  1462. self.assertIn(b"bar", self.repo.open_index())
  1463. self.assertEqual({"bar"}, set(added))
  1464. self.assertEqual({"foo", "subdir/"}, ignored)
  1465. def test_add_from_ignored_directory(self) -> None:
  1466. # Test for issue #550 - adding files when cwd is in ignored directory
  1467. # Create .gitignore that ignores build/
  1468. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1469. f.write("build/\n")
  1470. # Create ignored directory
  1471. build_dir = os.path.join(self.repo.path, "build")
  1472. os.mkdir(build_dir)
  1473. # Create a file in the repo (not in ignored directory)
  1474. src_file = os.path.join(self.repo.path, "source.py")
  1475. with open(src_file, "w") as f:
  1476. f.write("print('hello')\n")
  1477. # Save current directory and change to ignored directory
  1478. original_cwd = os.getcwd()
  1479. try:
  1480. os.chdir(build_dir)
  1481. # Add file using absolute path from within ignored directory
  1482. (added, _ignored) = porcelain.add(self.repo.path, paths=[src_file])
  1483. self.assertIn(b"source.py", self.repo.open_index())
  1484. self.assertEqual({"source.py"}, set(added))
  1485. finally:
  1486. os.chdir(original_cwd)
  1487. def test_add_file_absolute_path(self) -> None:
  1488. # Absolute paths are (not yet) supported
  1489. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1490. f.write("BAR")
  1491. porcelain.add(self.repo, paths=[os.path.join(self.repo.path, "foo")])
  1492. self.assertIn(b"foo", self.repo.open_index())
  1493. def test_add_not_in_repo(self) -> None:
  1494. with open(os.path.join(self.test_dir, "foo"), "w") as f:
  1495. f.write("BAR")
  1496. self.assertRaises(
  1497. ValueError,
  1498. porcelain.add,
  1499. self.repo,
  1500. paths=[os.path.join(self.test_dir, "foo")],
  1501. )
  1502. self.assertRaises(
  1503. (ValueError, FileNotFoundError),
  1504. porcelain.add,
  1505. self.repo,
  1506. paths=["../foo"],
  1507. )
  1508. self.assertEqual([], list(self.repo.open_index()))
  1509. def test_add_file_clrf_conversion(self) -> None:
  1510. from dulwich.index import IndexEntry
  1511. # Set the right configuration to the repo
  1512. c = self.repo.get_config()
  1513. c.set("core", "autocrlf", "input")
  1514. c.write_to_path()
  1515. # Add a file with CRLF line-ending
  1516. fullpath = os.path.join(self.repo.path, "foo")
  1517. with open(fullpath, "wb") as f:
  1518. f.write(b"line1\r\nline2")
  1519. porcelain.add(self.repo.path, paths=[fullpath])
  1520. # The line-endings should have been converted to LF
  1521. index = self.repo.open_index()
  1522. self.assertIn(b"foo", index)
  1523. entry = index[b"foo"]
  1524. assert isinstance(entry, IndexEntry)
  1525. blob = self.repo[entry.sha]
  1526. self.assertEqual(blob.data, b"line1\nline2")
  1527. def test_add_symlink_outside_repo(self) -> None:
  1528. """Test adding a symlink that points outside the repository."""
  1529. # Create a symlink pointing outside the repository
  1530. symlink_path = os.path.join(self.repo.path, "symlink_to_nowhere")
  1531. os.symlink("/nonexistent/path", symlink_path)
  1532. # Adding the symlink should succeed (matching Git's behavior)
  1533. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1534. # Should successfully add the symlink
  1535. self.assertIn("symlink_to_nowhere", added)
  1536. self.assertEqual(len(ignored), 0)
  1537. # Verify symlink is actually staged
  1538. index = self.repo.open_index()
  1539. self.assertIn(b"symlink_to_nowhere", index)
  1540. def test_add_symlink_to_file_inside_repo(self) -> None:
  1541. """Test adding a symlink that points to a file inside the repository."""
  1542. # Create a regular file
  1543. target_file = os.path.join(self.repo.path, "target.txt")
  1544. with open(target_file, "w") as f:
  1545. f.write("target content")
  1546. # Create a symlink to the file
  1547. symlink_path = os.path.join(self.repo.path, "link_to_target")
  1548. os.symlink("target.txt", symlink_path)
  1549. # Add both the target and the symlink
  1550. added, ignored = porcelain.add(
  1551. self.repo.path, paths=[target_file, symlink_path]
  1552. )
  1553. # Both should be added successfully
  1554. self.assertIn("target.txt", added)
  1555. self.assertIn("link_to_target", added)
  1556. self.assertEqual(len(ignored), 0)
  1557. # Verify both are in the index
  1558. index = self.repo.open_index()
  1559. self.assertIn(b"target.txt", index)
  1560. self.assertIn(b"link_to_target", index)
  1561. def test_add_symlink_to_directory_inside_repo(self) -> None:
  1562. """Test adding a symlink that points to a directory inside the repository."""
  1563. # Create a directory with some files
  1564. target_dir = os.path.join(self.repo.path, "target_dir")
  1565. os.mkdir(target_dir)
  1566. with open(os.path.join(target_dir, "file1.txt"), "w") as f:
  1567. f.write("content1")
  1568. with open(os.path.join(target_dir, "file2.txt"), "w") as f:
  1569. f.write("content2")
  1570. # Create a symlink to the directory
  1571. symlink_path = os.path.join(self.repo.path, "link_to_dir")
  1572. os.symlink("target_dir", symlink_path)
  1573. # Add the symlink
  1574. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1575. # When adding a symlink to a directory, it follows the symlink and adds contents
  1576. self.assertEqual(len(added), 2)
  1577. self.assertIn("link_to_dir/file1.txt", added)
  1578. self.assertIn("link_to_dir/file2.txt", added)
  1579. self.assertEqual(len(ignored), 0)
  1580. # Verify files are added through the symlink path
  1581. index = self.repo.open_index()
  1582. self.assertIn(b"link_to_dir/file1.txt", index)
  1583. self.assertIn(b"link_to_dir/file2.txt", index)
  1584. # The original target directory files are not added
  1585. self.assertNotIn(b"target_dir/file1.txt", index)
  1586. self.assertNotIn(b"target_dir/file2.txt", index)
  1587. def test_add_symlink_chain(self) -> None:
  1588. """Test adding a chain of symlinks (symlink to symlink)."""
  1589. # Create a regular file
  1590. target_file = os.path.join(self.repo.path, "original.txt")
  1591. with open(target_file, "w") as f:
  1592. f.write("original content")
  1593. # Create first symlink
  1594. first_link = os.path.join(self.repo.path, "link1")
  1595. os.symlink("original.txt", first_link)
  1596. # Create second symlink pointing to first
  1597. second_link = os.path.join(self.repo.path, "link2")
  1598. os.symlink("link1", second_link)
  1599. # Add all files
  1600. added, _ignored = porcelain.add(
  1601. self.repo.path, paths=[target_file, first_link, second_link]
  1602. )
  1603. # All should be added
  1604. self.assertEqual(len(added), 3)
  1605. self.assertIn("original.txt", added)
  1606. self.assertIn("link1", added)
  1607. self.assertIn("link2", added)
  1608. # Verify all are in the index
  1609. index = self.repo.open_index()
  1610. self.assertIn(b"original.txt", index)
  1611. self.assertIn(b"link1", index)
  1612. self.assertIn(b"link2", index)
  1613. def test_add_broken_symlink(self) -> None:
  1614. """Test adding a broken symlink (points to non-existent target)."""
  1615. # Create a symlink to a non-existent file
  1616. broken_link = os.path.join(self.repo.path, "broken_link")
  1617. os.symlink("does_not_exist.txt", broken_link)
  1618. # Add the broken symlink
  1619. added, ignored = porcelain.add(self.repo.path, paths=[broken_link])
  1620. # Should be added successfully (Git tracks the symlink, not its target)
  1621. self.assertIn("broken_link", added)
  1622. self.assertEqual(len(ignored), 0)
  1623. # Verify it's in the index
  1624. index = self.repo.open_index()
  1625. self.assertIn(b"broken_link", index)
  1626. def test_add_symlink_relative_outside_repo(self) -> None:
  1627. """Test adding a symlink that uses '..' to point outside the repository."""
  1628. # Create a file outside the repo
  1629. outside_file = os.path.join(self.test_dir, "outside.txt")
  1630. with open(outside_file, "w") as f:
  1631. f.write("outside content")
  1632. # Create a symlink using relative path to go outside
  1633. symlink_path = os.path.join(self.repo.path, "link_outside")
  1634. os.symlink("../outside.txt", symlink_path)
  1635. # Add the symlink
  1636. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1637. # Should be added successfully
  1638. self.assertIn("link_outside", added)
  1639. self.assertEqual(len(ignored), 0)
  1640. # Verify it's in the index
  1641. index = self.repo.open_index()
  1642. self.assertIn(b"link_outside", index)
  1643. def test_add_symlink_absolute_to_system(self) -> None:
  1644. """Test adding a symlink with absolute path to system directory."""
  1645. # Create a symlink to a system directory
  1646. symlink_path = os.path.join(self.repo.path, "link_to_tmp")
  1647. if os.name == "nt":
  1648. # On Windows, use a system directory like TEMP
  1649. symlink_target = os.environ["TEMP"]
  1650. else:
  1651. # On Unix-like systems, use /tmp
  1652. symlink_target = os.environ.get("TMPDIR", "/tmp")
  1653. os.symlink(symlink_target, symlink_path)
  1654. # Adding a symlink to a directory outside the repo should raise ValueError
  1655. with self.assertRaises(ValueError) as cm:
  1656. porcelain.add(self.repo.path, paths=[symlink_path])
  1657. # Check that the error indicates the path is outside the repository
  1658. self.assertIn("is not in the subpath of", str(cm.exception))
  1659. def test_add_file_through_symlink(self) -> None:
  1660. """Test adding a file through a symlinked directory."""
  1661. # Create a directory with a file
  1662. real_dir = os.path.join(self.repo.path, "real_dir")
  1663. os.mkdir(real_dir)
  1664. real_file = os.path.join(real_dir, "file.txt")
  1665. with open(real_file, "w") as f:
  1666. f.write("content")
  1667. # Create a symlink to the directory
  1668. link_dir = os.path.join(self.repo.path, "link_dir")
  1669. os.symlink("real_dir", link_dir)
  1670. # Try to add the file through the symlink path
  1671. symlink_file_path = os.path.join(link_dir, "file.txt")
  1672. # This should add the real file, not create a new entry
  1673. added, _ignored = porcelain.add(self.repo.path, paths=[symlink_file_path])
  1674. # The real file should be added
  1675. self.assertIn("real_dir/file.txt", added)
  1676. self.assertEqual(len(added), 1)
  1677. # Verify correct path in index
  1678. index = self.repo.open_index()
  1679. self.assertIn(b"real_dir/file.txt", index)
  1680. # Should not create a separate entry for the symlink path
  1681. self.assertNotIn(b"link_dir/file.txt", index)
  1682. def test_add_repo_path(self) -> None:
  1683. """Test adding the repository path itself should add all untracked files."""
  1684. # Create some untracked files
  1685. with open(os.path.join(self.repo.path, "file1.txt"), "w") as f:
  1686. f.write("content1")
  1687. with open(os.path.join(self.repo.path, "file2.txt"), "w") as f:
  1688. f.write("content2")
  1689. # Add the repository path itself
  1690. added, _ignored = porcelain.add(self.repo.path, paths=[self.repo.path])
  1691. # Should add all untracked files, not stage './'
  1692. self.assertIn("file1.txt", added)
  1693. self.assertIn("file2.txt", added)
  1694. self.assertNotIn("./", added)
  1695. # Verify files are actually staged
  1696. index = self.repo.open_index()
  1697. self.assertIn(b"file1.txt", index)
  1698. self.assertIn(b"file2.txt", index)
  1699. def test_add_directory_contents(self) -> None:
  1700. """Test adding a directory adds all files within it."""
  1701. # Create a subdirectory with multiple files
  1702. subdir = os.path.join(self.repo.path, "subdir")
  1703. os.mkdir(subdir)
  1704. with open(os.path.join(subdir, "file1.txt"), "w") as f:
  1705. f.write("content1")
  1706. with open(os.path.join(subdir, "file2.txt"), "w") as f:
  1707. f.write("content2")
  1708. with open(os.path.join(subdir, "file3.txt"), "w") as f:
  1709. f.write("content3")
  1710. # Add the directory
  1711. added, _ignored = porcelain.add(self.repo.path, paths=["subdir"])
  1712. # Should add all files in the directory
  1713. self.assertEqual(len(added), 3)
  1714. # Normalize paths to use forward slashes for comparison
  1715. added_normalized = [path.replace(os.sep, "/") for path in added]
  1716. self.assertIn("subdir/file1.txt", added_normalized)
  1717. self.assertIn("subdir/file2.txt", added_normalized)
  1718. self.assertIn("subdir/file3.txt", added_normalized)
  1719. # Verify files are actually staged
  1720. index = self.repo.open_index()
  1721. self.assertIn(b"subdir/file1.txt", index)
  1722. self.assertIn(b"subdir/file2.txt", index)
  1723. self.assertIn(b"subdir/file3.txt", index)
  1724. def test_add_nested_directories(self) -> None:
  1725. """Test adding a directory with nested subdirectories."""
  1726. # Create nested directory structure
  1727. dir1 = os.path.join(self.repo.path, "dir1")
  1728. dir2 = os.path.join(dir1, "dir2")
  1729. dir3 = os.path.join(dir2, "dir3")
  1730. os.makedirs(dir3)
  1731. # Add files at each level
  1732. with open(os.path.join(dir1, "file1.txt"), "w") as f:
  1733. f.write("level1")
  1734. with open(os.path.join(dir2, "file2.txt"), "w") as f:
  1735. f.write("level2")
  1736. with open(os.path.join(dir3, "file3.txt"), "w") as f:
  1737. f.write("level3")
  1738. # Add the top-level directory
  1739. added, _ignored = porcelain.add(self.repo.path, paths=["dir1"])
  1740. # Should add all files recursively
  1741. self.assertEqual(len(added), 3)
  1742. # Normalize paths to use forward slashes for comparison
  1743. added_normalized = [path.replace(os.sep, "/") for path in added]
  1744. self.assertIn("dir1/file1.txt", added_normalized)
  1745. self.assertIn("dir1/dir2/file2.txt", added_normalized)
  1746. self.assertIn("dir1/dir2/dir3/file3.txt", added_normalized)
  1747. # Verify files are actually staged
  1748. index = self.repo.open_index()
  1749. self.assertIn(b"dir1/file1.txt", index)
  1750. self.assertIn(b"dir1/dir2/file2.txt", index)
  1751. self.assertIn(b"dir1/dir2/dir3/file3.txt", index)
  1752. def test_add_directory_with_tracked_files(self) -> None:
  1753. """Test adding a directory with some files already tracked."""
  1754. # Create a subdirectory with files
  1755. subdir = os.path.join(self.repo.path, "mixed")
  1756. os.mkdir(subdir)
  1757. # Create and commit one file
  1758. tracked_file = os.path.join(subdir, "tracked.txt")
  1759. with open(tracked_file, "w") as f:
  1760. f.write("already tracked")
  1761. porcelain.add(self.repo.path, paths=[tracked_file])
  1762. porcelain.commit(
  1763. repo=self.repo.path,
  1764. message=b"Add tracked file",
  1765. author=b"test <email>",
  1766. committer=b"test <email>",
  1767. )
  1768. # Add more untracked files
  1769. with open(os.path.join(subdir, "untracked1.txt"), "w") as f:
  1770. f.write("new file 1")
  1771. with open(os.path.join(subdir, "untracked2.txt"), "w") as f:
  1772. f.write("new file 2")
  1773. # Add the directory
  1774. added, _ignored = porcelain.add(self.repo.path, paths=["mixed"])
  1775. # Should only add the untracked files
  1776. self.assertEqual(len(added), 2)
  1777. # Normalize paths to use forward slashes for comparison
  1778. added_normalized = [path.replace(os.sep, "/") for path in added]
  1779. self.assertIn("mixed/untracked1.txt", added_normalized)
  1780. self.assertIn("mixed/untracked2.txt", added_normalized)
  1781. self.assertNotIn("mixed/tracked.txt", added)
  1782. # Verify the index contains all files
  1783. index = self.repo.open_index()
  1784. self.assertIn(b"mixed/tracked.txt", index)
  1785. self.assertIn(b"mixed/untracked1.txt", index)
  1786. self.assertIn(b"mixed/untracked2.txt", index)
  1787. def test_add_directory_with_gitignore(self) -> None:
  1788. """Test adding a directory respects .gitignore patterns."""
  1789. # Create .gitignore
  1790. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1791. f.write("*.log\n*.tmp\nbuild/\n")
  1792. # Create directory with mixed files
  1793. testdir = os.path.join(self.repo.path, "testdir")
  1794. os.mkdir(testdir)
  1795. # Create various files
  1796. with open(os.path.join(testdir, "important.txt"), "w") as f:
  1797. f.write("keep this")
  1798. with open(os.path.join(testdir, "debug.log"), "w") as f:
  1799. f.write("ignore this")
  1800. with open(os.path.join(testdir, "temp.tmp"), "w") as f:
  1801. f.write("ignore this too")
  1802. with open(os.path.join(testdir, "readme.md"), "w") as f:
  1803. f.write("keep this too")
  1804. # Create a build directory that should be ignored
  1805. builddir = os.path.join(testdir, "build")
  1806. os.mkdir(builddir)
  1807. with open(os.path.join(builddir, "output.txt"), "w") as f:
  1808. f.write("ignore entire directory")
  1809. # Add the directory
  1810. added, ignored = porcelain.add(self.repo.path, paths=["testdir"])
  1811. # Should only add non-ignored files
  1812. # Normalize paths to use forward slashes for comparison
  1813. added_normalized = {path.replace(os.sep, "/") for path in added}
  1814. self.assertEqual(
  1815. added_normalized, {"testdir/important.txt", "testdir/readme.md"}
  1816. )
  1817. # Check ignored files
  1818. # Normalize paths to use forward slashes for comparison
  1819. ignored_normalized = {path.replace(os.sep, "/") for path in ignored}
  1820. self.assertIn("testdir/debug.log", ignored_normalized)
  1821. self.assertIn("testdir/temp.tmp", ignored_normalized)
  1822. self.assertIn("testdir/build/", ignored_normalized)
  1823. def test_add_multiple_directories(self) -> None:
  1824. """Test adding multiple directories in one call."""
  1825. # Create multiple directories
  1826. for dirname in ["dir1", "dir2", "dir3"]:
  1827. dirpath = os.path.join(self.repo.path, dirname)
  1828. os.mkdir(dirpath)
  1829. # Add files to each directory
  1830. for i in range(2):
  1831. with open(os.path.join(dirpath, f"file{i}.txt"), "w") as f:
  1832. f.write(f"content {dirname} {i}")
  1833. # Add all directories at once
  1834. added, _ignored = porcelain.add(self.repo.path, paths=["dir1", "dir2", "dir3"])
  1835. # Should add all files from all directories
  1836. self.assertEqual(len(added), 6)
  1837. # Normalize paths to use forward slashes for comparison
  1838. added_normalized = [path.replace(os.sep, "/") for path in added]
  1839. for dirname in ["dir1", "dir2", "dir3"]:
  1840. for i in range(2):
  1841. self.assertIn(f"{dirname}/file{i}.txt", added_normalized)
  1842. # Verify all files are staged
  1843. index = self.repo.open_index()
  1844. self.assertEqual(len(index), 6)
  1845. def test_add_default_paths_includes_modified_files(self) -> None:
  1846. """Test that add() with no paths includes both untracked and modified files."""
  1847. # Create and commit initial file
  1848. initial_file = os.path.join(self.repo.path, "existing.txt")
  1849. with open(initial_file, "w") as f:
  1850. f.write("initial content\n")
  1851. porcelain.add(repo=self.repo.path, paths=[initial_file])
  1852. porcelain.commit(
  1853. repo=self.repo.path,
  1854. message=b"initial commit",
  1855. author=b"test <email>",
  1856. committer=b"test <email>",
  1857. )
  1858. # Modify the existing file (this creates an unstaged change)
  1859. with open(initial_file, "w") as f:
  1860. f.write("modified content\n")
  1861. # Create a new untracked file
  1862. new_file = os.path.join(self.repo.path, "new.txt")
  1863. with open(new_file, "w") as f:
  1864. f.write("new file content\n")
  1865. # Call add() with no paths - should stage both modified and untracked files
  1866. added_files, ignored_files = porcelain.add(repo=self.repo.path)
  1867. # Verify both files were added
  1868. self.assertIn("existing.txt", added_files)
  1869. self.assertIn("new.txt", added_files)
  1870. self.assertEqual(len(ignored_files), 0)
  1871. # Verify both files are now staged
  1872. index = self.repo.open_index()
  1873. self.assertIn(b"existing.txt", index)
  1874. self.assertIn(b"new.txt", index)
  1875. def test_add_empty_paths_list(self) -> None:
  1876. """Test that passing paths=[] does not add any files."""
  1877. # Create an untracked file
  1878. with open(os.path.join(self.repo.path, "file.txt"), "w") as f:
  1879. f.write("content")
  1880. # Add with empty paths list
  1881. added, _ignored = porcelain.add(self.repo.path, paths=[])
  1882. # Should not add any files
  1883. self.assertEqual(len(added), 0)
  1884. class RemoveTests(PorcelainTestCase):
  1885. def test_remove_file(self) -> None:
  1886. fullpath = os.path.join(self.repo.path, "foo")
  1887. with open(fullpath, "w") as f:
  1888. f.write("BAR")
  1889. porcelain.add(self.repo.path, paths=[fullpath])
  1890. porcelain.commit(
  1891. repo=self.repo,
  1892. message=b"test",
  1893. author=b"test <email>",
  1894. committer=b"test <email>",
  1895. )
  1896. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "foo")))
  1897. cwd = os.getcwd()
  1898. self.addCleanup(os.chdir, cwd)
  1899. os.chdir(self.repo.path)
  1900. porcelain.remove(self.repo.path, paths=["foo"])
  1901. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1902. def test_remove_file_staged(self) -> None:
  1903. fullpath = os.path.join(self.repo.path, "foo")
  1904. with open(fullpath, "w") as f:
  1905. f.write("BAR")
  1906. cwd = os.getcwd()
  1907. self.addCleanup(os.chdir, cwd)
  1908. os.chdir(self.repo.path)
  1909. porcelain.add(self.repo.path, paths=[fullpath])
  1910. self.assertRaises(Exception, porcelain.rm, self.repo.path, paths=["foo"])
  1911. def test_remove_file_removed_on_disk(self) -> None:
  1912. fullpath = os.path.join(self.repo.path, "foo")
  1913. with open(fullpath, "w") as f:
  1914. f.write("BAR")
  1915. porcelain.add(self.repo.path, paths=[fullpath])
  1916. cwd = os.getcwd()
  1917. self.addCleanup(os.chdir, cwd)
  1918. os.chdir(self.repo.path)
  1919. os.remove(fullpath)
  1920. porcelain.remove(self.repo.path, paths=["foo"])
  1921. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1922. def test_remove_from_different_directory(self) -> None:
  1923. # Create a subdirectory with a file
  1924. subdir = os.path.join(self.repo.path, "mydir")
  1925. os.makedirs(subdir)
  1926. fullpath = os.path.join(subdir, "myfile")
  1927. with open(fullpath, "w") as f:
  1928. f.write("BAR")
  1929. # Add and commit the file
  1930. porcelain.add(self.repo.path, paths=[fullpath])
  1931. porcelain.commit(
  1932. repo=self.repo,
  1933. message=b"test",
  1934. author=b"test <email>",
  1935. committer=b"test <email>",
  1936. )
  1937. # Change to a different directory
  1938. cwd = os.getcwd()
  1939. tempdir = tempfile.mkdtemp()
  1940. def cleanup():
  1941. os.chdir(cwd)
  1942. shutil.rmtree(tempdir)
  1943. self.addCleanup(cleanup)
  1944. os.chdir(tempdir)
  1945. # Remove the file using relative path from repository root
  1946. porcelain.remove(self.repo.path, paths=["mydir/myfile"])
  1947. # Verify file was removed
  1948. self.assertFalse(os.path.exists(fullpath))
  1949. def test_remove_with_absolute_path(self) -> None:
  1950. # Create a file
  1951. fullpath = os.path.join(self.repo.path, "foo")
  1952. with open(fullpath, "w") as f:
  1953. f.write("BAR")
  1954. # Add and commit the file
  1955. porcelain.add(self.repo.path, paths=[fullpath])
  1956. porcelain.commit(
  1957. repo=self.repo,
  1958. message=b"test",
  1959. author=b"test <email>",
  1960. committer=b"test <email>",
  1961. )
  1962. # Change to a different directory
  1963. cwd = os.getcwd()
  1964. tempdir = tempfile.mkdtemp()
  1965. def cleanup():
  1966. os.chdir(cwd)
  1967. shutil.rmtree(tempdir)
  1968. self.addCleanup(cleanup)
  1969. os.chdir(tempdir)
  1970. # Remove the file using absolute path
  1971. porcelain.remove(self.repo.path, paths=[fullpath])
  1972. # Verify file was removed
  1973. self.assertFalse(os.path.exists(fullpath))
  1974. def test_remove_with_filter_normalization(self) -> None:
  1975. # Enable autocrlf to normalize line endings
  1976. config = self.repo.get_config()
  1977. config.set(("core",), "autocrlf", b"true")
  1978. config.write_to_path()
  1979. # Create a file with LF line endings (will be stored with LF in index)
  1980. fullpath = os.path.join(self.repo.path, "foo.txt")
  1981. with open(fullpath, "wb") as f:
  1982. f.write(b"line1\nline2\nline3")
  1983. # Add and commit the file (stored with LF in index)
  1984. porcelain.add(self.repo.path, paths=[fullpath])
  1985. porcelain.commit(
  1986. repo=self.repo,
  1987. message=b"Add file with LF",
  1988. author=b"test <email>",
  1989. committer=b"test <email>",
  1990. )
  1991. # Simulate checkout with CRLF conversion (as would happen on Windows)
  1992. with open(fullpath, "wb") as f:
  1993. f.write(b"line1\r\nline2\r\nline3")
  1994. # Verify file exists
  1995. self.assertTrue(os.path.exists(fullpath))
  1996. # Remove the file - this should not fail even though working tree has CRLF
  1997. # and index has LF (thanks to the normalization in the commit)
  1998. cwd = os.getcwd()
  1999. os.chdir(self.repo.path)
  2000. self.addCleanup(os.chdir, cwd)
  2001. porcelain.remove(self.repo.path, paths=["foo.txt"])
  2002. # Verify file was removed
  2003. self.assertFalse(os.path.exists(fullpath))
  2004. class MvTests(PorcelainTestCase):
  2005. def test_mv_file(self) -> None:
  2006. # Create a file
  2007. fullpath = os.path.join(self.repo.path, "foo")
  2008. with open(fullpath, "w") as f:
  2009. f.write("BAR")
  2010. # Add and commit the file
  2011. porcelain.add(self.repo.path, paths=[fullpath])
  2012. porcelain.commit(
  2013. repo=self.repo,
  2014. message=b"test",
  2015. author=b"test <email>",
  2016. committer=b"test <email>",
  2017. )
  2018. # Move the file
  2019. porcelain.mv(self.repo.path, "foo", "bar")
  2020. # Verify old path doesn't exist and new path does
  2021. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  2022. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "bar")))
  2023. # Verify index was updated
  2024. index = self.repo.open_index()
  2025. self.assertNotIn(b"foo", index)
  2026. self.assertIn(b"bar", index)
  2027. def test_mv_file_to_existing_directory(self) -> None:
  2028. # Create a file and a directory
  2029. fullpath = os.path.join(self.repo.path, "foo")
  2030. with open(fullpath, "w") as f:
  2031. f.write("BAR")
  2032. dirpath = os.path.join(self.repo.path, "mydir")
  2033. os.makedirs(dirpath)
  2034. # Add and commit the file
  2035. porcelain.add(self.repo.path, paths=[fullpath])
  2036. porcelain.commit(
  2037. repo=self.repo,
  2038. message=b"test",
  2039. author=b"test <email>",
  2040. committer=b"test <email>",
  2041. )
  2042. # Move the file into the directory
  2043. porcelain.mv(self.repo.path, "foo", "mydir")
  2044. # Verify file moved into directory
  2045. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  2046. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "mydir", "foo")))
  2047. # Verify index was updated
  2048. index = self.repo.open_index()
  2049. self.assertNotIn(b"foo", index)
  2050. self.assertIn(b"mydir/foo", index)
  2051. def test_mv_file_force_overwrite(self) -> None:
  2052. # Create two files
  2053. fullpath1 = os.path.join(self.repo.path, "foo")
  2054. with open(fullpath1, "w") as f:
  2055. f.write("FOO")
  2056. fullpath2 = os.path.join(self.repo.path, "bar")
  2057. with open(fullpath2, "w") as f:
  2058. f.write("BAR")
  2059. # Add and commit both files
  2060. porcelain.add(self.repo.path, paths=[fullpath1, fullpath2])
  2061. porcelain.commit(
  2062. repo=self.repo,
  2063. message=b"test",
  2064. author=b"test <email>",
  2065. committer=b"test <email>",
  2066. )
  2067. # Try to move without force (should fail)
  2068. self.assertRaises(porcelain.Error, porcelain.mv, self.repo.path, "foo", "bar")
  2069. # Move with force
  2070. porcelain.mv(self.repo.path, "foo", "bar", force=True)
  2071. # Verify foo doesn't exist and bar has foo's content
  2072. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  2073. with open(os.path.join(self.repo.path, "bar")) as f:
  2074. self.assertEqual(f.read(), "FOO")
  2075. def test_mv_file_not_tracked(self) -> None:
  2076. # Create an untracked file
  2077. fullpath = os.path.join(self.repo.path, "untracked")
  2078. with open(fullpath, "w") as f:
  2079. f.write("UNTRACKED")
  2080. # Try to move it (should fail)
  2081. self.assertRaises(
  2082. porcelain.Error, porcelain.mv, self.repo.path, "untracked", "tracked"
  2083. )
  2084. def test_mv_file_not_exists(self) -> None:
  2085. # Try to move a non-existent file
  2086. self.assertRaises(
  2087. porcelain.Error, porcelain.mv, self.repo.path, "nonexistent", "destination"
  2088. )
  2089. def test_mv_absolute_paths(self) -> None:
  2090. # Create a file
  2091. fullpath = os.path.join(self.repo.path, "foo")
  2092. with open(fullpath, "w") as f:
  2093. f.write("BAR")
  2094. # Add and commit the file
  2095. porcelain.add(self.repo.path, paths=[fullpath])
  2096. porcelain.commit(
  2097. repo=self.repo,
  2098. message=b"test",
  2099. author=b"test <email>",
  2100. committer=b"test <email>",
  2101. )
  2102. # Move using absolute paths
  2103. dest_path = os.path.join(self.repo.path, "bar")
  2104. porcelain.mv(self.repo.path, fullpath, dest_path)
  2105. # Verify file moved
  2106. self.assertFalse(os.path.exists(fullpath))
  2107. self.assertTrue(os.path.exists(dest_path))
  2108. def test_mv_from_different_directory(self) -> None:
  2109. # Create a subdirectory with a file
  2110. subdir = os.path.join(self.repo.path, "mydir")
  2111. os.makedirs(subdir)
  2112. fullpath = os.path.join(subdir, "myfile")
  2113. with open(fullpath, "w") as f:
  2114. f.write("BAR")
  2115. # Add and commit the file
  2116. porcelain.add(self.repo.path, paths=[fullpath])
  2117. porcelain.commit(
  2118. repo=self.repo,
  2119. message=b"test",
  2120. author=b"test <email>",
  2121. committer=b"test <email>",
  2122. )
  2123. # Change to a different directory and move the file
  2124. cwd = os.getcwd()
  2125. tempdir = tempfile.mkdtemp()
  2126. def cleanup():
  2127. os.chdir(cwd)
  2128. shutil.rmtree(tempdir)
  2129. self.addCleanup(cleanup)
  2130. os.chdir(tempdir)
  2131. # Move the file using relative path from repository root
  2132. porcelain.mv(self.repo.path, "mydir/myfile", "renamed")
  2133. # Verify file was moved
  2134. self.assertFalse(os.path.exists(fullpath))
  2135. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "renamed")))
  2136. class LogTests(PorcelainTestCase):
  2137. def test_simple(self) -> None:
  2138. _c1, _c2, c3 = build_commit_graph(
  2139. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2140. )
  2141. self.repo.refs[b"HEAD"] = c3.id
  2142. self.maxDiff = None
  2143. outstream = StringIO()
  2144. porcelain.log(self.repo.path, outstream=outstream)
  2145. self.assertEqual(
  2146. outstream.getvalue(),
  2147. """\
  2148. --------------------------------------------------
  2149. commit: 4a3b887baa9ecb2d054d2469b628aef84e2d74f0
  2150. merge: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  2151. Author: Test Author <test@nodomain.com>
  2152. Committer: Test Committer <test@nodomain.com>
  2153. Date: Fri Jan 01 2010 00:00:00 +0000
  2154. Commit 3
  2155. --------------------------------------------------
  2156. commit: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  2157. Author: Test Author <test@nodomain.com>
  2158. Committer: Test Committer <test@nodomain.com>
  2159. Date: Fri Jan 01 2010 00:00:00 +0000
  2160. Commit 2
  2161. --------------------------------------------------
  2162. commit: 11d3cf672a19366435c1983c7340b008ec6b8bf3
  2163. Author: Test Author <test@nodomain.com>
  2164. Committer: Test Committer <test@nodomain.com>
  2165. Date: Fri Jan 01 2010 00:00:00 +0000
  2166. Commit 1
  2167. """,
  2168. )
  2169. def test_max_entries(self) -> None:
  2170. _c1, _c2, c3 = build_commit_graph(
  2171. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2172. )
  2173. self.repo.refs[b"HEAD"] = c3.id
  2174. outstream = StringIO()
  2175. porcelain.log(self.repo.path, outstream=outstream, max_entries=1)
  2176. self.assertEqual(1, outstream.getvalue().count("-" * 50))
  2177. def test_no_revisions(self) -> None:
  2178. outstream = StringIO()
  2179. porcelain.log(self.repo.path, outstream=outstream)
  2180. self.assertEqual("", outstream.getvalue())
  2181. def test_empty_message(self) -> None:
  2182. c1 = make_commit(message="")
  2183. self.repo.object_store.add_object(c1)
  2184. self.repo.refs[b"HEAD"] = c1.id
  2185. outstream = StringIO()
  2186. porcelain.log(self.repo.path, outstream=outstream)
  2187. self.assertEqual(
  2188. outstream.getvalue(),
  2189. """\
  2190. --------------------------------------------------
  2191. commit: 4a7ad5552fad70647a81fb9a4a923ccefcca4b76
  2192. Author: Test Author <test@nodomain.com>
  2193. Committer: Test Committer <test@nodomain.com>
  2194. Date: Fri Jan 01 2010 00:00:00 +0000
  2195. """,
  2196. )
  2197. class ShowTests(PorcelainTestCase):
  2198. def test_nolist(self) -> None:
  2199. _c1, _c2, c3 = build_commit_graph(
  2200. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2201. )
  2202. self.repo.refs[b"HEAD"] = c3.id
  2203. outstream = StringIO()
  2204. porcelain.show(self.repo.path, objects=c3.id, outstream=outstream)
  2205. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  2206. def test_simple(self) -> None:
  2207. _c1, _c2, c3 = build_commit_graph(
  2208. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2209. )
  2210. self.repo.refs[b"HEAD"] = c3.id
  2211. outstream = StringIO()
  2212. porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream)
  2213. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  2214. def test_blob(self) -> None:
  2215. b = Blob.from_string(b"The Foo\n")
  2216. self.repo.object_store.add_object(b)
  2217. outstream = StringIO()
  2218. porcelain.show(self.repo.path, objects=[b.id], outstream=outstream)
  2219. self.assertEqual(outstream.getvalue(), "The Foo\n")
  2220. def test_commit_no_parent(self) -> None:
  2221. a = Blob.from_string(b"The Foo\n")
  2222. ta = Tree()
  2223. ta.add(b"somename", 0o100644, a.id)
  2224. ca = make_commit(tree=ta.id)
  2225. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2226. outstream = StringIO()
  2227. porcelain.show(self.repo.path, objects=[ca.id], outstream=outstream)
  2228. self.assertMultiLineEqual(
  2229. outstream.getvalue(),
  2230. """\
  2231. --------------------------------------------------
  2232. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2233. Author: Test Author <test@nodomain.com>
  2234. Committer: Test Committer <test@nodomain.com>
  2235. Date: Fri Jan 01 2010 00:00:00 +0000
  2236. Test message.
  2237. diff --git a/somename b/somename
  2238. new file mode 100644
  2239. index 0000000..ea5c7bf
  2240. --- /dev/null
  2241. +++ b/somename
  2242. @@ -0,0 +1 @@
  2243. +The Foo
  2244. """,
  2245. )
  2246. def test_tag(self) -> None:
  2247. a = Blob.from_string(b"The Foo\n")
  2248. ta = Tree()
  2249. ta.add(b"somename", 0o100644, a.id)
  2250. ca = make_commit(tree=ta.id)
  2251. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2252. porcelain.tag_create(
  2253. self.repo.path,
  2254. b"tryme",
  2255. b"foo <foo@bar.com>",
  2256. b"bar",
  2257. annotated=True,
  2258. objectish=ca.id,
  2259. tag_time=1552854211,
  2260. tag_timezone=0,
  2261. )
  2262. outstream = StringIO()
  2263. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2264. self.maxDiff = None
  2265. self.assertMultiLineEqual(
  2266. outstream.getvalue(),
  2267. """\
  2268. Tagger: foo <foo@bar.com>
  2269. Date: Sun Mar 17 2019 20:23:31 +0000
  2270. bar
  2271. --------------------------------------------------
  2272. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2273. Author: Test Author <test@nodomain.com>
  2274. Committer: Test Committer <test@nodomain.com>
  2275. Date: Fri Jan 01 2010 00:00:00 +0000
  2276. Test message.
  2277. diff --git a/somename b/somename
  2278. new file mode 100644
  2279. index 0000000..ea5c7bf
  2280. --- /dev/null
  2281. +++ b/somename
  2282. @@ -0,0 +1 @@
  2283. +The Foo
  2284. """,
  2285. )
  2286. def test_tag_unicode(self) -> None:
  2287. a = Blob.from_string(b"The Foo\n")
  2288. ta = Tree()
  2289. ta.add(b"somename", 0o100644, a.id)
  2290. ca = make_commit(tree=ta.id)
  2291. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2292. porcelain.tag_create(
  2293. self.repo.path,
  2294. "tryme",
  2295. "foo <foo@bar.com>",
  2296. "bar",
  2297. annotated=True,
  2298. objectish=ca.id,
  2299. tag_time=1552854211,
  2300. tag_timezone=0,
  2301. )
  2302. outstream = StringIO()
  2303. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2304. self.maxDiff = None
  2305. self.assertMultiLineEqual(
  2306. outstream.getvalue(),
  2307. """\
  2308. Tagger: foo <foo@bar.com>
  2309. Date: Sun Mar 17 2019 20:23:31 +0000
  2310. bar
  2311. --------------------------------------------------
  2312. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2313. Author: Test Author <test@nodomain.com>
  2314. Committer: Test Committer <test@nodomain.com>
  2315. Date: Fri Jan 01 2010 00:00:00 +0000
  2316. Test message.
  2317. diff --git a/somename b/somename
  2318. new file mode 100644
  2319. index 0000000..ea5c7bf
  2320. --- /dev/null
  2321. +++ b/somename
  2322. @@ -0,0 +1 @@
  2323. +The Foo
  2324. """,
  2325. )
  2326. def test_commit_with_change(self) -> None:
  2327. a = Blob.from_string(b"The Foo\n")
  2328. ta = Tree()
  2329. ta.add(b"somename", 0o100644, a.id)
  2330. ca = make_commit(tree=ta.id)
  2331. b = Blob.from_string(b"The Bar\n")
  2332. tb = Tree()
  2333. tb.add(b"somename", 0o100644, b.id)
  2334. cb = make_commit(tree=tb.id, parents=[ca.id])
  2335. self.repo.object_store.add_objects(
  2336. [
  2337. (a, None),
  2338. (b, None),
  2339. (ta, None),
  2340. (tb, None),
  2341. (ca, None),
  2342. (cb, None),
  2343. ]
  2344. )
  2345. outstream = StringIO()
  2346. porcelain.show(self.repo.path, objects=[cb.id], outstream=outstream)
  2347. self.assertMultiLineEqual(
  2348. outstream.getvalue(),
  2349. """\
  2350. --------------------------------------------------
  2351. commit: 2c6b6c9cb72c130956657e1fdae58e5b103744fa
  2352. Author: Test Author <test@nodomain.com>
  2353. Committer: Test Committer <test@nodomain.com>
  2354. Date: Fri Jan 01 2010 00:00:00 +0000
  2355. Test message.
  2356. diff --git a/somename b/somename
  2357. index ea5c7bf..fd38bcb 100644
  2358. --- a/somename
  2359. +++ b/somename
  2360. @@ -1 +1 @@
  2361. -The Foo
  2362. +The Bar
  2363. """,
  2364. )
  2365. class FormatPatchTests(PorcelainTestCase):
  2366. def test_format_patch_single_commit(self) -> None:
  2367. # Create initial commit
  2368. tree1 = Tree()
  2369. c1 = make_commit(
  2370. tree=tree1,
  2371. message=b"Initial commit",
  2372. )
  2373. self.repo.object_store.add_objects([(tree1, None), (c1, None)])
  2374. # Create second commit
  2375. b = Blob.from_string(b"modified")
  2376. tree = Tree()
  2377. tree.add(b"test.txt", 0o100644, b.id)
  2378. c2 = make_commit(
  2379. tree=tree,
  2380. parents=[c1.id],
  2381. message=b"Add test.txt",
  2382. )
  2383. self.repo.object_store.add_objects([(b, None), (tree, None), (c2, None)])
  2384. self.repo[b"HEAD"] = c2.id
  2385. # Generate patch for single commit
  2386. with tempfile.TemporaryDirectory() as tmpdir:
  2387. patches = porcelain.format_patch(
  2388. self.repo.path,
  2389. committish=c2.id,
  2390. outdir=tmpdir,
  2391. )
  2392. self.assertEqual(len(patches), 1)
  2393. self.assertTrue(patches[0].endswith("-Add-test.txt.patch"))
  2394. # Verify patch content
  2395. with open(patches[0], "rb") as f:
  2396. content = f.read()
  2397. self.assertIn(b"Subject: [PATCH 1/1] Add test.txt", content)
  2398. self.assertIn(b"+modified", content)
  2399. def test_format_patch_multiple_commits(self) -> None:
  2400. # Create commit chain
  2401. commits = []
  2402. for i in range(3):
  2403. blob = Blob.from_string(f"content {i}".encode())
  2404. tree = Tree()
  2405. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  2406. parents = [commits[-1].id] if commits else []
  2407. commit = make_commit(
  2408. tree=tree,
  2409. parents=parents,
  2410. message=f"Commit {i}".encode(),
  2411. )
  2412. self.repo.object_store.add_objects(
  2413. [(blob, None), (tree, None), (commit, None)]
  2414. )
  2415. commits.append(commit)
  2416. self.repo[b"HEAD"] = commits[-1].id
  2417. # Test generating last 2 commits
  2418. with tempfile.TemporaryDirectory() as tmpdir:
  2419. patches = porcelain.format_patch(
  2420. self.repo.path,
  2421. n=2,
  2422. outdir=tmpdir,
  2423. )
  2424. self.assertEqual(len(patches), 2)
  2425. self.assertTrue(patches[0].endswith("-Commit-1.patch"))
  2426. self.assertTrue(patches[1].endswith("-Commit-2.patch"))
  2427. # Check patch numbering
  2428. with open(patches[0], "rb") as f:
  2429. self.assertIn(b"Subject: [PATCH 1/2] Commit 1", f.read())
  2430. with open(patches[1], "rb") as f:
  2431. self.assertIn(b"Subject: [PATCH 2/2] Commit 2", f.read())
  2432. def test_format_patch_range(self) -> None:
  2433. # Create commit chain
  2434. c1, _c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  2435. self.repo[b"HEAD"] = c3.id
  2436. # Test commit range
  2437. with tempfile.TemporaryDirectory() as tmpdir:
  2438. patches = porcelain.format_patch(
  2439. self.repo.path,
  2440. committish=(c1.id, c3.id),
  2441. outdir=tmpdir,
  2442. )
  2443. # Should include c2 and c3
  2444. self.assertEqual(len(patches), 2)
  2445. def test_format_patch_stdout(self) -> None:
  2446. # Create a commit
  2447. blob = Blob.from_string(b"test content")
  2448. tree = Tree()
  2449. tree.add(b"test.txt", 0o100644, blob.id)
  2450. commit = make_commit(
  2451. tree=tree,
  2452. message=b"Test commit",
  2453. )
  2454. self.repo.object_store.add_objects([(blob, None), (tree, None), (commit, None)])
  2455. self.repo[b"HEAD"] = commit.id
  2456. # Test stdout output
  2457. outstream = BytesIO()
  2458. patches = porcelain.format_patch(
  2459. self.repo.path,
  2460. committish=commit.id,
  2461. stdout=True,
  2462. outstream=outstream,
  2463. )
  2464. # Should return empty list when writing to stdout
  2465. self.assertEqual(patches, [])
  2466. # Check stdout content
  2467. outstream.seek(0)
  2468. content = outstream.read()
  2469. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  2470. self.assertIn(b"diff --git", content)
  2471. def test_format_patch_no_commits(self) -> None:
  2472. # Test with a new repository with no commits
  2473. # Just remove HEAD to simulate empty repo
  2474. patches = porcelain.format_patch(
  2475. self.repo.path,
  2476. n=5,
  2477. )
  2478. self.assertEqual(patches, [])
  2479. class SymbolicRefTests(PorcelainTestCase):
  2480. def test_set_wrong_symbolic_ref(self) -> None:
  2481. _c1, _c2, c3 = build_commit_graph(
  2482. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2483. )
  2484. self.repo.refs[b"HEAD"] = c3.id
  2485. self.assertRaises(
  2486. porcelain.Error, porcelain.symbolic_ref, self.repo.path, b"foobar"
  2487. )
  2488. def test_set_force_wrong_symbolic_ref(self) -> None:
  2489. _c1, _c2, c3 = build_commit_graph(
  2490. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2491. )
  2492. self.repo.refs[b"HEAD"] = c3.id
  2493. porcelain.symbolic_ref(self.repo.path, b"force_foobar", force=True)
  2494. # test if we actually changed the file
  2495. with self.repo.get_named_file("HEAD") as f:
  2496. new_ref = f.read()
  2497. self.assertEqual(new_ref, b"ref: refs/heads/force_foobar\n")
  2498. def test_set_symbolic_ref(self) -> None:
  2499. _c1, _c2, c3 = build_commit_graph(
  2500. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2501. )
  2502. self.repo.refs[b"HEAD"] = c3.id
  2503. porcelain.symbolic_ref(self.repo.path, b"master")
  2504. def test_set_symbolic_ref_other_than_master(self) -> None:
  2505. _c1, _c2, c3 = build_commit_graph(
  2506. self.repo.object_store,
  2507. [[1], [2, 1], [3, 1, 2]],
  2508. attrs=dict(refs="develop"),
  2509. )
  2510. self.repo.refs[b"HEAD"] = c3.id
  2511. self.repo.refs[b"refs/heads/develop"] = c3.id
  2512. porcelain.symbolic_ref(self.repo.path, b"develop")
  2513. # test if we actually changed the file
  2514. with self.repo.get_named_file("HEAD") as f:
  2515. new_ref = f.read()
  2516. self.assertEqual(new_ref, b"ref: refs/heads/develop\n")
  2517. class DiffTreeTests(PorcelainTestCase):
  2518. def test_empty(self) -> None:
  2519. _c1, c2, c3 = build_commit_graph(
  2520. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2521. )
  2522. self.repo.refs[b"HEAD"] = c3.id
  2523. outstream = BytesIO()
  2524. porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream)
  2525. self.assertEqual(outstream.getvalue(), b"")
  2526. class DiffTests(PorcelainTestCase):
  2527. def test_diff_uncommitted_stage(self) -> None:
  2528. # Test diff in repository with no commits yet
  2529. fullpath = os.path.join(self.repo.path, "test.txt")
  2530. with open(fullpath, "w") as f:
  2531. f.write("Hello, world!\n")
  2532. porcelain.add(self.repo.path, paths=["test.txt"])
  2533. outstream = BytesIO()
  2534. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2535. diff_output = outstream.getvalue()
  2536. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2537. self.assertIn(b"new file mode", diff_output)
  2538. self.assertIn(b"+Hello, world!", diff_output)
  2539. def test_diff_uncommitted_working_tree(self) -> None:
  2540. # Test unstaged changes in repository with no commits
  2541. fullpath = os.path.join(self.repo.path, "test.txt")
  2542. with open(fullpath, "w") as f:
  2543. f.write("Hello, world!\n")
  2544. porcelain.add(self.repo.path, paths=["test.txt"])
  2545. # Modify file in working tree
  2546. with open(fullpath, "w") as f:
  2547. f.write("Hello, world!\nNew line\n")
  2548. outstream = BytesIO()
  2549. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2550. diff_output = outstream.getvalue()
  2551. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2552. self.assertIn(b"+New line", diff_output)
  2553. def test_diff_with_commits_staged(self) -> None:
  2554. # Test staged changes with existing commits
  2555. fullpath = os.path.join(self.repo.path, "test.txt")
  2556. with open(fullpath, "w") as f:
  2557. f.write("Initial content\n")
  2558. porcelain.add(self.repo.path, paths=["test.txt"])
  2559. porcelain.commit(self.repo.path, message=b"Initial commit")
  2560. # Modify and stage
  2561. with open(fullpath, "w") as f:
  2562. f.write("Initial content\nModified\n")
  2563. porcelain.add(self.repo.path, paths=["test.txt"])
  2564. outstream = BytesIO()
  2565. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2566. diff_output = outstream.getvalue()
  2567. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2568. self.assertIn(b"+Modified", diff_output)
  2569. def test_diff_with_commits_unstaged(self) -> None:
  2570. # Test unstaged changes with existing commits
  2571. fullpath = os.path.join(self.repo.path, "test.txt")
  2572. with open(fullpath, "w") as f:
  2573. f.write("Initial content\n")
  2574. porcelain.add(self.repo.path, paths=["test.txt"])
  2575. porcelain.commit(self.repo.path, message=b"Initial commit")
  2576. # Modify without staging
  2577. with open(fullpath, "w") as f:
  2578. f.write("Initial content\nModified\n")
  2579. outstream = BytesIO()
  2580. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2581. diff_output = outstream.getvalue()
  2582. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2583. self.assertIn(b"+Modified", diff_output)
  2584. def test_diff_file_deletion(self) -> None:
  2585. # Test showing file deletion
  2586. fullpath = os.path.join(self.repo.path, "test.txt")
  2587. with open(fullpath, "w") as f:
  2588. f.write("Content to delete\n")
  2589. porcelain.add(self.repo.path, paths=["test.txt"])
  2590. porcelain.commit(self.repo.path, message=b"Add file")
  2591. # Delete file
  2592. os.unlink(fullpath)
  2593. outstream = BytesIO()
  2594. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2595. diff_output = outstream.getvalue()
  2596. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2597. self.assertIn(b"deleted file mode", diff_output)
  2598. self.assertIn(b"-Content to delete", diff_output)
  2599. def test_diff_with_paths(self) -> None:
  2600. # Test diff with specific paths
  2601. # Create two files
  2602. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2603. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2604. with open(fullpath1, "w") as f:
  2605. f.write("File 1 content\n")
  2606. with open(fullpath2, "w") as f:
  2607. f.write("File 2 content\n")
  2608. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2609. porcelain.commit(self.repo.path, message=b"Add two files")
  2610. # Modify both files
  2611. with open(fullpath1, "w") as f:
  2612. f.write("File 1 modified\n")
  2613. with open(fullpath2, "w") as f:
  2614. f.write("File 2 modified\n")
  2615. # Test diff with specific path
  2616. outstream = BytesIO()
  2617. porcelain.diff(self.repo.path, paths=["file1.txt"], outstream=outstream)
  2618. diff_output = outstream.getvalue()
  2619. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2620. self.assertIn(b"-File 1 content", diff_output)
  2621. self.assertIn(b"+File 1 modified", diff_output)
  2622. # file2.txt should not appear in diff
  2623. self.assertNotIn(b"file2.txt", diff_output)
  2624. def test_diff_with_paths_multiple(self) -> None:
  2625. # Test diff with multiple paths
  2626. # Create three files
  2627. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2628. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2629. fullpath3 = os.path.join(self.repo.path, "file3.txt")
  2630. with open(fullpath1, "w") as f:
  2631. f.write("File 1 content\n")
  2632. with open(fullpath2, "w") as f:
  2633. f.write("File 2 content\n")
  2634. with open(fullpath3, "w") as f:
  2635. f.write("File 3 content\n")
  2636. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt", "file3.txt"])
  2637. porcelain.commit(self.repo.path, message=b"Add three files")
  2638. # Modify all files
  2639. with open(fullpath1, "w") as f:
  2640. f.write("File 1 modified\n")
  2641. with open(fullpath2, "w") as f:
  2642. f.write("File 2 modified\n")
  2643. with open(fullpath3, "w") as f:
  2644. f.write("File 3 modified\n")
  2645. # Test diff with two specific paths
  2646. outstream = BytesIO()
  2647. porcelain.diff(
  2648. self.repo.path, paths=["file1.txt", "file3.txt"], outstream=outstream
  2649. )
  2650. diff_output = outstream.getvalue()
  2651. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2652. self.assertIn(b"diff --git a/file3.txt b/file3.txt", diff_output)
  2653. # file2.txt should not appear in diff
  2654. self.assertNotIn(b"file2.txt", diff_output)
  2655. def test_diff_with_paths_directory(self) -> None:
  2656. # Test diff with directory paths
  2657. # Create files in subdirectory
  2658. os.mkdir(os.path.join(self.repo.path, "subdir"))
  2659. fullpath1 = os.path.join(self.repo.path, "subdir", "file1.txt")
  2660. fullpath2 = os.path.join(self.repo.path, "subdir", "file2.txt")
  2661. fullpath3 = os.path.join(self.repo.path, "root.txt")
  2662. with open(fullpath1, "w") as f:
  2663. f.write("Subdir file 1\n")
  2664. with open(fullpath2, "w") as f:
  2665. f.write("Subdir file 2\n")
  2666. with open(fullpath3, "w") as f:
  2667. f.write("Root file\n")
  2668. porcelain.add(
  2669. self.repo.path, paths=["subdir/file1.txt", "subdir/file2.txt", "root.txt"]
  2670. )
  2671. porcelain.commit(self.repo.path, message=b"Add files in subdir")
  2672. # Modify all files
  2673. with open(fullpath1, "w") as f:
  2674. f.write("Subdir file 1 modified\n")
  2675. with open(fullpath2, "w") as f:
  2676. f.write("Subdir file 2 modified\n")
  2677. with open(fullpath3, "w") as f:
  2678. f.write("Root file modified\n")
  2679. # Test diff with directory path
  2680. outstream = BytesIO()
  2681. porcelain.diff(self.repo.path, paths=["subdir"], outstream=outstream)
  2682. diff_output = outstream.getvalue()
  2683. self.assertIn(b"subdir/file1.txt", diff_output)
  2684. self.assertIn(b"subdir/file2.txt", diff_output)
  2685. # root.txt should not appear in diff
  2686. self.assertNotIn(b"root.txt", diff_output)
  2687. def test_diff_staged_with_paths(self) -> None:
  2688. # Test staged diff with specific paths
  2689. # Create two files
  2690. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2691. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2692. with open(fullpath1, "w") as f:
  2693. f.write("File 1 content\n")
  2694. with open(fullpath2, "w") as f:
  2695. f.write("File 2 content\n")
  2696. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2697. porcelain.commit(self.repo.path, message=b"Add two files")
  2698. # Modify and stage both files
  2699. with open(fullpath1, "w") as f:
  2700. f.write("File 1 staged\n")
  2701. with open(fullpath2, "w") as f:
  2702. f.write("File 2 staged\n")
  2703. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2704. # Test staged diff with specific path
  2705. outstream = BytesIO()
  2706. porcelain.diff(
  2707. self.repo.path, staged=True, paths=["file1.txt"], outstream=outstream
  2708. )
  2709. diff_output = outstream.getvalue()
  2710. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2711. self.assertIn(b"-File 1 content", diff_output)
  2712. self.assertIn(b"+File 1 staged", diff_output)
  2713. # file2.txt should not appear in diff
  2714. self.assertNotIn(b"file2.txt", diff_output)
  2715. def test_diff_with_commit_and_paths(self) -> None:
  2716. # Test diff against specific commit with paths
  2717. # Create initial file
  2718. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2719. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2720. with open(fullpath1, "w") as f:
  2721. f.write("Initial content 1\n")
  2722. with open(fullpath2, "w") as f:
  2723. f.write("Initial content 2\n")
  2724. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2725. first_commit = porcelain.commit(self.repo.path, message=b"Initial commit")
  2726. # Make second commit
  2727. with open(fullpath1, "w") as f:
  2728. f.write("Second content 1\n")
  2729. with open(fullpath2, "w") as f:
  2730. f.write("Second content 2\n")
  2731. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2732. porcelain.commit(self.repo.path, message=b"Second commit")
  2733. # Modify working tree
  2734. with open(fullpath1, "w") as f:
  2735. f.write("Working content 1\n")
  2736. with open(fullpath2, "w") as f:
  2737. f.write("Working content 2\n")
  2738. # Test diff against first commit with specific path
  2739. outstream = BytesIO()
  2740. porcelain.diff(
  2741. self.repo.path,
  2742. commit=first_commit,
  2743. paths=["file1.txt"],
  2744. outstream=outstream,
  2745. )
  2746. diff_output = outstream.getvalue()
  2747. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2748. self.assertIn(b"-Initial content 1", diff_output)
  2749. self.assertIn(b"+Working content 1", diff_output)
  2750. # file2.txt should not appear in diff
  2751. self.assertNotIn(b"file2.txt", diff_output)
  2752. class CommitTreeTests(PorcelainTestCase):
  2753. def test_simple(self) -> None:
  2754. _c1, _c2, _c3 = build_commit_graph(
  2755. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2756. )
  2757. b = Blob()
  2758. b.data = b"foo the bar"
  2759. t = Tree()
  2760. t.add(b"somename", 0o100644, b.id)
  2761. self.repo.object_store.add_object(t)
  2762. self.repo.object_store.add_object(b)
  2763. sha = porcelain.commit_tree(
  2764. self.repo.path,
  2765. t.id,
  2766. message=b"Withcommit.",
  2767. author=b"Joe <joe@example.com>",
  2768. committer=b"Jane <jane@example.com>",
  2769. )
  2770. self.assertIsInstance(sha, bytes)
  2771. self.assertEqual(len(sha), 40)
  2772. class RevListTests(PorcelainTestCase):
  2773. def test_simple(self) -> None:
  2774. c1, c2, c3 = build_commit_graph(
  2775. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2776. )
  2777. outstream = BytesIO()
  2778. porcelain.rev_list(self.repo.path, [c3.id], outstream=outstream)
  2779. self.assertEqual(
  2780. c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue()
  2781. )
  2782. @skipIf(
  2783. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  2784. "gpgme not easily available or supported on Windows and PyPy",
  2785. )
  2786. class TagCreateSignTests(PorcelainGpgTestCase):
  2787. def test_default_key(self) -> None:
  2788. _c1, _c2, c3 = build_commit_graph(
  2789. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2790. )
  2791. self.repo.refs[b"HEAD"] = c3.id
  2792. cfg = self.repo.get_config()
  2793. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2794. self.import_default_key()
  2795. porcelain.tag_create(
  2796. self.repo.path,
  2797. b"tryme",
  2798. b"foo <foo@bar.com>",
  2799. b"bar",
  2800. annotated=True,
  2801. sign=True,
  2802. )
  2803. tags = self.repo.refs.as_dict(b"refs/tags")
  2804. self.assertEqual(list(tags.keys()), [b"tryme"])
  2805. tag = self.repo[b"refs/tags/tryme"]
  2806. self.assertIsInstance(tag, Tag)
  2807. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2808. self.assertEqual(b"bar\n", tag.message)
  2809. self.assertRecentTimestamp(tag.tag_time)
  2810. tag = self.repo[b"refs/tags/tryme"]
  2811. assert isinstance(tag, Tag)
  2812. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2813. from dulwich.signature import (
  2814. BadSignature,
  2815. UntrustedSignature,
  2816. get_signature_vendor_for_signature,
  2817. )
  2818. self.assertIsNotNone(tag.signature)
  2819. vendor = get_signature_vendor_for_signature(tag.signature)
  2820. vendor.verify(tag.raw_without_sig(), tag.signature)
  2821. vendor.verify(
  2822. tag.raw_without_sig(),
  2823. tag.signature,
  2824. keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID],
  2825. )
  2826. self.import_non_default_key()
  2827. self.assertRaises(
  2828. UntrustedSignature,
  2829. vendor.verify,
  2830. tag.raw_without_sig(),
  2831. tag.signature,
  2832. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  2833. )
  2834. assert tag.signature is not None
  2835. tag._chunked_text = [b"bad data", tag.signature]
  2836. self.assertRaises(
  2837. BadSignature,
  2838. vendor.verify,
  2839. tag.raw_without_sig(),
  2840. tag.signature,
  2841. )
  2842. def test_non_default_key(self) -> None:
  2843. _c1, _c2, c3 = build_commit_graph(
  2844. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2845. )
  2846. self.repo.refs[b"HEAD"] = c3.id
  2847. cfg = self.repo.get_config()
  2848. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2849. self.import_non_default_key()
  2850. porcelain.tag_create(
  2851. self.repo.path,
  2852. b"tryme",
  2853. b"foo <foo@bar.com>",
  2854. b"bar",
  2855. annotated=True,
  2856. sign=True,
  2857. )
  2858. tags = self.repo.refs.as_dict(b"refs/tags")
  2859. self.assertEqual(list(tags.keys()), [b"tryme"])
  2860. tag = self.repo[b"refs/tags/tryme"]
  2861. self.assertIsInstance(tag, Tag)
  2862. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2863. self.assertEqual(b"bar\n", tag.message)
  2864. self.assertRecentTimestamp(tag.tag_time)
  2865. tag = self.repo[b"refs/tags/tryme"]
  2866. assert isinstance(tag, Tag)
  2867. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2868. from dulwich.signature import get_signature_vendor_for_signature
  2869. self.assertIsNotNone(tag.signature)
  2870. vendor = get_signature_vendor_for_signature(tag.signature)
  2871. vendor.verify(tag.raw_without_sig(), tag.signature)
  2872. def test_sign_uses_config_signingkey(self) -> None:
  2873. """Test that sign=True uses user.signingKey from config."""
  2874. _c1, _c2, c3 = build_commit_graph(
  2875. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2876. )
  2877. self.repo.refs[b"HEAD"] = c3.id
  2878. # Set up user.signingKey in config
  2879. cfg = self.repo.get_config()
  2880. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2881. cfg.write_to_path()
  2882. self.import_default_key()
  2883. # Create tag with sign=True (should use signingKey from config)
  2884. porcelain.tag_create(
  2885. self.repo.path,
  2886. b"signed-tag",
  2887. b"foo <foo@bar.com>",
  2888. b"Tag with configured key",
  2889. annotated=True,
  2890. sign=True, # This should read user.signingKey from config
  2891. )
  2892. tags = self.repo.refs.as_dict(b"refs/tags")
  2893. self.assertEqual(list(tags.keys()), [b"signed-tag"])
  2894. tag = self.repo[b"refs/tags/signed-tag"]
  2895. self.assertIsInstance(tag, Tag)
  2896. # Verify the tag is signed with the configured key
  2897. from dulwich.signature import get_signature_vendor_for_signature
  2898. self.assertIsNotNone(tag.signature)
  2899. vendor = get_signature_vendor_for_signature(tag.signature)
  2900. vendor.verify(tag.raw_without_sig(), tag.signature)
  2901. vendor.verify(
  2902. tag.raw_without_sig(),
  2903. tag.signature,
  2904. keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID],
  2905. )
  2906. def test_tag_gpg_sign_config_enabled(self) -> None:
  2907. """Test that tag.gpgSign=true automatically signs tags."""
  2908. _c1, _c2, c3 = build_commit_graph(
  2909. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2910. )
  2911. self.repo.refs[b"HEAD"] = c3.id
  2912. # Set up user.signingKey and tag.gpgSign in config
  2913. cfg = self.repo.get_config()
  2914. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2915. cfg.set(("tag",), "gpgSign", True)
  2916. cfg.write_to_path()
  2917. self.import_default_key()
  2918. # Create tag without explicit sign parameter (should auto-sign due to config)
  2919. porcelain.tag_create(
  2920. self.repo.path,
  2921. b"auto-signed-tag",
  2922. b"foo <foo@bar.com>",
  2923. b"Auto-signed tag",
  2924. annotated=True,
  2925. # No sign parameter - should use tag.gpgSign config
  2926. )
  2927. tags = self.repo.refs.as_dict(b"refs/tags")
  2928. self.assertEqual(list(tags.keys()), [b"auto-signed-tag"])
  2929. tag = self.repo[b"refs/tags/auto-signed-tag"]
  2930. self.assertIsInstance(tag, Tag)
  2931. # Verify the tag is signed due to config
  2932. from dulwich.signature import get_signature_vendor_for_signature
  2933. self.assertIsNotNone(tag.signature)
  2934. vendor = get_signature_vendor_for_signature(tag.signature)
  2935. vendor.verify(tag.raw_without_sig(), tag.signature)
  2936. vendor.verify(
  2937. tag.raw_without_sig(),
  2938. tag.signature,
  2939. keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID],
  2940. )
  2941. def test_tag_gpg_sign_config_disabled(self) -> None:
  2942. """Test that tag.gpgSign=false does not sign tags."""
  2943. _c1, _c2, c3 = build_commit_graph(
  2944. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2945. )
  2946. self.repo.refs[b"HEAD"] = c3.id
  2947. # Set up user.signingKey and tag.gpgSign=false in config
  2948. cfg = self.repo.get_config()
  2949. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2950. cfg.set(("tag",), "gpgSign", False)
  2951. cfg.write_to_path()
  2952. self.import_default_key()
  2953. # Create tag without explicit sign parameter (should not sign)
  2954. porcelain.tag_create(
  2955. self.repo.path,
  2956. b"unsigned-tag",
  2957. b"foo <foo@bar.com>",
  2958. b"Unsigned tag",
  2959. annotated=True,
  2960. # No sign parameter - should use tag.gpgSign=false config
  2961. )
  2962. tags = self.repo.refs.as_dict(b"refs/tags")
  2963. self.assertEqual(list(tags.keys()), [b"unsigned-tag"])
  2964. tag = self.repo[b"refs/tags/unsigned-tag"]
  2965. self.assertIsInstance(tag, Tag)
  2966. # Verify the tag is not signed
  2967. self.assertIsNone(tag._signature)
  2968. def test_tag_gpg_sign_config_no_signing_key(self) -> None:
  2969. """Test that tag.gpgSign=true works without user.signingKey (uses default)."""
  2970. _c1, _c2, c3 = build_commit_graph(
  2971. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2972. )
  2973. self.repo.refs[b"HEAD"] = c3.id
  2974. # Set up tag.gpgSign but no user.signingKey
  2975. cfg = self.repo.get_config()
  2976. cfg.set(("tag",), "gpgSign", True)
  2977. cfg.write_to_path()
  2978. self.import_default_key()
  2979. # Create tag without explicit sign parameter (should auto-sign with default key)
  2980. porcelain.tag_create(
  2981. self.repo.path,
  2982. b"default-signed-tag",
  2983. b"foo <foo@bar.com>",
  2984. b"Default signed tag",
  2985. annotated=True,
  2986. # No sign parameter - should use tag.gpgSign config with default key
  2987. )
  2988. tags = self.repo.refs.as_dict(b"refs/tags")
  2989. self.assertEqual(list(tags.keys()), [b"default-signed-tag"])
  2990. tag = self.repo[b"refs/tags/default-signed-tag"]
  2991. self.assertIsInstance(tag, Tag)
  2992. # Verify the tag is signed with default key
  2993. from dulwich.signature import get_signature_vendor_for_signature
  2994. self.assertIsNotNone(tag.signature)
  2995. vendor = get_signature_vendor_for_signature(tag.signature)
  2996. vendor.verify(tag.raw_without_sig(), tag.signature)
  2997. def test_explicit_sign_overrides_config(self) -> None:
  2998. """Test that explicit sign parameter overrides tag.gpgSign config."""
  2999. _c1, _c2, c3 = build_commit_graph(
  3000. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  3001. )
  3002. self.repo.refs[b"HEAD"] = c3.id
  3003. # Set up tag.gpgSign=false but explicitly pass sign=True
  3004. cfg = self.repo.get_config()
  3005. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  3006. cfg.set(("tag",), "gpgSign", False)
  3007. cfg.write_to_path()
  3008. self.import_default_key()
  3009. # Create tag with explicit sign=True (should override config)
  3010. porcelain.tag_create(
  3011. self.repo.path,
  3012. b"explicit-signed-tag",
  3013. b"foo <foo@bar.com>",
  3014. b"Explicitly signed tag",
  3015. annotated=True,
  3016. sign=True, # This should override tag.gpgSign=false
  3017. )
  3018. tags = self.repo.refs.as_dict(b"refs/tags")
  3019. self.assertEqual(list(tags.keys()), [b"explicit-signed-tag"])
  3020. tag = self.repo[b"refs/tags/explicit-signed-tag"]
  3021. self.assertIsInstance(tag, Tag)
  3022. # Verify the tag is signed despite config=false
  3023. from dulwich.signature import get_signature_vendor_for_signature
  3024. self.assertIsNotNone(tag.signature)
  3025. vendor = get_signature_vendor_for_signature(tag.signature)
  3026. vendor.verify(tag.raw_without_sig(), tag.signature)
  3027. vendor.verify(
  3028. tag.raw_without_sig(),
  3029. tag.signature,
  3030. keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID],
  3031. )
  3032. def test_explicit_false_disables_tag_signing(self) -> None:
  3033. """Test that explicit sign=False disables signing even with config=true."""
  3034. _c1, _c2, c3 = build_commit_graph(
  3035. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  3036. )
  3037. self.repo.refs[b"HEAD"] = c3.id
  3038. # Set up tag.gpgSign=true but explicitly pass sign=False
  3039. cfg = self.repo.get_config()
  3040. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  3041. cfg.set(("tag",), "gpgSign", True)
  3042. cfg.write_to_path()
  3043. self.import_default_key()
  3044. # Create tag with explicit sign=False (should disable signing)
  3045. porcelain.tag_create(
  3046. self.repo.path,
  3047. b"explicit-unsigned-tag",
  3048. b"foo <foo@bar.com>",
  3049. b"Explicitly unsigned tag",
  3050. annotated=True,
  3051. sign=False, # This should override tag.gpgSign=true
  3052. )
  3053. tags = self.repo.refs.as_dict(b"refs/tags")
  3054. self.assertEqual(list(tags.keys()), [b"explicit-unsigned-tag"])
  3055. tag = self.repo[b"refs/tags/explicit-unsigned-tag"]
  3056. self.assertIsInstance(tag, Tag)
  3057. # Verify the tag is NOT signed despite config=true
  3058. self.assertIsNone(tag._signature)
  3059. class TagCreateTests(PorcelainTestCase):
  3060. def test_annotated(self) -> None:
  3061. _c1, _c2, c3 = build_commit_graph(
  3062. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  3063. )
  3064. self.repo.refs[b"HEAD"] = c3.id
  3065. porcelain.tag_create(
  3066. self.repo.path,
  3067. b"tryme",
  3068. b"foo <foo@bar.com>",
  3069. b"bar",
  3070. annotated=True,
  3071. )
  3072. tags = self.repo.refs.as_dict(b"refs/tags")
  3073. self.assertEqual(list(tags.keys()), [b"tryme"])
  3074. tag = self.repo[b"refs/tags/tryme"]
  3075. self.assertIsInstance(tag, Tag)
  3076. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  3077. self.assertEqual(b"bar\n", tag.message)
  3078. self.assertRecentTimestamp(tag.tag_time)
  3079. def test_unannotated(self) -> None:
  3080. _c1, _c2, c3 = build_commit_graph(
  3081. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  3082. )
  3083. self.repo.refs[b"HEAD"] = c3.id
  3084. porcelain.tag_create(self.repo.path, b"tryme", annotated=False)
  3085. tags = self.repo.refs.as_dict(b"refs/tags")
  3086. self.assertEqual(list(tags.keys()), [b"tryme"])
  3087. self.repo[b"refs/tags/tryme"]
  3088. self.assertEqual(list(tags.values()), [self.repo.head()])
  3089. def test_unannotated_unicode(self) -> None:
  3090. _c1, _c2, c3 = build_commit_graph(
  3091. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  3092. )
  3093. self.repo.refs[b"HEAD"] = c3.id
  3094. porcelain.tag_create(self.repo.path, "tryme", annotated=False)
  3095. tags = self.repo.refs.as_dict(b"refs/tags")
  3096. self.assertEqual(list(tags.keys()), [b"tryme"])
  3097. self.repo[b"refs/tags/tryme"]
  3098. self.assertEqual(list(tags.values()), [self.repo.head()])
  3099. class TagListTests(PorcelainTestCase):
  3100. def test_empty(self) -> None:
  3101. tags = porcelain.tag_list(self.repo.path)
  3102. self.assertEqual([], tags)
  3103. def test_simple(self) -> None:
  3104. self.repo.refs[b"refs/tags/foo"] = b"aa" * 20
  3105. self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20
  3106. tags = porcelain.tag_list(self.repo.path)
  3107. self.assertEqual([b"bar/bla", b"foo"], tags)
  3108. class TagDeleteTests(PorcelainTestCase):
  3109. def test_simple(self) -> None:
  3110. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3111. self.repo[b"HEAD"] = c1.id
  3112. porcelain.tag_create(self.repo, b"foo")
  3113. self.assertIn(b"foo", porcelain.tag_list(self.repo))
  3114. porcelain.tag_delete(self.repo, b"foo")
  3115. self.assertNotIn(b"foo", porcelain.tag_list(self.repo))
  3116. class ResetTests(PorcelainTestCase):
  3117. def test_hard_head(self) -> None:
  3118. fullpath = os.path.join(self.repo.path, "foo")
  3119. with open(fullpath, "w") as f:
  3120. f.write("BAR")
  3121. porcelain.add(self.repo.path, paths=[fullpath])
  3122. porcelain.commit(
  3123. self.repo.path,
  3124. message=b"Some message",
  3125. committer=b"Jane <jane@example.com>",
  3126. author=b"John <john@example.com>",
  3127. )
  3128. with open(os.path.join(self.repo.path, "foo"), "wb") as f:
  3129. f.write(b"OOH")
  3130. porcelain.reset(self.repo, "hard", b"HEAD")
  3131. index = self.repo.open_index()
  3132. changes = list(
  3133. tree_changes(
  3134. self.repo.object_store,
  3135. index.commit(self.repo.object_store),
  3136. self.repo[b"HEAD"].tree,
  3137. )
  3138. )
  3139. self.assertEqual([], changes)
  3140. def test_hard_commit(self) -> None:
  3141. fullpath = os.path.join(self.repo.path, "foo")
  3142. with open(fullpath, "w") as f:
  3143. f.write("BAR")
  3144. porcelain.add(self.repo.path, paths=[fullpath])
  3145. sha = porcelain.commit(
  3146. self.repo.path,
  3147. message=b"Some message",
  3148. committer=b"Jane <jane@example.com>",
  3149. author=b"John <john@example.com>",
  3150. )
  3151. with open(fullpath, "wb") as f:
  3152. f.write(b"BAZ")
  3153. porcelain.add(self.repo.path, paths=[fullpath])
  3154. porcelain.commit(
  3155. self.repo.path,
  3156. message=b"Some other message",
  3157. committer=b"Jane <jane@example.com>",
  3158. author=b"John <john@example.com>",
  3159. )
  3160. porcelain.reset(self.repo, "hard", sha)
  3161. index = self.repo.open_index()
  3162. changes = list(
  3163. tree_changes(
  3164. self.repo.object_store,
  3165. index.commit(self.repo.object_store),
  3166. self.repo[sha].tree,
  3167. )
  3168. )
  3169. self.assertEqual([], changes)
  3170. def test_hard_commit_short_hash(self) -> None:
  3171. fullpath = os.path.join(self.repo.path, "foo")
  3172. with open(fullpath, "w") as f:
  3173. f.write("BAR")
  3174. porcelain.add(self.repo.path, paths=[fullpath])
  3175. sha = porcelain.commit(
  3176. self.repo.path,
  3177. message=b"Some message",
  3178. committer=b"Jane <jane@example.com>",
  3179. author=b"John <john@example.com>",
  3180. )
  3181. with open(fullpath, "wb") as f:
  3182. f.write(b"BAZ")
  3183. porcelain.add(self.repo.path, paths=[fullpath])
  3184. porcelain.commit(
  3185. self.repo.path,
  3186. message=b"Some other message",
  3187. committer=b"Jane <jane@example.com>",
  3188. author=b"John <john@example.com>",
  3189. )
  3190. # Test with short hash (7 characters)
  3191. short_sha = sha[:7].decode("ascii")
  3192. porcelain.reset(self.repo, "hard", short_sha)
  3193. index = self.repo.open_index()
  3194. changes = list(
  3195. tree_changes(
  3196. self.repo.object_store,
  3197. index.commit(self.repo.object_store),
  3198. self.repo[sha].tree,
  3199. )
  3200. )
  3201. self.assertEqual([], changes)
  3202. def test_hard_deletes_untracked_files(self) -> None:
  3203. """Test that reset --hard deletes files that don't exist in target tree."""
  3204. # Create and commit a file
  3205. fullpath = os.path.join(self.repo.path, "foo")
  3206. with open(fullpath, "w") as f:
  3207. f.write("BAR")
  3208. porcelain.add(self.repo.path, paths=[fullpath])
  3209. sha1 = porcelain.commit(
  3210. self.repo.path,
  3211. message=b"First commit",
  3212. committer=b"Jane <jane@example.com>",
  3213. author=b"John <john@example.com>",
  3214. )
  3215. # Create another file and commit
  3216. fullpath2 = os.path.join(self.repo.path, "bar")
  3217. with open(fullpath2, "w") as f:
  3218. f.write("BAZ")
  3219. porcelain.add(self.repo.path, paths=[fullpath2])
  3220. porcelain.commit(
  3221. self.repo.path,
  3222. message=b"Second commit",
  3223. committer=b"Jane <jane@example.com>",
  3224. author=b"John <john@example.com>",
  3225. )
  3226. # Reset hard to first commit - this should delete 'bar'
  3227. porcelain.reset(self.repo, "hard", sha1)
  3228. # Check that 'foo' still exists and 'bar' is deleted
  3229. self.assertTrue(os.path.exists(fullpath))
  3230. self.assertFalse(os.path.exists(fullpath2))
  3231. # Check index matches first commit
  3232. index = self.repo.open_index()
  3233. self.assertIn(b"foo", index)
  3234. self.assertNotIn(b"bar", index)
  3235. def test_hard_deletes_files_in_subdirs(self) -> None:
  3236. """Test that reset --hard deletes files in subdirectories."""
  3237. # Create and commit files in subdirectory
  3238. subdir = os.path.join(self.repo.path, "subdir")
  3239. os.makedirs(subdir)
  3240. file1 = os.path.join(subdir, "file1")
  3241. file2 = os.path.join(subdir, "file2")
  3242. with open(file1, "w") as f:
  3243. f.write("content1")
  3244. with open(file2, "w") as f:
  3245. f.write("content2")
  3246. porcelain.add(self.repo.path, paths=[file1, file2])
  3247. porcelain.commit(
  3248. self.repo.path,
  3249. message=b"First commit",
  3250. committer=b"Jane <jane@example.com>",
  3251. author=b"John <john@example.com>",
  3252. )
  3253. # Remove one file from subdirectory and commit
  3254. porcelain.rm(self.repo.path, paths=[file2])
  3255. sha2 = porcelain.commit(
  3256. self.repo.path,
  3257. message=b"Remove file2",
  3258. committer=b"Jane <jane@example.com>",
  3259. author=b"John <john@example.com>",
  3260. )
  3261. # Create file2 again (untracked)
  3262. with open(file2, "w") as f:
  3263. f.write("new content")
  3264. # Reset to commit that has file2 removed - untracked file2 should remain
  3265. porcelain.reset(self.repo, "hard", sha2)
  3266. self.assertTrue(os.path.exists(file1))
  3267. # Untracked files are not removed by reset --hard
  3268. self.assertTrue(os.path.exists(file2))
  3269. def test_hard_reset_to_remote_branch(self) -> None:
  3270. """Test reset --hard to remote branch deletes local files not in remote."""
  3271. # Create a file and commit
  3272. file1 = os.path.join(self.repo.path, "file1")
  3273. with open(file1, "w") as f:
  3274. f.write("content1")
  3275. porcelain.add(self.repo.path, paths=[file1])
  3276. sha1 = porcelain.commit(
  3277. self.repo.path,
  3278. message=b"Initial commit",
  3279. committer=b"Jane <jane@example.com>",
  3280. author=b"John <john@example.com>",
  3281. )
  3282. # Create a "remote" ref that doesn't have additional files
  3283. self.repo.refs[b"refs/remotes/origin/master"] = sha1
  3284. # Add another file locally and commit
  3285. file2 = os.path.join(self.repo.path, "file2")
  3286. with open(file2, "w") as f:
  3287. f.write("content2")
  3288. porcelain.add(self.repo.path, paths=[file2])
  3289. porcelain.commit(
  3290. self.repo.path,
  3291. message=b"Add file2",
  3292. committer=b"Jane <jane@example.com>",
  3293. author=b"John <john@example.com>",
  3294. )
  3295. # Both files should exist
  3296. self.assertTrue(os.path.exists(file1))
  3297. self.assertTrue(os.path.exists(file2))
  3298. # Reset to remote branch - should delete file2
  3299. porcelain.reset(self.repo, "hard", b"refs/remotes/origin/master")
  3300. # file1 should exist, file2 should be deleted
  3301. self.assertTrue(os.path.exists(file1))
  3302. self.assertFalse(os.path.exists(file2))
  3303. def test_mixed_reset(self) -> None:
  3304. # Create initial commit
  3305. fullpath = os.path.join(self.repo.path, "foo")
  3306. with open(fullpath, "w") as f:
  3307. f.write("BAR")
  3308. porcelain.add(self.repo.path, paths=[fullpath])
  3309. first_sha = porcelain.commit(
  3310. self.repo.path,
  3311. message=b"First commit",
  3312. committer=b"Jane <jane@example.com>",
  3313. author=b"John <john@example.com>",
  3314. )
  3315. # Make second commit with modified content
  3316. with open(fullpath, "w") as f:
  3317. f.write("BAZ")
  3318. porcelain.add(self.repo.path, paths=[fullpath])
  3319. porcelain.commit(
  3320. self.repo.path,
  3321. message=b"Second commit",
  3322. committer=b"Jane <jane@example.com>",
  3323. author=b"John <john@example.com>",
  3324. )
  3325. # Modify working tree without staging
  3326. with open(fullpath, "w") as f:
  3327. f.write("MODIFIED")
  3328. # Mixed reset to first commit
  3329. porcelain.reset(self.repo, "mixed", first_sha)
  3330. # Check that HEAD points to first commit
  3331. self.assertEqual(self.repo.head(), first_sha)
  3332. # Check that index matches first commit
  3333. index = self.repo.open_index()
  3334. changes = list(
  3335. tree_changes(
  3336. self.repo.object_store,
  3337. index.commit(self.repo.object_store),
  3338. self.repo[first_sha].tree,
  3339. )
  3340. )
  3341. self.assertEqual([], changes)
  3342. # Check that working tree is unchanged (still has "MODIFIED")
  3343. with open(fullpath) as f:
  3344. self.assertEqual(f.read(), "MODIFIED")
  3345. def test_soft_reset(self) -> None:
  3346. # Create initial commit
  3347. fullpath = os.path.join(self.repo.path, "foo")
  3348. with open(fullpath, "w") as f:
  3349. f.write("BAR")
  3350. porcelain.add(self.repo.path, paths=[fullpath])
  3351. first_sha = porcelain.commit(
  3352. self.repo.path,
  3353. message=b"First commit",
  3354. committer=b"Jane <jane@example.com>",
  3355. author=b"John <john@example.com>",
  3356. )
  3357. # Make second commit with modified content
  3358. with open(fullpath, "w") as f:
  3359. f.write("BAZ")
  3360. porcelain.add(self.repo.path, paths=[fullpath])
  3361. porcelain.commit(
  3362. self.repo.path,
  3363. message=b"Second commit",
  3364. committer=b"Jane <jane@example.com>",
  3365. author=b"John <john@example.com>",
  3366. )
  3367. # Stage a new change
  3368. with open(fullpath, "w") as f:
  3369. f.write("STAGED")
  3370. porcelain.add(self.repo.path, paths=[fullpath])
  3371. # Soft reset to first commit
  3372. porcelain.reset(self.repo, "soft", first_sha)
  3373. # Check that HEAD points to first commit
  3374. self.assertEqual(self.repo.head(), first_sha)
  3375. # Check that index still has the staged change (not reset)
  3376. index = self.repo.open_index()
  3377. # The index should still contain the staged content, not the first commit's content
  3378. self.assertIn(b"foo", index)
  3379. # Check that working tree is unchanged
  3380. with open(fullpath) as f:
  3381. self.assertEqual(f.read(), "STAGED")
  3382. class ResetFileTests(PorcelainTestCase):
  3383. def test_reset_modify_file_to_commit(self) -> None:
  3384. file = "foo"
  3385. full_path = os.path.join(self.repo.path, file)
  3386. with open(full_path, "w") as f:
  3387. f.write("hello")
  3388. porcelain.add(self.repo, paths=[full_path])
  3389. sha = porcelain.commit(
  3390. self.repo,
  3391. message=b"unitest",
  3392. committer=b"Jane <jane@example.com>",
  3393. author=b"John <john@example.com>",
  3394. )
  3395. with open(full_path, "a") as f:
  3396. f.write("something new")
  3397. porcelain.reset_file(self.repo, file, target=sha)
  3398. with open(full_path) as f:
  3399. self.assertEqual("hello", f.read())
  3400. def test_reset_remove_file_to_commit(self) -> None:
  3401. file = "foo"
  3402. full_path = os.path.join(self.repo.path, file)
  3403. with open(full_path, "w") as f:
  3404. f.write("hello")
  3405. porcelain.add(self.repo, paths=[full_path])
  3406. sha = porcelain.commit(
  3407. self.repo,
  3408. message=b"unitest",
  3409. committer=b"Jane <jane@example.com>",
  3410. author=b"John <john@example.com>",
  3411. )
  3412. os.remove(full_path)
  3413. porcelain.reset_file(self.repo, file, target=sha)
  3414. with open(full_path) as f:
  3415. self.assertEqual("hello", f.read())
  3416. def test_resetfile_with_dir(self) -> None:
  3417. os.mkdir(os.path.join(self.repo.path, "new_dir"))
  3418. full_path = os.path.join(self.repo.path, "new_dir", "foo")
  3419. with open(full_path, "w") as f:
  3420. f.write("hello")
  3421. porcelain.add(self.repo, paths=[full_path])
  3422. sha = porcelain.commit(
  3423. self.repo,
  3424. message=b"unitest",
  3425. committer=b"Jane <jane@example.com>",
  3426. author=b"John <john@example.com>",
  3427. )
  3428. with open(full_path, "a") as f:
  3429. f.write("something new")
  3430. porcelain.commit(
  3431. self.repo,
  3432. message=b"unitest 2",
  3433. committer=b"Jane <jane@example.com>",
  3434. author=b"John <john@example.com>",
  3435. )
  3436. porcelain.reset_file(self.repo, os.path.join("new_dir", "foo"), target=sha)
  3437. with open(full_path) as f:
  3438. self.assertEqual("hello", f.read())
  3439. def _commit_file_with_content(repo, filename, content):
  3440. file_path = os.path.join(repo.path, filename)
  3441. with open(file_path, "w") as f:
  3442. f.write(content)
  3443. porcelain.add(repo, paths=[file_path])
  3444. sha = porcelain.commit(
  3445. repo,
  3446. message=b"add " + filename.encode(),
  3447. committer=b"Jane <jane@example.com>",
  3448. author=b"John <john@example.com>",
  3449. )
  3450. return sha, file_path
  3451. class RevertTests(PorcelainTestCase):
  3452. def test_revert_simple(self) -> None:
  3453. # Create initial commit
  3454. fullpath = os.path.join(self.repo.path, "foo")
  3455. with open(fullpath, "w") as f:
  3456. f.write("initial content\n")
  3457. porcelain.add(self.repo.path, paths=[fullpath])
  3458. porcelain.commit(
  3459. self.repo.path,
  3460. message=b"Initial commit",
  3461. committer=b"Jane <jane@example.com>",
  3462. author=b"John <john@example.com>",
  3463. )
  3464. # Make a change
  3465. with open(fullpath, "w") as f:
  3466. f.write("modified content\n")
  3467. porcelain.add(self.repo.path, paths=[fullpath])
  3468. change_sha = porcelain.commit(
  3469. self.repo.path,
  3470. message=b"Change content",
  3471. committer=b"Jane <jane@example.com>",
  3472. author=b"John <john@example.com>",
  3473. )
  3474. # Revert the change
  3475. revert_sha = porcelain.revert(self.repo.path, commits=[change_sha])
  3476. # Check the file content is back to initial
  3477. with open(fullpath) as f:
  3478. self.assertEqual("initial content\n", f.read())
  3479. # Check the revert commit message
  3480. revert_commit = self.repo[revert_sha]
  3481. self.assertIn(b'Revert "Change content"', revert_commit.message)
  3482. self.assertIn(change_sha[:7], revert_commit.message)
  3483. def test_revert_multiple(self) -> None:
  3484. # Create initial commit
  3485. fullpath = os.path.join(self.repo.path, "foo")
  3486. with open(fullpath, "w") as f:
  3487. f.write("line1\n")
  3488. porcelain.add(self.repo.path, paths=[fullpath])
  3489. porcelain.commit(
  3490. self.repo.path,
  3491. message=b"Initial commit",
  3492. committer=b"Jane <jane@example.com>",
  3493. author=b"John <john@example.com>",
  3494. )
  3495. # Add line2
  3496. with open(fullpath, "a") as f:
  3497. f.write("line2\n")
  3498. porcelain.add(self.repo.path, paths=[fullpath])
  3499. commit1 = porcelain.commit(
  3500. self.repo.path,
  3501. message=b"Add line2",
  3502. committer=b"Jane <jane@example.com>",
  3503. author=b"John <john@example.com>",
  3504. )
  3505. # Add line3
  3506. with open(fullpath, "a") as f:
  3507. f.write("line3\n")
  3508. porcelain.add(self.repo.path, paths=[fullpath])
  3509. commit2 = porcelain.commit(
  3510. self.repo.path,
  3511. message=b"Add line3",
  3512. committer=b"Jane <jane@example.com>",
  3513. author=b"John <john@example.com>",
  3514. )
  3515. # Revert both commits (in reverse order)
  3516. porcelain.revert(self.repo.path, commits=[commit2, commit1])
  3517. # Check file is back to initial state
  3518. with open(fullpath) as f:
  3519. self.assertEqual("line1\n", f.read())
  3520. def test_revert_no_commit(self) -> None:
  3521. # Create initial commit
  3522. fullpath = os.path.join(self.repo.path, "foo")
  3523. with open(fullpath, "w") as f:
  3524. f.write("initial\n")
  3525. porcelain.add(self.repo.path, paths=[fullpath])
  3526. porcelain.commit(
  3527. self.repo.path,
  3528. message=b"Initial",
  3529. committer=b"Jane <jane@example.com>",
  3530. author=b"John <john@example.com>",
  3531. )
  3532. # Make a change
  3533. with open(fullpath, "w") as f:
  3534. f.write("changed\n")
  3535. porcelain.add(self.repo.path, paths=[fullpath])
  3536. change_sha = porcelain.commit(
  3537. self.repo.path,
  3538. message=b"Change",
  3539. committer=b"Jane <jane@example.com>",
  3540. author=b"John <john@example.com>",
  3541. )
  3542. # Revert with no_commit
  3543. result = porcelain.revert(self.repo.path, commits=[change_sha], no_commit=True)
  3544. # Should return None
  3545. self.assertIsNone(result)
  3546. # File should be reverted
  3547. with open(fullpath) as f:
  3548. self.assertEqual("initial\n", f.read())
  3549. # HEAD should still point to the change commit
  3550. self.assertEqual(self.repo.refs[b"HEAD"], change_sha)
  3551. def test_revert_custom_message(self) -> None:
  3552. # Create commits
  3553. fullpath = os.path.join(self.repo.path, "foo")
  3554. with open(fullpath, "w") as f:
  3555. f.write("initial\n")
  3556. porcelain.add(self.repo.path, paths=[fullpath])
  3557. porcelain.commit(
  3558. self.repo.path,
  3559. message=b"Initial",
  3560. committer=b"Jane <jane@example.com>",
  3561. author=b"John <john@example.com>",
  3562. )
  3563. with open(fullpath, "w") as f:
  3564. f.write("changed\n")
  3565. porcelain.add(self.repo.path, paths=[fullpath])
  3566. change_sha = porcelain.commit(
  3567. self.repo.path,
  3568. message=b"Change",
  3569. committer=b"Jane <jane@example.com>",
  3570. author=b"John <john@example.com>",
  3571. )
  3572. # Revert with custom message
  3573. custom_msg = "Custom revert message"
  3574. revert_sha = porcelain.revert(
  3575. self.repo.path, commits=[change_sha], message=custom_msg
  3576. )
  3577. # Check the message
  3578. revert_commit = self.repo[revert_sha]
  3579. self.assertEqual(custom_msg.encode("utf-8"), revert_commit.message)
  3580. def test_revert_no_parent(self) -> None:
  3581. # Try to revert the initial commit (no parent)
  3582. fullpath = os.path.join(self.repo.path, "foo")
  3583. with open(fullpath, "w") as f:
  3584. f.write("content\n")
  3585. porcelain.add(self.repo.path, paths=[fullpath])
  3586. initial_sha = porcelain.commit(
  3587. self.repo.path,
  3588. message=b"Initial",
  3589. committer=b"Jane <jane@example.com>",
  3590. author=b"John <john@example.com>",
  3591. )
  3592. # Should raise an error
  3593. with self.assertRaises(porcelain.Error) as cm:
  3594. porcelain.revert(self.repo.path, commits=[initial_sha])
  3595. self.assertIn("no parents", str(cm.exception))
  3596. class CheckoutTests(PorcelainTestCase):
  3597. def setUp(self) -> None:
  3598. super().setUp()
  3599. self._sha, self._foo_path = _commit_file_with_content(
  3600. self.repo, "foo", "hello\n"
  3601. )
  3602. porcelain.branch_create(self.repo, "uni")
  3603. def test_checkout_to_existing_branch(self) -> None:
  3604. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3605. porcelain.checkout(self.repo, b"uni")
  3606. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3607. def test_checkout_to_non_existing_branch(self) -> None:
  3608. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3609. with self.assertRaises(KeyError):
  3610. porcelain.checkout(self.repo, b"bob")
  3611. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3612. def test_checkout_to_branch_with_modified_files(self) -> None:
  3613. with open(self._foo_path, "a") as f:
  3614. f.write("new message\n")
  3615. porcelain.add(self.repo, paths=[self._foo_path])
  3616. status = list(porcelain.status(self.repo))
  3617. self.assertEqual(
  3618. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  3619. )
  3620. # The new checkout behavior prevents switching with staged changes
  3621. with self.assertRaises(porcelain.CheckoutError):
  3622. porcelain.checkout(self.repo, b"uni")
  3623. # Should still be on master
  3624. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3625. # Force checkout should work
  3626. porcelain.checkout(self.repo, b"uni", force=True)
  3627. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3628. def test_checkout_with_deleted_files(self) -> None:
  3629. porcelain.remove(self.repo.path, [os.path.join(self.repo.path, "foo")])
  3630. status = list(porcelain.status(self.repo))
  3631. self.assertEqual(
  3632. [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status
  3633. )
  3634. # The new checkout behavior prevents switching with staged deletions
  3635. with self.assertRaises(porcelain.CheckoutError):
  3636. porcelain.checkout(self.repo, b"uni")
  3637. # Should still be on master
  3638. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3639. # Force checkout should work
  3640. porcelain.checkout(self.repo, b"uni", force=True)
  3641. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3642. def test_checkout_to_branch_with_added_files(self) -> None:
  3643. file_path = os.path.join(self.repo.path, "bar")
  3644. with open(file_path, "w") as f:
  3645. f.write("bar content\n")
  3646. porcelain.add(self.repo, paths=[file_path])
  3647. status = list(porcelain.status(self.repo))
  3648. self.assertEqual(
  3649. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3650. )
  3651. # Both branches have file 'foo' checkout should be fine.
  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(
  3656. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3657. )
  3658. def test_checkout_to_branch_with_modified_file_not_present(self) -> None:
  3659. # Commit a new file that the other branch doesn't have.
  3660. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3661. # Modify the file the other branch doesn't have.
  3662. with open(nee_path, "a") as f:
  3663. f.write("bar content\n")
  3664. porcelain.add(self.repo, paths=[nee_path])
  3665. status = list(porcelain.status(self.repo))
  3666. self.assertEqual(
  3667. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3668. )
  3669. # Checkout should fail when there are staged changes that would be lost
  3670. # This matches Git's behavior to prevent data loss
  3671. from dulwich.errors import WorkingTreeModifiedError
  3672. with self.assertRaises(WorkingTreeModifiedError) as cm:
  3673. porcelain.checkout(self.repo, b"uni")
  3674. self.assertIn("nee", str(cm.exception))
  3675. # Should still be on master branch
  3676. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3677. # The staged changes should still be present
  3678. status = list(porcelain.status(self.repo))
  3679. self.assertEqual(
  3680. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3681. )
  3682. self.assertTrue(os.path.exists(nee_path))
  3683. # Force checkout should work and lose the changes
  3684. porcelain.checkout(self.repo, b"uni", force=True)
  3685. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3686. # Now the file should be gone
  3687. self.assertFalse(os.path.exists(nee_path))
  3688. def test_checkout_to_branch_with_modified_file_not_present_forced(self) -> None:
  3689. # Commit a new file that the other branch doesn't have.
  3690. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3691. # Modify the file the other branch doesn't have.
  3692. with open(nee_path, "a") as f:
  3693. f.write("bar content\n")
  3694. porcelain.add(self.repo, paths=[nee_path])
  3695. status = list(porcelain.status(self.repo))
  3696. self.assertEqual(
  3697. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3698. )
  3699. # 'uni' branch doesn't have 'nee' and it has been modified, but we force to reset the entire index.
  3700. porcelain.checkout(self.repo, b"uni", force=True)
  3701. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3702. status = list(porcelain.status(self.repo))
  3703. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3704. def test_checkout_to_branch_with_unstaged_files(self) -> None:
  3705. # Edit `foo`.
  3706. with open(self._foo_path, "a") as f:
  3707. f.write("new message")
  3708. status = list(porcelain.status(self.repo))
  3709. self.assertEqual(
  3710. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  3711. )
  3712. # The new checkout behavior prevents switching with unstaged changes
  3713. with self.assertRaises(porcelain.CheckoutError):
  3714. porcelain.checkout(self.repo, b"uni")
  3715. # Should still be on master
  3716. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3717. # Force checkout should work
  3718. porcelain.checkout(self.repo, b"uni", force=True)
  3719. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3720. def test_checkout_to_branch_with_untracked_files(self) -> None:
  3721. with open(os.path.join(self.repo.path, "neu"), "a") as f:
  3722. f.write("new message\n")
  3723. status = list(porcelain.status(self.repo))
  3724. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3725. porcelain.checkout(self.repo, b"uni")
  3726. status = list(porcelain.status(self.repo))
  3727. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3728. def test_checkout_to_branch_with_new_files(self) -> None:
  3729. porcelain.checkout(self.repo, b"uni")
  3730. sub_directory = os.path.join(self.repo.path, "sub1")
  3731. os.mkdir(sub_directory)
  3732. for index in range(5):
  3733. _commit_file_with_content(
  3734. self.repo, "new_file_" + str(index + 1), "Some content\n"
  3735. )
  3736. _commit_file_with_content(
  3737. self.repo,
  3738. os.path.join("sub1", "new_file_" + str(index + 10)),
  3739. "Good content\n",
  3740. )
  3741. status = list(porcelain.status(self.repo))
  3742. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3743. porcelain.checkout(self.repo, b"master")
  3744. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3745. status = list(porcelain.status(self.repo))
  3746. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3747. porcelain.checkout(self.repo, b"uni")
  3748. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3749. status = list(porcelain.status(self.repo))
  3750. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3751. def test_checkout_to_branch_with_file_in_sub_directory(self) -> None:
  3752. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3753. os.makedirs(sub_directory)
  3754. sub_directory_file = os.path.join(sub_directory, "neu")
  3755. with open(sub_directory_file, "w") as f:
  3756. f.write("new message\n")
  3757. porcelain.add(self.repo, paths=[sub_directory_file])
  3758. porcelain.commit(
  3759. self.repo,
  3760. message=b"add " + sub_directory_file.encode(),
  3761. committer=b"Jane <jane@example.com>",
  3762. author=b"John <john@example.com>",
  3763. )
  3764. status = list(porcelain.status(self.repo))
  3765. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3766. self.assertTrue(os.path.isdir(sub_directory))
  3767. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3768. porcelain.checkout(self.repo, b"uni")
  3769. status = list(porcelain.status(self.repo))
  3770. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3771. self.assertFalse(os.path.isdir(sub_directory))
  3772. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3773. porcelain.checkout(self.repo, b"master")
  3774. self.assertTrue(os.path.isdir(sub_directory))
  3775. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3776. def test_checkout_to_branch_with_multiple_files_in_sub_directory(self) -> None:
  3777. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3778. os.makedirs(sub_directory)
  3779. sub_directory_file_1 = os.path.join(sub_directory, "neu")
  3780. with open(sub_directory_file_1, "w") as f:
  3781. f.write("new message\n")
  3782. sub_directory_file_2 = os.path.join(sub_directory, "gus")
  3783. with open(sub_directory_file_2, "w") as f:
  3784. f.write("alternative message\n")
  3785. porcelain.add(self.repo, paths=[sub_directory_file_1, sub_directory_file_2])
  3786. porcelain.commit(
  3787. self.repo,
  3788. message=b"add files neu and gus.",
  3789. committer=b"Jane <jane@example.com>",
  3790. author=b"John <john@example.com>",
  3791. )
  3792. status = list(porcelain.status(self.repo))
  3793. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3794. self.assertTrue(os.path.isdir(sub_directory))
  3795. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3796. porcelain.checkout(self.repo, b"uni")
  3797. status = list(porcelain.status(self.repo))
  3798. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3799. self.assertFalse(os.path.isdir(sub_directory))
  3800. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3801. def _commit_something_wrong(self):
  3802. with open(self._foo_path, "a") as f:
  3803. f.write("something wrong")
  3804. porcelain.add(self.repo, paths=[self._foo_path])
  3805. return porcelain.commit(
  3806. self.repo,
  3807. message=b"I may added something wrong",
  3808. committer=b"Jane <jane@example.com>",
  3809. author=b"John <john@example.com>",
  3810. )
  3811. def test_checkout_to_commit_sha(self) -> None:
  3812. self._commit_something_wrong()
  3813. porcelain.checkout(self.repo, self._sha)
  3814. self.assertEqual(self._sha, self.repo.head())
  3815. def test_checkout_to_head(self) -> None:
  3816. new_sha = self._commit_something_wrong()
  3817. porcelain.checkout(self.repo, b"HEAD")
  3818. self.assertEqual(new_sha, self.repo.head())
  3819. def _checkout_remote_branch(self):
  3820. errstream = BytesIO()
  3821. outstream = BytesIO()
  3822. porcelain.commit(
  3823. repo=self.repo.path,
  3824. message=b"init",
  3825. author=b"author <email>",
  3826. committer=b"committer <email>",
  3827. )
  3828. # Setup target repo cloned from temp test repo
  3829. clone_path = tempfile.mkdtemp()
  3830. self.addCleanup(shutil.rmtree, clone_path)
  3831. target_repo = porcelain.clone(
  3832. self.repo.path, target=clone_path, errstream=errstream
  3833. )
  3834. self.addCleanup(target_repo.close)
  3835. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  3836. # create a second file to be pushed back to origin
  3837. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3838. os.close(handle)
  3839. porcelain.add(repo=clone_path, paths=[fullpath])
  3840. porcelain.commit(
  3841. repo=clone_path,
  3842. message=b"push",
  3843. author=b"author <email>",
  3844. committer=b"committer <email>",
  3845. )
  3846. # Setup a non-checked out branch in the remote
  3847. refs_path = b"refs/heads/foo"
  3848. new_id = self.repo[b"HEAD"].id
  3849. self.assertNotEqual(new_id, ZERO_SHA)
  3850. self.repo.refs[refs_path] = new_id
  3851. # Push to the remote
  3852. porcelain.push(
  3853. clone_path,
  3854. "origin",
  3855. b"HEAD:" + refs_path,
  3856. outstream=outstream,
  3857. errstream=errstream,
  3858. )
  3859. self.assertEqual(
  3860. target_repo.refs[b"refs/remotes/origin/foo"],
  3861. target_repo.refs[b"HEAD"],
  3862. )
  3863. # The new checkout behavior treats origin/foo as a ref and creates detached HEAD
  3864. porcelain.checkout(target_repo, b"origin/foo")
  3865. original_id = target_repo[b"HEAD"].id
  3866. uni_id = target_repo[b"refs/remotes/origin/uni"].id
  3867. # Should be in detached HEAD state
  3868. with self.assertRaises((ValueError, IndexError)):
  3869. porcelain.active_branch(target_repo)
  3870. expected_refs = {
  3871. b"HEAD": original_id,
  3872. b"refs/heads/master": original_id,
  3873. # No local foo branch is created anymore
  3874. b"refs/remotes/origin/foo": original_id,
  3875. b"refs/remotes/origin/uni": uni_id,
  3876. b"refs/remotes/origin/HEAD": new_id,
  3877. b"refs/remotes/origin/master": new_id,
  3878. }
  3879. self.assertEqual(expected_refs, target_repo.get_refs())
  3880. return target_repo
  3881. def test_checkout_remote_branch(self) -> None:
  3882. repo = self._checkout_remote_branch()
  3883. repo.close()
  3884. def test_checkout_remote_branch_then_master_then_remote_branch_again(self) -> None:
  3885. target_repo = self._checkout_remote_branch()
  3886. # Should be in detached HEAD state
  3887. with self.assertRaises((ValueError, IndexError)):
  3888. porcelain.active_branch(target_repo)
  3889. # Save the commit SHA before adding bar
  3890. detached_commit_sha, _ = _commit_file_with_content(
  3891. target_repo, "bar", "something\n"
  3892. )
  3893. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3894. porcelain.checkout(target_repo, b"master")
  3895. self.assertEqual(b"master", porcelain.active_branch(target_repo))
  3896. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3897. # Going back to origin/foo won't have bar because the commit was made in detached state
  3898. porcelain.checkout(target_repo, b"origin/foo")
  3899. # Should be in detached HEAD state again
  3900. with self.assertRaises((ValueError, IndexError)):
  3901. porcelain.active_branch(target_repo)
  3902. # bar is NOT there because we're back at the original origin/foo commit
  3903. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3904. # But we can checkout the specific commit to get bar back
  3905. porcelain.checkout(target_repo, detached_commit_sha.decode())
  3906. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3907. target_repo.close()
  3908. def test_checkout_new_branch_from_remote_sets_tracking(self) -> None:
  3909. # Create a "remote" repository
  3910. remote_path = tempfile.mkdtemp()
  3911. self.addCleanup(shutil.rmtree, remote_path)
  3912. remote_repo = porcelain.init(remote_path)
  3913. # Add a commit to the remote
  3914. remote_sha, _ = _commit_file_with_content(
  3915. remote_repo, "bar", "remote content\n"
  3916. )
  3917. # Clone the remote repository
  3918. target_path = tempfile.mkdtemp()
  3919. self.addCleanup(shutil.rmtree, target_path)
  3920. target_repo = porcelain.clone(remote_path, target_path)
  3921. self.addCleanup(target_repo.close)
  3922. # Create a remote tracking branch reference
  3923. remote_branch_ref = b"refs/remotes/origin/feature"
  3924. target_repo.refs[remote_branch_ref] = remote_sha
  3925. # Checkout a new branch from the remote branch
  3926. porcelain.checkout(target_repo, remote_branch_ref, new_branch=b"local-feature")
  3927. # Verify the branch was created and is active
  3928. self.assertEqual(b"local-feature", porcelain.active_branch(target_repo))
  3929. # Verify tracking configuration was set
  3930. config = target_repo.get_config()
  3931. self.assertEqual(
  3932. b"origin", config.get((b"branch", b"local-feature"), b"remote")
  3933. )
  3934. self.assertEqual(
  3935. b"refs/heads/feature", config.get((b"branch", b"local-feature"), b"merge")
  3936. )
  3937. target_repo.close()
  3938. remote_repo.close()
  3939. class RestoreTests(PorcelainTestCase):
  3940. """Tests for the restore command."""
  3941. def setUp(self) -> None:
  3942. super().setUp()
  3943. self._sha, self._foo_path = _commit_file_with_content(
  3944. self.repo, "foo", "original\n"
  3945. )
  3946. def test_restore_worktree_from_index(self) -> None:
  3947. # Modify the working tree file
  3948. with open(self._foo_path, "w") as f:
  3949. f.write("modified\n")
  3950. # Restore from index (should restore to original)
  3951. porcelain.restore(self.repo, paths=["foo"])
  3952. with open(self._foo_path) as f:
  3953. content = f.read()
  3954. self.assertEqual("original\n", content)
  3955. def test_restore_worktree_from_head(self) -> None:
  3956. # Modify and stage the file
  3957. with open(self._foo_path, "w") as f:
  3958. f.write("staged\n")
  3959. porcelain.add(self.repo, paths=[self._foo_path])
  3960. # Now modify it again in worktree
  3961. with open(self._foo_path, "w") as f:
  3962. f.write("worktree\n")
  3963. # Restore from HEAD (should restore to original, not staged)
  3964. porcelain.restore(self.repo, paths=["foo"], source="HEAD")
  3965. with open(self._foo_path) as f:
  3966. content = f.read()
  3967. self.assertEqual("original\n", content)
  3968. def test_restore_staged_from_head(self) -> None:
  3969. # Modify and stage the file
  3970. with open(self._foo_path, "w") as f:
  3971. f.write("staged\n")
  3972. porcelain.add(self.repo, paths=[self._foo_path])
  3973. # Verify it's staged
  3974. status = list(porcelain.status(self.repo))
  3975. self.assertEqual(
  3976. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  3977. )
  3978. # Restore staged from HEAD
  3979. porcelain.restore(self.repo, paths=["foo"], staged=True, worktree=False)
  3980. # Verify it's no longer staged
  3981. status = list(porcelain.status(self.repo))
  3982. # Now it should show as unstaged modification
  3983. self.assertEqual(
  3984. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  3985. )
  3986. def test_restore_both_staged_and_worktree(self) -> None:
  3987. # Modify and stage the file
  3988. with open(self._foo_path, "w") as f:
  3989. f.write("staged\n")
  3990. porcelain.add(self.repo, paths=[self._foo_path])
  3991. # Now modify it again in worktree
  3992. with open(self._foo_path, "w") as f:
  3993. f.write("worktree\n")
  3994. # Restore both from HEAD
  3995. porcelain.restore(self.repo, paths=["foo"], staged=True, worktree=True)
  3996. # Verify content is restored
  3997. with open(self._foo_path) as f:
  3998. content = f.read()
  3999. self.assertEqual("original\n", content)
  4000. # Verify nothing is staged
  4001. status = list(porcelain.status(self.repo))
  4002. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  4003. def test_restore_nonexistent_path(self) -> None:
  4004. with self.assertRaises(porcelain.CheckoutError):
  4005. porcelain.restore(self.repo, paths=["nonexistent"])
  4006. class SwitchTests(PorcelainTestCase):
  4007. """Tests for the switch command."""
  4008. def setUp(self) -> None:
  4009. super().setUp()
  4010. self._sha, self._foo_path = _commit_file_with_content(
  4011. self.repo, "foo", "hello\n"
  4012. )
  4013. porcelain.branch_create(self.repo, "dev")
  4014. def test_switch_to_existing_branch(self) -> None:
  4015. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4016. porcelain.switch(self.repo, "dev")
  4017. self.assertEqual(b"dev", porcelain.active_branch(self.repo))
  4018. def test_switch_to_non_existing_branch(self) -> None:
  4019. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4020. with self.assertRaises(KeyError):
  4021. porcelain.switch(self.repo, "nonexistent")
  4022. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4023. def test_switch_with_create(self) -> None:
  4024. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4025. porcelain.switch(self.repo, "master", create="feature")
  4026. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4027. def test_switch_with_detach(self) -> None:
  4028. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4029. porcelain.switch(self.repo, self._sha.decode(), detach=True)
  4030. # In detached HEAD state, active_branch raises IndexError
  4031. with self.assertRaises(IndexError):
  4032. porcelain.active_branch(self.repo)
  4033. def test_switch_with_uncommitted_changes(self) -> None:
  4034. # Modify the file
  4035. with open(self._foo_path, "a") as f:
  4036. f.write("new content\n")
  4037. porcelain.add(self.repo, paths=[self._foo_path])
  4038. # Switch should fail due to uncommitted changes
  4039. with self.assertRaises(porcelain.CheckoutError):
  4040. porcelain.switch(self.repo, "dev")
  4041. # Should still be on master
  4042. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4043. def test_switch_with_force(self) -> None:
  4044. # Modify the file
  4045. with open(self._foo_path, "a") as f:
  4046. f.write("new content\n")
  4047. porcelain.add(self.repo, paths=[self._foo_path])
  4048. # Force switch should work
  4049. porcelain.switch(self.repo, "dev", force=True)
  4050. self.assertEqual(b"dev", porcelain.active_branch(self.repo))
  4051. def test_switch_to_commit_without_detach(self) -> None:
  4052. # Switching to a commit SHA without --detach should fail
  4053. with self.assertRaises(porcelain.CheckoutError):
  4054. porcelain.switch(self.repo, self._sha.decode())
  4055. class GeneralCheckoutTests(PorcelainTestCase):
  4056. """Tests for the general checkout function that handles branches, tags, and commits."""
  4057. def setUp(self) -> None:
  4058. super().setUp()
  4059. # Create initial commit
  4060. self._sha1, self._foo_path = _commit_file_with_content(
  4061. self.repo, "foo", "initial content\n"
  4062. )
  4063. # Create a branch
  4064. porcelain.branch_create(self.repo, "feature")
  4065. # Create another commit on master
  4066. self._sha2, self._bar_path = _commit_file_with_content(
  4067. self.repo, "bar", "bar content\n"
  4068. )
  4069. # Create a tag
  4070. porcelain.tag_create(self.repo, "v1.0", objectish=self._sha1)
  4071. def test_checkout_branch(self) -> None:
  4072. """Test checking out a branch."""
  4073. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4074. # Checkout feature branch
  4075. porcelain.checkout(self.repo, "feature")
  4076. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4077. # File 'bar' should not exist in feature branch
  4078. self.assertFalse(os.path.exists(self._bar_path))
  4079. # Go back to master
  4080. porcelain.checkout(self.repo, "master")
  4081. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4082. # File 'bar' should exist again
  4083. self.assertTrue(os.path.exists(self._bar_path))
  4084. def test_checkout_commit(self) -> None:
  4085. """Test checking out a specific commit (detached HEAD)."""
  4086. # Checkout first commit by SHA
  4087. porcelain.checkout(self.repo, self._sha1.decode("ascii"))
  4088. # Should be in detached HEAD state - active_branch raises IndexError
  4089. with self.assertRaises((ValueError, IndexError)):
  4090. porcelain.active_branch(self.repo)
  4091. # File 'bar' should not exist
  4092. self.assertFalse(os.path.exists(self._bar_path))
  4093. # HEAD should point to the commit
  4094. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  4095. def test_checkout_tag(self) -> None:
  4096. """Test checking out a tag (detached HEAD)."""
  4097. # Checkout tag
  4098. porcelain.checkout(self.repo, "v1.0")
  4099. # Should be in detached HEAD state - active_branch raises IndexError
  4100. with self.assertRaises((ValueError, IndexError)):
  4101. porcelain.active_branch(self.repo)
  4102. # File 'bar' should not exist (tag points to first commit)
  4103. self.assertFalse(os.path.exists(self._bar_path))
  4104. # HEAD should point to the tagged commit
  4105. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  4106. def test_checkout_new_branch(self) -> None:
  4107. """Test creating a new branch during checkout (like git checkout -b)."""
  4108. # Create and checkout new branch from current HEAD
  4109. porcelain.checkout(self.repo, "master", new_branch="new-feature")
  4110. self.assertEqual(b"new-feature", porcelain.active_branch(self.repo))
  4111. self.assertTrue(os.path.exists(self._bar_path))
  4112. # Create and checkout new branch from specific commit
  4113. porcelain.checkout(self.repo, self._sha1.decode("ascii"), new_branch="from-old")
  4114. self.assertEqual(b"from-old", porcelain.active_branch(self.repo))
  4115. self.assertFalse(os.path.exists(self._bar_path))
  4116. def test_checkout_with_uncommitted_changes(self) -> None:
  4117. """Test checkout behavior with uncommitted changes."""
  4118. # Modify a file
  4119. with open(self._foo_path, "w") as f:
  4120. f.write("modified content\n")
  4121. # Should raise error when trying to checkout
  4122. with self.assertRaises(porcelain.CheckoutError) as cm:
  4123. porcelain.checkout(self.repo, "feature")
  4124. self.assertIn("local changes", str(cm.exception))
  4125. self.assertIn("foo", str(cm.exception))
  4126. # Should still be on master
  4127. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4128. def test_checkout_force(self) -> None:
  4129. """Test forced checkout discards local changes for files that differ between branches."""
  4130. # Modify a file
  4131. with open(self._foo_path, "w") as f:
  4132. f.write("modified content\n")
  4133. # Force checkout should succeed
  4134. porcelain.checkout(self.repo, "feature", force=True)
  4135. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4136. # Since foo has the same content in master and feature branches,
  4137. # checkout should NOT restore it - the modified content should remain
  4138. with open(self._foo_path) as f:
  4139. content = f.read()
  4140. self.assertEqual("modified content\n", content)
  4141. def test_checkout_nonexistent_ref(self) -> None:
  4142. """Test checkout of non-existent branch/commit."""
  4143. with self.assertRaises(KeyError):
  4144. porcelain.checkout(self.repo, "nonexistent")
  4145. def test_checkout_partial_sha(self) -> None:
  4146. """Test checkout with partial SHA."""
  4147. # Git typically allows checkout with partial SHA
  4148. partial_sha = self._sha1.decode("ascii")[:7]
  4149. porcelain.checkout(self.repo, partial_sha)
  4150. # Should be in detached HEAD state at the right commit
  4151. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  4152. def test_checkout_preserves_untracked_files(self) -> None:
  4153. """Test that checkout preserves untracked files."""
  4154. # Create an untracked file
  4155. untracked_path = os.path.join(self.repo.path, "untracked.txt")
  4156. with open(untracked_path, "w") as f:
  4157. f.write("untracked content\n")
  4158. # Checkout another branch
  4159. porcelain.checkout(self.repo, "feature")
  4160. # Untracked file should still exist
  4161. self.assertTrue(os.path.exists(untracked_path))
  4162. with open(untracked_path) as f:
  4163. content = f.read()
  4164. self.assertEqual("untracked content\n", content)
  4165. def test_checkout_full_ref_paths(self) -> None:
  4166. """Test checkout with full ref paths."""
  4167. # Test checkout with full branch ref path
  4168. porcelain.checkout(self.repo, "refs/heads/feature")
  4169. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4170. # Test checkout with full tag ref path
  4171. porcelain.checkout(self.repo, "refs/tags/v1.0")
  4172. # Should be in detached HEAD state
  4173. with self.assertRaises((ValueError, IndexError)):
  4174. porcelain.active_branch(self.repo)
  4175. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  4176. def test_checkout_bytes_vs_string_target(self) -> None:
  4177. """Test that checkout works with both bytes and string targets."""
  4178. # Test with string target
  4179. porcelain.checkout(self.repo, "feature")
  4180. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4181. # Test with bytes target
  4182. porcelain.checkout(self.repo, b"master")
  4183. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4184. def test_checkout_new_branch_from_commit(self) -> None:
  4185. """Test creating a new branch from a specific commit."""
  4186. # Create new branch from first commit
  4187. porcelain.checkout(self.repo, self._sha1.decode(), new_branch="from-commit")
  4188. self.assertEqual(b"from-commit", porcelain.active_branch(self.repo))
  4189. # Should be at the first commit (no bar file)
  4190. self.assertFalse(os.path.exists(self._bar_path))
  4191. def test_checkout_with_staged_addition(self) -> None:
  4192. """Test checkout behavior with staged file additions."""
  4193. # Create and stage a new file that doesn't exist in target branch
  4194. new_file_path = os.path.join(self.repo.path, "new.txt")
  4195. with open(new_file_path, "w") as f:
  4196. f.write("new file content\n")
  4197. porcelain.add(self.repo, [new_file_path])
  4198. # This should succeed because the file doesn't exist in target branch
  4199. porcelain.checkout(self.repo, "feature")
  4200. # Should be on feature branch
  4201. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  4202. # The new file should still exist and be staged
  4203. self.assertTrue(os.path.exists(new_file_path))
  4204. status = porcelain.status(self.repo)
  4205. self.assertIn(b"new.txt", status.staged["add"])
  4206. def test_checkout_with_staged_modification_conflict(self) -> None:
  4207. """Test checkout behavior with staged modifications that would conflict."""
  4208. # Stage changes to a file that exists in both branches
  4209. with open(self._foo_path, "w") as f:
  4210. f.write("modified content\n")
  4211. porcelain.add(self.repo, [self._foo_path])
  4212. # Should prevent checkout due to staged changes to existing file
  4213. with self.assertRaises(porcelain.CheckoutError) as cm:
  4214. porcelain.checkout(self.repo, "feature")
  4215. self.assertIn("local changes", str(cm.exception))
  4216. self.assertIn("foo", str(cm.exception))
  4217. def test_checkout_head_reference(self) -> None:
  4218. """Test checkout of HEAD reference."""
  4219. # Move to feature branch first
  4220. porcelain.checkout(self.repo, "feature")
  4221. # Checkout HEAD creates detached HEAD state
  4222. porcelain.checkout(self.repo, "HEAD")
  4223. # Should be in detached HEAD state
  4224. with self.assertRaises((ValueError, IndexError)):
  4225. porcelain.active_branch(self.repo)
  4226. def test_checkout_error_messages(self) -> None:
  4227. """Test that checkout error messages are helpful."""
  4228. # Create uncommitted changes
  4229. with open(self._foo_path, "w") as f:
  4230. f.write("uncommitted changes\n")
  4231. # Try to checkout
  4232. with self.assertRaises(porcelain.CheckoutError) as cm:
  4233. porcelain.checkout(self.repo, "feature")
  4234. error_msg = str(cm.exception)
  4235. self.assertIn("local changes", error_msg)
  4236. self.assertIn("foo", error_msg)
  4237. self.assertIn("overwritten", error_msg)
  4238. self.assertIn("commit or stash", error_msg)
  4239. class SubmoduleTests(PorcelainTestCase):
  4240. def test_empty(self) -> None:
  4241. porcelain.commit(
  4242. repo=self.repo.path,
  4243. message=b"init",
  4244. author=b"author <email>",
  4245. committer=b"committer <email>",
  4246. )
  4247. self.assertEqual([], list(porcelain.submodule_list(self.repo)))
  4248. def test_add(self) -> None:
  4249. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  4250. with open(f"{self.repo.path}/.gitmodules") as f:
  4251. self.assertEqual(
  4252. """\
  4253. [submodule "bar"]
  4254. \turl = ../bar.git
  4255. \tpath = bar
  4256. """,
  4257. f.read(),
  4258. )
  4259. def test_init(self) -> None:
  4260. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  4261. porcelain.submodule_init(self.repo)
  4262. def test_update(self) -> None:
  4263. # Create a submodule repository
  4264. sub_repo_path = tempfile.mkdtemp()
  4265. self.addCleanup(shutil.rmtree, sub_repo_path)
  4266. sub_repo = Repo.init(sub_repo_path)
  4267. self.addCleanup(sub_repo.close)
  4268. # Add a file to the submodule repo
  4269. sub_file = os.path.join(sub_repo_path, "test.txt")
  4270. with open(sub_file, "w") as f:
  4271. f.write("submodule content")
  4272. porcelain.add(sub_repo, paths=[sub_file])
  4273. sub_commit = porcelain.commit(
  4274. sub_repo,
  4275. message=b"Initial submodule commit",
  4276. author=b"Test Author <test@example.com>",
  4277. committer=b"Test Committer <test@example.com>",
  4278. )
  4279. # Add the submodule to the main repository
  4280. porcelain.submodule_add(self.repo, sub_repo_path, "test_submodule")
  4281. # Manually add the submodule to the index
  4282. from dulwich.index import IndexEntry
  4283. from dulwich.objects import S_IFGITLINK
  4284. index = self.repo.open_index()
  4285. index[b"test_submodule"] = IndexEntry(
  4286. ctime=0,
  4287. mtime=0,
  4288. dev=0,
  4289. ino=0,
  4290. mode=S_IFGITLINK,
  4291. uid=0,
  4292. gid=0,
  4293. size=0,
  4294. sha=sub_commit,
  4295. flags=0,
  4296. )
  4297. index.write()
  4298. porcelain.add(self.repo, paths=[".gitmodules"])
  4299. porcelain.commit(
  4300. self.repo,
  4301. message=b"Add submodule",
  4302. author=b"Test Author <test@example.com>",
  4303. committer=b"Test Committer <test@example.com>",
  4304. )
  4305. # Initialize and update the submodule
  4306. porcelain.submodule_init(self.repo)
  4307. porcelain.submodule_update(self.repo)
  4308. # Check that the submodule directory exists
  4309. submodule_path = os.path.join(self.repo.path, "test_submodule")
  4310. self.assertTrue(os.path.exists(submodule_path))
  4311. # Check that the submodule file exists
  4312. submodule_file = os.path.join(submodule_path, "test.txt")
  4313. self.assertTrue(os.path.exists(submodule_file))
  4314. with open(submodule_file) as f:
  4315. self.assertEqual(f.read(), "submodule content")
  4316. def test_update_recursive(self) -> None:
  4317. # Create a nested (innermost) submodule repository
  4318. nested_repo_path = tempfile.mkdtemp()
  4319. self.addCleanup(shutil.rmtree, nested_repo_path)
  4320. nested_repo = Repo.init(nested_repo_path)
  4321. self.addCleanup(nested_repo.close)
  4322. # Add a file to the nested repo
  4323. nested_file = os.path.join(nested_repo_path, "nested.txt")
  4324. with open(nested_file, "w") as f:
  4325. f.write("nested submodule content")
  4326. porcelain.add(nested_repo, paths=[nested_file])
  4327. nested_commit = porcelain.commit(
  4328. nested_repo,
  4329. message=b"Initial nested commit",
  4330. author=b"Test Author <test@example.com>",
  4331. committer=b"Test Committer <test@example.com>",
  4332. )
  4333. # Create a middle submodule repository
  4334. middle_repo_path = tempfile.mkdtemp()
  4335. self.addCleanup(shutil.rmtree, middle_repo_path)
  4336. middle_repo = Repo.init(middle_repo_path)
  4337. self.addCleanup(middle_repo.close)
  4338. # Add a file to the middle repo
  4339. middle_file = os.path.join(middle_repo_path, "middle.txt")
  4340. with open(middle_file, "w") as f:
  4341. f.write("middle submodule content")
  4342. porcelain.add(middle_repo, paths=[middle_file])
  4343. # Add the nested submodule to the middle repository
  4344. porcelain.submodule_add(middle_repo, nested_repo_path, "nested")
  4345. # Manually add the nested submodule to the index
  4346. from dulwich.index import IndexEntry
  4347. from dulwich.objects import S_IFGITLINK
  4348. middle_index = middle_repo.open_index()
  4349. middle_index[b"nested"] = IndexEntry(
  4350. ctime=0,
  4351. mtime=0,
  4352. dev=0,
  4353. ino=0,
  4354. mode=S_IFGITLINK,
  4355. uid=0,
  4356. gid=0,
  4357. size=0,
  4358. sha=nested_commit,
  4359. flags=0,
  4360. )
  4361. middle_index.write()
  4362. porcelain.add(middle_repo, paths=[".gitmodules"])
  4363. middle_commit = porcelain.commit(
  4364. middle_repo,
  4365. message=b"Add nested submodule",
  4366. author=b"Test Author <test@example.com>",
  4367. committer=b"Test Committer <test@example.com>",
  4368. )
  4369. # Add the middle submodule to the main repository
  4370. porcelain.submodule_add(self.repo, middle_repo_path, "middle")
  4371. # Manually add the middle submodule to the index
  4372. main_index = self.repo.open_index()
  4373. main_index[b"middle"] = IndexEntry(
  4374. ctime=0,
  4375. mtime=0,
  4376. dev=0,
  4377. ino=0,
  4378. mode=S_IFGITLINK,
  4379. uid=0,
  4380. gid=0,
  4381. size=0,
  4382. sha=middle_commit,
  4383. flags=0,
  4384. )
  4385. main_index.write()
  4386. porcelain.add(self.repo, paths=[".gitmodules"])
  4387. porcelain.commit(
  4388. self.repo,
  4389. message=b"Add middle submodule",
  4390. author=b"Test Author <test@example.com>",
  4391. committer=b"Test Committer <test@example.com>",
  4392. )
  4393. # Initialize and recursively update the submodules
  4394. porcelain.submodule_init(self.repo)
  4395. porcelain.submodule_update(self.repo, recursive=True)
  4396. # Check that the middle submodule directory and file exist
  4397. middle_submodule_path = os.path.join(self.repo.path, "middle")
  4398. self.assertTrue(os.path.exists(middle_submodule_path))
  4399. middle_submodule_file = os.path.join(middle_submodule_path, "middle.txt")
  4400. self.assertTrue(os.path.exists(middle_submodule_file))
  4401. with open(middle_submodule_file) as f:
  4402. self.assertEqual(f.read(), "middle submodule content")
  4403. # Check that the nested submodule directory and file exist
  4404. nested_submodule_path = os.path.join(self.repo.path, "middle", "nested")
  4405. self.assertTrue(os.path.exists(nested_submodule_path))
  4406. nested_submodule_file = os.path.join(nested_submodule_path, "nested.txt")
  4407. self.assertTrue(os.path.exists(nested_submodule_file))
  4408. with open(nested_submodule_file) as f:
  4409. self.assertEqual(f.read(), "nested submodule content")
  4410. class PushTests(PorcelainTestCase):
  4411. def test_simple(self) -> None:
  4412. """Basic test of porcelain push where self.repo is the remote. First
  4413. clone the remote, commit a file to the clone, then push the changes
  4414. back to the remote.
  4415. """
  4416. outstream = BytesIO()
  4417. errstream = BytesIO()
  4418. porcelain.commit(
  4419. repo=self.repo.path,
  4420. message=b"init",
  4421. author=b"author <email>",
  4422. committer=b"committer <email>",
  4423. )
  4424. # Setup target repo cloned from temp test repo
  4425. clone_path = tempfile.mkdtemp()
  4426. self.addCleanup(shutil.rmtree, clone_path)
  4427. target_repo = porcelain.clone(
  4428. self.repo.path, target=clone_path, errstream=errstream
  4429. )
  4430. self.addCleanup(target_repo.close)
  4431. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  4432. # create a second file to be pushed back to origin
  4433. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4434. os.close(handle)
  4435. porcelain.add(repo=clone_path, paths=[fullpath])
  4436. porcelain.commit(
  4437. repo=clone_path,
  4438. message=b"push",
  4439. author=b"author <email>",
  4440. committer=b"committer <email>",
  4441. )
  4442. # Setup a non-checked out branch in the remote
  4443. refs_path = b"refs/heads/foo"
  4444. new_id = self.repo[b"HEAD"].id
  4445. self.assertNotEqual(new_id, ZERO_SHA)
  4446. self.repo.refs[refs_path] = new_id
  4447. # Push to the remote
  4448. porcelain.push(
  4449. clone_path,
  4450. "origin",
  4451. b"HEAD:" + refs_path,
  4452. outstream=outstream,
  4453. errstream=errstream,
  4454. )
  4455. self.assertEqual(
  4456. target_repo.refs[b"refs/remotes/origin/foo"],
  4457. target_repo.refs[b"HEAD"],
  4458. )
  4459. # Check that the target and source
  4460. with Repo(clone_path) as r_clone:
  4461. self.assertEqual(
  4462. {
  4463. b"HEAD": new_id,
  4464. b"refs/heads/foo": r_clone[b"HEAD"].id,
  4465. b"refs/heads/master": new_id,
  4466. },
  4467. self.repo.get_refs(),
  4468. )
  4469. self.assertEqual(r_clone[b"HEAD"].id, self.repo[refs_path].id)
  4470. # Get the change in the target repo corresponding to the add
  4471. # this will be in the foo branch.
  4472. change = next(
  4473. iter(
  4474. tree_changes(
  4475. self.repo.object_store,
  4476. self.repo[b"HEAD"].tree,
  4477. self.repo[b"refs/heads/foo"].tree,
  4478. )
  4479. )
  4480. )
  4481. self.assertEqual(
  4482. os.path.basename(fullpath), change.new.path.decode("ascii")
  4483. )
  4484. def test_local_missing(self) -> None:
  4485. """Pushing a new branch."""
  4486. outstream = BytesIO()
  4487. errstream = BytesIO()
  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.init(clone_path)
  4492. target_repo.close()
  4493. self.assertRaises(
  4494. porcelain.Error,
  4495. porcelain.push,
  4496. self.repo,
  4497. clone_path,
  4498. b"HEAD:refs/heads/master",
  4499. outstream=outstream,
  4500. errstream=errstream,
  4501. )
  4502. def test_new(self) -> None:
  4503. """Pushing a new branch."""
  4504. outstream = BytesIO()
  4505. errstream = BytesIO()
  4506. # Setup target repo cloned from temp test repo
  4507. clone_path = tempfile.mkdtemp()
  4508. self.addCleanup(shutil.rmtree, clone_path)
  4509. target_repo = porcelain.init(clone_path)
  4510. target_repo.close()
  4511. # create a second file to be pushed back to origin
  4512. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4513. os.close(handle)
  4514. porcelain.add(repo=clone_path, paths=[fullpath])
  4515. new_id = porcelain.commit(
  4516. repo=self.repo,
  4517. message=b"push",
  4518. author=b"author <email>",
  4519. committer=b"committer <email>",
  4520. )
  4521. # Push to the remote
  4522. porcelain.push(
  4523. self.repo,
  4524. clone_path,
  4525. b"HEAD:refs/heads/master",
  4526. outstream=outstream,
  4527. errstream=errstream,
  4528. )
  4529. with Repo(clone_path) as r_clone:
  4530. self.assertEqual(
  4531. {
  4532. b"HEAD": new_id,
  4533. b"refs/heads/master": new_id,
  4534. },
  4535. r_clone.get_refs(),
  4536. )
  4537. def test_delete(self) -> None:
  4538. """Basic test of porcelain push, removing a branch."""
  4539. outstream = BytesIO()
  4540. errstream = BytesIO()
  4541. porcelain.commit(
  4542. repo=self.repo.path,
  4543. message=b"init",
  4544. author=b"author <email>",
  4545. committer=b"committer <email>",
  4546. )
  4547. # Setup target repo cloned from temp test repo
  4548. clone_path = tempfile.mkdtemp()
  4549. self.addCleanup(shutil.rmtree, clone_path)
  4550. target_repo = porcelain.clone(
  4551. self.repo.path, target=clone_path, errstream=errstream
  4552. )
  4553. target_repo.close()
  4554. # Setup a non-checked out branch in the remote
  4555. refs_path = b"refs/heads/foo"
  4556. new_id = self.repo[b"HEAD"].id
  4557. self.assertNotEqual(new_id, ZERO_SHA)
  4558. self.repo.refs[refs_path] = new_id
  4559. # Push to the remote
  4560. porcelain.push(
  4561. clone_path,
  4562. self.repo.path,
  4563. b":" + refs_path,
  4564. outstream=outstream,
  4565. errstream=errstream,
  4566. )
  4567. self.assertEqual(
  4568. {
  4569. b"HEAD": new_id,
  4570. b"refs/heads/master": new_id,
  4571. },
  4572. self.repo.get_refs(),
  4573. )
  4574. def test_diverged(self) -> None:
  4575. outstream = BytesIO()
  4576. errstream = BytesIO()
  4577. porcelain.commit(
  4578. repo=self.repo.path,
  4579. message=b"init",
  4580. author=b"author <email>",
  4581. committer=b"committer <email>",
  4582. )
  4583. # Setup target repo cloned from temp test repo
  4584. clone_path = tempfile.mkdtemp()
  4585. self.addCleanup(shutil.rmtree, clone_path)
  4586. target_repo = porcelain.clone(
  4587. self.repo.path, target=clone_path, errstream=errstream
  4588. )
  4589. target_repo.close()
  4590. remote_id = porcelain.commit(
  4591. repo=self.repo.path,
  4592. message=b"remote change",
  4593. author=b"author <email>",
  4594. committer=b"committer <email>",
  4595. )
  4596. local_id = porcelain.commit(
  4597. repo=clone_path,
  4598. message=b"local change",
  4599. author=b"author <email>",
  4600. committer=b"committer <email>",
  4601. )
  4602. outstream = BytesIO()
  4603. errstream = BytesIO()
  4604. # Push to the remote
  4605. self.assertRaises(
  4606. porcelain.DivergedBranches,
  4607. porcelain.push,
  4608. clone_path,
  4609. self.repo.path,
  4610. b"refs/heads/master",
  4611. outstream=outstream,
  4612. errstream=errstream,
  4613. )
  4614. self.assertEqual(
  4615. {
  4616. b"HEAD": remote_id,
  4617. b"refs/heads/master": remote_id,
  4618. },
  4619. self.repo.get_refs(),
  4620. )
  4621. self.assertEqual(b"", outstream.getvalue())
  4622. self.assertEqual(b"", errstream.getvalue())
  4623. outstream = BytesIO()
  4624. errstream = BytesIO()
  4625. # Push to the remote with --force
  4626. porcelain.push(
  4627. clone_path,
  4628. self.repo.path,
  4629. b"refs/heads/master",
  4630. outstream=outstream,
  4631. errstream=errstream,
  4632. force=True,
  4633. )
  4634. self.assertEqual(
  4635. {
  4636. b"HEAD": local_id,
  4637. b"refs/heads/master": local_id,
  4638. },
  4639. self.repo.get_refs(),
  4640. )
  4641. self.assertEqual(b"", outstream.getvalue())
  4642. self.assertTrue(re.search(b"Push to .* successful.\n", errstream.getvalue()))
  4643. def test_push_returns_sendpackresult(self) -> None:
  4644. """Test that push returns a SendPackResult with per-ref information."""
  4645. outstream = BytesIO()
  4646. errstream = BytesIO()
  4647. # Create initial commit
  4648. porcelain.commit(
  4649. repo=self.repo.path,
  4650. message=b"init",
  4651. author=b"author <email>",
  4652. committer=b"committer <email>",
  4653. )
  4654. # Setup target repo cloned from temp test repo
  4655. clone_path = tempfile.mkdtemp()
  4656. self.addCleanup(shutil.rmtree, clone_path)
  4657. target_repo = porcelain.clone(
  4658. self.repo.path, target=clone_path, errstream=errstream
  4659. )
  4660. target_repo.close()
  4661. # Create a commit in the clone
  4662. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4663. os.close(handle)
  4664. porcelain.add(repo=clone_path, paths=[fullpath])
  4665. porcelain.commit(
  4666. repo=clone_path,
  4667. message=b"push",
  4668. author=b"author <email>",
  4669. committer=b"committer <email>",
  4670. )
  4671. # Push and check the return value
  4672. result = porcelain.push(
  4673. clone_path,
  4674. "origin",
  4675. b"HEAD:refs/heads/new-branch",
  4676. outstream=outstream,
  4677. errstream=errstream,
  4678. )
  4679. # Verify that we get a SendPackResult
  4680. self.assertIsInstance(result, SendPackResult)
  4681. # Verify that it contains refs
  4682. self.assertIsNotNone(result.refs)
  4683. self.assertIn(b"refs/heads/new-branch", result.refs)
  4684. # Verify ref_status - should be None for successful updates
  4685. if result.ref_status:
  4686. self.assertIsNone(result.ref_status.get(b"refs/heads/new-branch"))
  4687. def test_mirror_mode(self) -> None:
  4688. """Test push with remote.<name>.mirror configuration."""
  4689. outstream = BytesIO()
  4690. errstream = BytesIO()
  4691. # Create initial commit
  4692. porcelain.commit(
  4693. repo=self.repo.path,
  4694. message=b"init",
  4695. author=b"author <email>",
  4696. committer=b"committer <email>",
  4697. )
  4698. # Setup target repo cloned from temp test repo
  4699. clone_path = tempfile.mkdtemp()
  4700. self.addCleanup(shutil.rmtree, clone_path)
  4701. target_repo = porcelain.clone(
  4702. self.repo.path, target=clone_path, errstream=errstream
  4703. )
  4704. target_repo.close()
  4705. # Create multiple refs in the clone
  4706. with Repo(clone_path) as r_clone:
  4707. # Create a new branch
  4708. r_clone.refs[b"refs/heads/feature"] = r_clone[b"HEAD"].id
  4709. # Create a tag
  4710. r_clone.refs[b"refs/tags/v1.0"] = r_clone[b"HEAD"].id
  4711. # Create a remote tracking branch
  4712. r_clone.refs[b"refs/remotes/upstream/main"] = r_clone[b"HEAD"].id
  4713. # Create a branch in the remote that doesn't exist in clone
  4714. self.repo.refs[b"refs/heads/to-be-deleted"] = self.repo[b"HEAD"].id
  4715. # Configure mirror mode
  4716. with Repo(clone_path) as r_clone:
  4717. config = r_clone.get_config()
  4718. config.set((b"remote", b"origin"), b"mirror", True)
  4719. config.write_to_path()
  4720. # Push with mirror mode
  4721. porcelain.push(
  4722. clone_path,
  4723. "origin",
  4724. outstream=outstream,
  4725. errstream=errstream,
  4726. )
  4727. # Verify refs were properly mirrored
  4728. with Repo(clone_path) as r_clone:
  4729. # All local branches should be pushed
  4730. self.assertEqual(
  4731. r_clone.refs[b"refs/heads/feature"],
  4732. self.repo.refs[b"refs/heads/feature"],
  4733. )
  4734. # All tags should be pushed
  4735. self.assertEqual(
  4736. r_clone.refs[b"refs/tags/v1.0"], self.repo.refs[b"refs/tags/v1.0"]
  4737. )
  4738. # Remote tracking branches should be pushed
  4739. self.assertEqual(
  4740. r_clone.refs[b"refs/remotes/upstream/main"],
  4741. self.repo.refs[b"refs/remotes/upstream/main"],
  4742. )
  4743. # Verify the extra branch was deleted
  4744. self.assertNotIn(b"refs/heads/to-be-deleted", self.repo.refs)
  4745. def test_mirror_mode_disabled(self) -> None:
  4746. """Test that mirror mode is properly disabled when set to false."""
  4747. outstream = BytesIO()
  4748. errstream = BytesIO()
  4749. # Create initial commit
  4750. porcelain.commit(
  4751. repo=self.repo.path,
  4752. message=b"init",
  4753. author=b"author <email>",
  4754. committer=b"committer <email>",
  4755. )
  4756. # Setup target repo cloned from temp test repo
  4757. clone_path = tempfile.mkdtemp()
  4758. self.addCleanup(shutil.rmtree, clone_path)
  4759. target_repo = porcelain.clone(
  4760. self.repo.path, target=clone_path, errstream=errstream
  4761. )
  4762. target_repo.close()
  4763. # Create a branch in the remote that doesn't exist in clone
  4764. self.repo.refs[b"refs/heads/should-not-be-deleted"] = self.repo[b"HEAD"].id
  4765. # Explicitly set mirror mode to false
  4766. with Repo(clone_path) as r_clone:
  4767. config = r_clone.get_config()
  4768. config.set((b"remote", b"origin"), b"mirror", False)
  4769. config.write_to_path()
  4770. # Push normally (not mirror mode)
  4771. porcelain.push(
  4772. clone_path,
  4773. "origin",
  4774. outstream=outstream,
  4775. errstream=errstream,
  4776. )
  4777. # Verify the extra branch was NOT deleted
  4778. self.assertIn(b"refs/heads/should-not-be-deleted", self.repo.refs)
  4779. class PullTests(PorcelainTestCase):
  4780. def setUp(self) -> None:
  4781. super().setUp()
  4782. # create a file for initial commit
  4783. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4784. os.close(handle)
  4785. porcelain.add(repo=self.repo.path, paths=fullpath)
  4786. porcelain.commit(
  4787. repo=self.repo.path,
  4788. message=b"test",
  4789. author=b"test <email>",
  4790. committer=b"test <email>",
  4791. )
  4792. # Setup target repo
  4793. self.target_path = tempfile.mkdtemp()
  4794. self.addCleanup(shutil.rmtree, self.target_path)
  4795. target_repo = porcelain.clone(
  4796. self.repo.path, target=self.target_path, errstream=BytesIO()
  4797. )
  4798. target_repo.close()
  4799. # create a second file to be pushed
  4800. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4801. os.close(handle)
  4802. porcelain.add(repo=self.repo.path, paths=fullpath)
  4803. porcelain.commit(
  4804. repo=self.repo.path,
  4805. message=b"test2",
  4806. author=b"test2 <email>",
  4807. committer=b"test2 <email>",
  4808. )
  4809. self.assertIn(b"refs/heads/master", self.repo.refs)
  4810. self.assertIn(b"refs/heads/master", target_repo.refs)
  4811. def test_simple(self) -> None:
  4812. outstream = BytesIO()
  4813. errstream = BytesIO()
  4814. # Pull changes into the cloned repo
  4815. porcelain.pull(
  4816. self.target_path,
  4817. self.repo.path,
  4818. b"refs/heads/master",
  4819. outstream=outstream,
  4820. errstream=errstream,
  4821. )
  4822. # Check the target repo for pushed changes
  4823. with Repo(self.target_path) as r:
  4824. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4825. def test_diverged(self) -> None:
  4826. outstream = BytesIO()
  4827. errstream = BytesIO()
  4828. c3a = porcelain.commit(
  4829. repo=self.target_path,
  4830. message=b"test3a",
  4831. author=b"test2 <email>",
  4832. committer=b"test2 <email>",
  4833. )
  4834. porcelain.commit(
  4835. repo=self.repo.path,
  4836. message=b"test3b",
  4837. author=b"test2 <email>",
  4838. committer=b"test2 <email>",
  4839. )
  4840. # Pull changes into the cloned repo
  4841. self.assertRaises(
  4842. porcelain.DivergedBranches,
  4843. porcelain.pull,
  4844. self.target_path,
  4845. self.repo.path,
  4846. b"refs/heads/master",
  4847. outstream=outstream,
  4848. errstream=errstream,
  4849. )
  4850. # Check the target repo for pushed changes
  4851. with Repo(self.target_path) as r:
  4852. self.assertEqual(r[b"refs/heads/master"].id, c3a)
  4853. # Pull with merge should now work
  4854. porcelain.pull(
  4855. self.target_path,
  4856. self.repo.path,
  4857. b"refs/heads/master",
  4858. outstream=outstream,
  4859. errstream=errstream,
  4860. fast_forward=False,
  4861. )
  4862. # Check the target repo for merged changes
  4863. with Repo(self.target_path) as r:
  4864. # HEAD should now be a merge commit
  4865. head = r[b"HEAD"]
  4866. # It should have two parents
  4867. self.assertEqual(len(head.parents), 2)
  4868. # One parent should be the previous HEAD (c3a)
  4869. self.assertIn(c3a, head.parents)
  4870. # The other parent should be from the source repo
  4871. self.assertIn(self.repo[b"HEAD"].id, head.parents)
  4872. def test_no_refspec(self) -> None:
  4873. outstream = BytesIO()
  4874. errstream = BytesIO()
  4875. # Pull changes into the cloned repo
  4876. porcelain.pull(
  4877. self.target_path,
  4878. self.repo.path,
  4879. outstream=outstream,
  4880. errstream=errstream,
  4881. )
  4882. # Check the target repo for pushed changes
  4883. with Repo(self.target_path) as r:
  4884. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4885. def test_no_remote_location(self) -> None:
  4886. outstream = BytesIO()
  4887. errstream = BytesIO()
  4888. # Pull changes into the cloned repo
  4889. porcelain.pull(
  4890. self.target_path,
  4891. refspecs=b"refs/heads/master",
  4892. outstream=outstream,
  4893. errstream=errstream,
  4894. )
  4895. # Check the target repo for pushed changes
  4896. with Repo(self.target_path) as r:
  4897. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4898. def test_pull_updates_working_tree(self) -> None:
  4899. """Test that pull updates the working tree with new files."""
  4900. outstream = BytesIO()
  4901. errstream = BytesIO()
  4902. # Create a new file with content in the source repo
  4903. new_file = os.path.join(self.repo.path, "newfile.txt")
  4904. with open(new_file, "w") as f:
  4905. f.write("This is new content")
  4906. porcelain.add(repo=self.repo.path, paths=[new_file])
  4907. porcelain.commit(
  4908. repo=self.repo.path,
  4909. message=b"Add new file",
  4910. author=b"test <email>",
  4911. committer=b"test <email>",
  4912. )
  4913. # Before pull, the file should not exist in target
  4914. target_file = os.path.join(self.target_path, "newfile.txt")
  4915. self.assertFalse(os.path.exists(target_file))
  4916. # Pull changes into the cloned repo
  4917. porcelain.pull(
  4918. self.target_path,
  4919. self.repo.path,
  4920. b"refs/heads/master",
  4921. outstream=outstream,
  4922. errstream=errstream,
  4923. )
  4924. # After pull, the file should exist with correct content
  4925. self.assertTrue(os.path.exists(target_file))
  4926. with open(target_file) as f:
  4927. self.assertEqual(f.read(), "This is new content")
  4928. # Check the HEAD is updated too
  4929. with Repo(self.target_path) as r:
  4930. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4931. def test_pull_protects_modified_files(self) -> None:
  4932. """Test that pull refuses to overwrite uncommitted changes by default."""
  4933. from dulwich.errors import WorkingTreeModifiedError
  4934. outstream = BytesIO()
  4935. errstream = BytesIO()
  4936. # Create a file with content in the source repo
  4937. test_file = os.path.join(self.repo.path, "testfile.txt")
  4938. with open(test_file, "w") as f:
  4939. f.write("original content")
  4940. porcelain.add(repo=self.repo.path, paths=[test_file])
  4941. porcelain.commit(
  4942. repo=self.repo.path,
  4943. message=b"Add test file",
  4944. author=b"test <email>",
  4945. committer=b"test <email>",
  4946. )
  4947. # Pull this change to target first
  4948. porcelain.pull(
  4949. self.target_path,
  4950. self.repo.path,
  4951. b"refs/heads/master",
  4952. outstream=outstream,
  4953. errstream=errstream,
  4954. )
  4955. # Now modify the file in source repo
  4956. with open(test_file, "w") as f:
  4957. f.write("updated content")
  4958. porcelain.add(repo=self.repo.path, paths=[test_file])
  4959. porcelain.commit(
  4960. repo=self.repo.path,
  4961. message=b"Update test file",
  4962. author=b"test <email>",
  4963. committer=b"test <email>",
  4964. )
  4965. # Modify the same file in target working directory (uncommitted)
  4966. target_file = os.path.join(self.target_path, "testfile.txt")
  4967. with open(target_file, "w") as f:
  4968. f.write("local modifications")
  4969. # Pull should fail because of uncommitted changes
  4970. with self.assertRaises(WorkingTreeModifiedError) as cm:
  4971. porcelain.pull(
  4972. self.target_path,
  4973. self.repo.path,
  4974. b"refs/heads/master",
  4975. outstream=outstream,
  4976. errstream=errstream,
  4977. )
  4978. self.assertIn("Your local changes", str(cm.exception))
  4979. self.assertIn("testfile.txt", str(cm.exception))
  4980. # Verify the file still has local modifications
  4981. with open(target_file) as f:
  4982. self.assertEqual(f.read(), "local modifications")
  4983. def test_pull_force_overwrites_modified_files(self) -> None:
  4984. """Test that pull with force=True overwrites uncommitted changes."""
  4985. outstream = BytesIO()
  4986. errstream = BytesIO()
  4987. # Create a file with content in the source repo
  4988. test_file = os.path.join(self.repo.path, "testfile.txt")
  4989. with open(test_file, "w") as f:
  4990. f.write("original content")
  4991. porcelain.add(repo=self.repo.path, paths=[test_file])
  4992. porcelain.commit(
  4993. repo=self.repo.path,
  4994. message=b"Add test file",
  4995. author=b"test <email>",
  4996. committer=b"test <email>",
  4997. )
  4998. # Pull this change to target first
  4999. porcelain.pull(
  5000. self.target_path,
  5001. self.repo.path,
  5002. b"refs/heads/master",
  5003. outstream=outstream,
  5004. errstream=errstream,
  5005. )
  5006. # Now modify the file in source repo
  5007. with open(test_file, "w") as f:
  5008. f.write("updated content")
  5009. porcelain.add(repo=self.repo.path, paths=[test_file])
  5010. porcelain.commit(
  5011. repo=self.repo.path,
  5012. message=b"Update test file",
  5013. author=b"test <email>",
  5014. committer=b"test <email>",
  5015. )
  5016. # Modify the same file in target working directory (uncommitted)
  5017. target_file = os.path.join(self.target_path, "testfile.txt")
  5018. with open(target_file, "w") as f:
  5019. f.write("local modifications")
  5020. # Pull with force=True should succeed and overwrite local changes
  5021. porcelain.pull(
  5022. self.target_path,
  5023. self.repo.path,
  5024. b"refs/heads/master",
  5025. outstream=outstream,
  5026. errstream=errstream,
  5027. force=True,
  5028. )
  5029. # Verify the file now has the remote content
  5030. with open(target_file) as f:
  5031. self.assertEqual(f.read(), "updated content")
  5032. # Check the HEAD is updated too
  5033. with Repo(self.target_path) as r:
  5034. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  5035. def test_pull_allows_unmodified_files(self) -> None:
  5036. """Test that pull allows updating files that haven't been modified locally."""
  5037. outstream = BytesIO()
  5038. errstream = BytesIO()
  5039. # Create a file with content in the source repo
  5040. test_file = os.path.join(self.repo.path, "testfile.txt")
  5041. with open(test_file, "w") as f:
  5042. f.write("original content")
  5043. porcelain.add(repo=self.repo.path, paths=[test_file])
  5044. porcelain.commit(
  5045. repo=self.repo.path,
  5046. message=b"Add test file",
  5047. author=b"test <email>",
  5048. committer=b"test <email>",
  5049. )
  5050. # Pull this change to target first
  5051. porcelain.pull(
  5052. self.target_path,
  5053. self.repo.path,
  5054. b"refs/heads/master",
  5055. outstream=outstream,
  5056. errstream=errstream,
  5057. )
  5058. # Now modify the file in source repo
  5059. with open(test_file, "w") as f:
  5060. f.write("updated content")
  5061. porcelain.add(repo=self.repo.path, paths=[test_file])
  5062. porcelain.commit(
  5063. repo=self.repo.path,
  5064. message=b"Update test file",
  5065. author=b"test <email>",
  5066. committer=b"test <email>",
  5067. )
  5068. # Don't modify the file in target - it should be safe to update
  5069. target_file = os.path.join(self.target_path, "testfile.txt")
  5070. # Pull should succeed since the file wasn't modified locally
  5071. porcelain.pull(
  5072. self.target_path,
  5073. self.repo.path,
  5074. b"refs/heads/master",
  5075. outstream=outstream,
  5076. errstream=errstream,
  5077. )
  5078. # Verify the file now has the remote content
  5079. with open(target_file) as f:
  5080. self.assertEqual(f.read(), "updated content")
  5081. # Check the HEAD is updated too
  5082. with Repo(self.target_path) as r:
  5083. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  5084. class StatusTests(PorcelainTestCase):
  5085. def test_empty(self) -> None:
  5086. results = porcelain.status(self.repo)
  5087. self.assertEqual({"add": [], "delete": [], "modify": []}, results.staged)
  5088. self.assertEqual([], results.unstaged)
  5089. def test_status_base(self) -> None:
  5090. """Integration test for `status` functionality."""
  5091. # Commit a dummy file then modify it
  5092. fullpath = os.path.join(self.repo.path, "foo")
  5093. with open(fullpath, "w") as f:
  5094. f.write("origstuff")
  5095. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5096. porcelain.commit(
  5097. repo=self.repo.path,
  5098. message=b"test status",
  5099. author=b"author <email>",
  5100. committer=b"committer <email>",
  5101. )
  5102. # modify access and modify time of path
  5103. os.utime(fullpath, (0, 0))
  5104. with open(fullpath, "wb") as f:
  5105. f.write(b"stuff")
  5106. # Make a dummy file and stage it
  5107. filename_add = "bar"
  5108. fullpath = os.path.join(self.repo.path, filename_add)
  5109. with open(fullpath, "w") as f:
  5110. f.write("stuff")
  5111. porcelain.add(repo=self.repo.path, paths=fullpath)
  5112. results = porcelain.status(self.repo)
  5113. self.assertEqual(results.staged["add"][0], filename_add.encode("ascii"))
  5114. self.assertEqual(results.unstaged, [b"foo"])
  5115. def test_status_with_core_preloadindex(self) -> None:
  5116. """Test status with core.preloadIndex enabled."""
  5117. # Set core.preloadIndex to true
  5118. config = self.repo.get_config()
  5119. config.set(b"core", b"preloadIndex", b"true")
  5120. config.write_to_path()
  5121. # Create multiple files
  5122. files = []
  5123. for i in range(10):
  5124. filename = f"file{i}"
  5125. fullpath = os.path.join(self.repo.path, filename)
  5126. with open(fullpath, "w") as f:
  5127. f.write(f"content{i}")
  5128. files.append(fullpath)
  5129. porcelain.add(repo=self.repo.path, paths=files)
  5130. porcelain.commit(
  5131. repo=self.repo.path,
  5132. message=b"test preload status",
  5133. author=b"author <email>",
  5134. committer=b"committer <email>",
  5135. )
  5136. # Modify some files
  5137. modified_files = ["file1", "file3", "file5", "file7"]
  5138. for filename in modified_files:
  5139. fullpath = os.path.join(self.repo.path, filename)
  5140. with open(fullpath, "w") as f:
  5141. f.write("modified content")
  5142. os.utime(fullpath, (0, 0))
  5143. # Status should work correctly with preloadIndex enabled
  5144. results = porcelain.status(self.repo)
  5145. # Check that we detected the correct unstaged changes
  5146. unstaged_sorted = sorted(results.unstaged)
  5147. expected_sorted = sorted([f.encode("ascii") for f in modified_files])
  5148. self.assertEqual(unstaged_sorted, expected_sorted)
  5149. def test_status_all(self) -> None:
  5150. del_path = os.path.join(self.repo.path, "foo")
  5151. mod_path = os.path.join(self.repo.path, "bar")
  5152. add_path = os.path.join(self.repo.path, "baz")
  5153. us_path = os.path.join(self.repo.path, "blye")
  5154. ut_path = os.path.join(self.repo.path, "blyat")
  5155. with open(del_path, "w") as f:
  5156. f.write("origstuff")
  5157. with open(mod_path, "w") as f:
  5158. f.write("origstuff")
  5159. with open(us_path, "w") as f:
  5160. f.write("origstuff")
  5161. porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path])
  5162. porcelain.commit(
  5163. repo=self.repo.path,
  5164. message=b"test status",
  5165. author=b"author <email>",
  5166. committer=b"committer <email>",
  5167. )
  5168. porcelain.remove(self.repo.path, [del_path])
  5169. with open(add_path, "w") as f:
  5170. f.write("origstuff")
  5171. with open(mod_path, "w") as f:
  5172. f.write("more_origstuff")
  5173. with open(us_path, "w") as f:
  5174. f.write("more_origstuff")
  5175. porcelain.add(repo=self.repo.path, paths=[add_path, mod_path])
  5176. with open(us_path, "w") as f:
  5177. f.write("\norigstuff")
  5178. with open(ut_path, "w") as f:
  5179. f.write("origstuff")
  5180. results = porcelain.status(self.repo.path)
  5181. self.assertDictEqual(
  5182. {"add": [b"baz"], "delete": [b"foo"], "modify": [b"bar"]},
  5183. results.staged,
  5184. )
  5185. self.assertListEqual(results.unstaged, [b"blye"])
  5186. results_no_untracked = porcelain.status(self.repo.path, untracked_files="no")
  5187. self.assertListEqual(results_no_untracked.untracked, [])
  5188. def test_status_wrong_untracked_files_value(self) -> None:
  5189. with self.assertRaises(ValueError):
  5190. porcelain.status(self.repo.path, untracked_files="antani")
  5191. def test_status_untracked_path(self) -> None:
  5192. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  5193. os.mkdir(untracked_dir)
  5194. untracked_file = os.path.join(untracked_dir, "untracked_file")
  5195. with open(untracked_file, "w") as fh:
  5196. fh.write("untracked")
  5197. _, _, untracked = porcelain.status(self.repo.path, untracked_files="all")
  5198. self.assertEqual(untracked, ["untracked_dir/untracked_file"])
  5199. def test_status_untracked_path_normal(self) -> None:
  5200. # Create an untracked directory with multiple files
  5201. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  5202. os.mkdir(untracked_dir)
  5203. untracked_file1 = os.path.join(untracked_dir, "file1")
  5204. untracked_file2 = os.path.join(untracked_dir, "file2")
  5205. with open(untracked_file1, "w") as fh:
  5206. fh.write("untracked1")
  5207. with open(untracked_file2, "w") as fh:
  5208. fh.write("untracked2")
  5209. # Create a nested untracked directory
  5210. nested_dir = os.path.join(untracked_dir, "nested")
  5211. os.mkdir(nested_dir)
  5212. nested_file = os.path.join(nested_dir, "file3")
  5213. with open(nested_file, "w") as fh:
  5214. fh.write("untracked3")
  5215. # Test "normal" mode - should only show the directory, not individual files
  5216. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  5217. self.assertEqual(untracked, ["untracked_dir/"])
  5218. # Test "all" mode - should show all files
  5219. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  5220. self.assertEqual(
  5221. sorted(untracked_all),
  5222. [
  5223. "untracked_dir/file1",
  5224. "untracked_dir/file2",
  5225. "untracked_dir/nested/file3",
  5226. ],
  5227. )
  5228. def test_status_mixed_tracked_untracked(self) -> None:
  5229. # Create a directory with both tracked and untracked files
  5230. mixed_dir = os.path.join(self.repo_path, "mixed_dir")
  5231. os.mkdir(mixed_dir)
  5232. # Add a tracked file
  5233. tracked_file = os.path.join(mixed_dir, "tracked.txt")
  5234. with open(tracked_file, "w") as fh:
  5235. fh.write("tracked content")
  5236. porcelain.add(self.repo.path, paths=[tracked_file])
  5237. porcelain.commit(
  5238. repo=self.repo.path,
  5239. message=b"add tracked file",
  5240. author=b"author <email>",
  5241. committer=b"committer <email>",
  5242. )
  5243. # Add untracked files to the same directory
  5244. untracked_file = os.path.join(mixed_dir, "untracked.txt")
  5245. with open(untracked_file, "w") as fh:
  5246. fh.write("untracked content")
  5247. # In "normal" mode, should show individual untracked files in mixed dirs
  5248. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  5249. self.assertEqual(untracked, ["mixed_dir/untracked.txt"])
  5250. # In "all" mode, should be the same for mixed directories
  5251. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  5252. self.assertEqual(untracked_all, ["mixed_dir/untracked.txt"])
  5253. def test_status_crlf_mismatch(self) -> None:
  5254. # First make a commit as if the file has been added on a Linux system
  5255. # or with core.autocrlf=True
  5256. file_path = os.path.join(self.repo.path, "crlf")
  5257. with open(file_path, "wb") as f:
  5258. f.write(b"line1\nline2")
  5259. porcelain.add(repo=self.repo.path, paths=[file_path])
  5260. porcelain.commit(
  5261. repo=self.repo.path,
  5262. message=b"test status",
  5263. author=b"author <email>",
  5264. committer=b"committer <email>",
  5265. )
  5266. # Then update the file as if it was created by CGit on a Windows
  5267. # system with core.autocrlf=true
  5268. with open(file_path, "wb") as f:
  5269. f.write(b"line1\r\nline2")
  5270. results = porcelain.status(self.repo)
  5271. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  5272. self.assertListEqual(results.unstaged, [b"crlf"])
  5273. self.assertListEqual(results.untracked, [])
  5274. def test_status_autocrlf_true(self) -> None:
  5275. # First make a commit as if the file has been added on a Linux system
  5276. # or with core.autocrlf=True
  5277. file_path = os.path.join(self.repo.path, "crlf")
  5278. with open(file_path, "wb") as f:
  5279. f.write(b"line1\nline2")
  5280. porcelain.add(repo=self.repo.path, paths=[file_path])
  5281. porcelain.commit(
  5282. repo=self.repo.path,
  5283. message=b"test status",
  5284. author=b"author <email>",
  5285. committer=b"committer <email>",
  5286. )
  5287. # Then update the file as if it was created by CGit on a Windows
  5288. # system with core.autocrlf=true
  5289. with open(file_path, "wb") as f:
  5290. f.write(b"line1\r\nline2")
  5291. # TODO: It should be set automatically by looking at the configuration
  5292. c = self.repo.get_config()
  5293. c.set("core", "autocrlf", True)
  5294. c.write_to_path()
  5295. results = porcelain.status(self.repo)
  5296. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  5297. self.assertListEqual(results.unstaged, [])
  5298. self.assertListEqual(results.untracked, [])
  5299. def test_status_autocrlf_input(self) -> None:
  5300. # Commit existing file with CRLF
  5301. file_path = os.path.join(self.repo.path, "crlf-exists")
  5302. with open(file_path, "wb") as f:
  5303. f.write(b"line1\r\nline2")
  5304. porcelain.add(repo=self.repo.path, paths=[file_path])
  5305. porcelain.commit(
  5306. repo=self.repo.path,
  5307. message=b"test status",
  5308. author=b"author <email>",
  5309. committer=b"committer <email>",
  5310. )
  5311. # Get the index entry mtime and set the file mtime to match it exactly
  5312. # This ensures stat matching works correctly with nanosecond precision
  5313. index = self.repo.open_index()
  5314. entry = index[b"crlf-exists"]
  5315. if isinstance(entry.mtime, tuple):
  5316. mtime_nsec = entry.mtime[0] * 1_000_000_000 + entry.mtime[1]
  5317. else:
  5318. mtime_nsec = int(entry.mtime * 1_000_000_000)
  5319. # Use ns parameter to preserve nanosecond precision
  5320. os.utime(file_path, ns=(mtime_nsec, mtime_nsec))
  5321. c = self.repo.get_config()
  5322. c.set("core", "autocrlf", "input")
  5323. c.write_to_path()
  5324. # Add new (untracked) file
  5325. file_path = os.path.join(self.repo.path, "crlf-new")
  5326. with open(file_path, "wb") as f:
  5327. f.write(b"line1\r\nline2")
  5328. porcelain.add(repo=self.repo.path, paths=[file_path])
  5329. results = porcelain.status(self.repo)
  5330. self.assertDictEqual(
  5331. {"add": [b"crlf-new"], "delete": [], "modify": []}, results.staged
  5332. )
  5333. # File committed with CRLF before autocrlf=input was enabled
  5334. # will NOT appear as unstaged because stat matching optimization
  5335. # skips filter processing when file hasn't been modified.
  5336. # This matches Git's behavior, which uses stat matching to avoid
  5337. # expensive filter operations. Git shows a warning instead.
  5338. self.assertListEqual(results.unstaged, [])
  5339. self.assertListEqual(results.untracked, [])
  5340. def test_status_autocrlf_input_modified(self) -> None:
  5341. """Test that modified files with CRLF are correctly detected with autocrlf=input."""
  5342. # Commit existing file with CRLF
  5343. file_path = os.path.join(self.repo.path, "crlf-file.txt")
  5344. with open(file_path, "wb") as f:
  5345. f.write(b"line1\r\nline2\r\nline3\r\n")
  5346. porcelain.add(repo=self.repo.path, paths=[file_path])
  5347. porcelain.commit(
  5348. repo=self.repo.path,
  5349. message=b"initial commit",
  5350. author=b"author <email>",
  5351. committer=b"committer <email>",
  5352. )
  5353. c = self.repo.get_config()
  5354. c.set("core", "autocrlf", "input")
  5355. c.write_to_path()
  5356. # Modify the file content but keep CRLF
  5357. with open(file_path, "wb") as f:
  5358. f.write(b"line1\r\nline2 modified\r\nline3\r\n")
  5359. results = porcelain.status(self.repo)
  5360. # Modified file should be detected as unstaged
  5361. self.assertListEqual(results.unstaged, [b"crlf-file.txt"])
  5362. def test_status_autocrlf_input_binary(self) -> None:
  5363. """Test that binary files are not affected by autocrlf=input."""
  5364. # Set autocrlf=input first
  5365. c = self.repo.get_config()
  5366. c.set("core", "autocrlf", "input")
  5367. c.write_to_path()
  5368. # Commit binary file with CRLF-like sequences
  5369. file_path = os.path.join(self.repo.path, "binary.dat")
  5370. with open(file_path, "wb") as f:
  5371. f.write(b"binary\r\ndata\x00\xff\r\nmore")
  5372. porcelain.add(repo=self.repo.path, paths=[file_path])
  5373. porcelain.commit(
  5374. repo=self.repo.path,
  5375. message=b"add binary",
  5376. author=b"author <email>",
  5377. committer=b"committer <email>",
  5378. )
  5379. # Status should be clean - binary files not normalized
  5380. results = porcelain.status(self.repo)
  5381. self.assertListEqual(results.unstaged, [])
  5382. def test_status_autocrlf_input_mixed_endings(self) -> None:
  5383. """Test files with mixed line endings with autocrlf=input."""
  5384. # Set autocrlf=input
  5385. c = self.repo.get_config()
  5386. c.set("core", "autocrlf", "input")
  5387. c.write_to_path()
  5388. # Create file with mixed line endings
  5389. file_path = os.path.join(self.repo.path, "mixed.txt")
  5390. with open(file_path, "wb") as f:
  5391. f.write(b"line1\r\nline2\nline3\r\n")
  5392. porcelain.add(repo=self.repo.path, paths=[file_path])
  5393. porcelain.commit(
  5394. repo=self.repo.path,
  5395. message=b"add mixed",
  5396. author=b"author <email>",
  5397. committer=b"committer <email>",
  5398. )
  5399. # The file was normalized on commit, so working tree should match
  5400. results = porcelain.status(self.repo)
  5401. self.assertListEqual(results.unstaged, [])
  5402. def test_status_autocrlf_input_issue_1770(self) -> None:
  5403. """Test the specific scenario from issue #1770.
  5404. Files with CRLF committed with autocrlf=input should not show as unstaged
  5405. when their content hasn't changed.
  5406. """
  5407. # Set autocrlf=input BEFORE committing
  5408. c = self.repo.get_config()
  5409. c.set("core", "autocrlf", "input")
  5410. c.write_to_path()
  5411. # Create and commit file with CRLF endings
  5412. file_path = os.path.join(self.repo.path, "crlf-test.dsp")
  5413. with open(file_path, "wb") as f:
  5414. f.write(b"# Microsoft DSP file\r\n\r\nContent here\r\n")
  5415. porcelain.add(repo=self.repo.path, paths=[file_path])
  5416. porcelain.commit(
  5417. repo=self.repo.path,
  5418. message=b"add dsp file",
  5419. author=b"author <email>",
  5420. committer=b"committer <email>",
  5421. )
  5422. # File was normalized to LF in index, but working tree still has CRLF
  5423. # Status should be clean because comparison normalizes working tree too
  5424. results = porcelain.status(self.repo)
  5425. self.assertListEqual(results.unstaged, [])
  5426. def test_get_tree_changes_add(self) -> None:
  5427. """Unit test for get_tree_changes add."""
  5428. # Make a dummy file, stage
  5429. filename = "bar"
  5430. fullpath = os.path.join(self.repo.path, filename)
  5431. with open(fullpath, "w") as f:
  5432. f.write("stuff")
  5433. porcelain.add(repo=self.repo.path, paths=fullpath)
  5434. porcelain.commit(
  5435. repo=self.repo.path,
  5436. message=b"test status",
  5437. author=b"author <email>",
  5438. committer=b"committer <email>",
  5439. )
  5440. filename = "foo"
  5441. fullpath = os.path.join(self.repo.path, filename)
  5442. with open(fullpath, "w") as f:
  5443. f.write("stuff")
  5444. porcelain.add(repo=self.repo.path, paths=fullpath)
  5445. changes = porcelain.get_tree_changes(self.repo.path)
  5446. self.assertEqual(changes["add"][0], filename.encode("ascii"))
  5447. self.assertEqual(len(changes["add"]), 1)
  5448. self.assertEqual(len(changes["modify"]), 0)
  5449. self.assertEqual(len(changes["delete"]), 0)
  5450. def test_get_tree_changes_modify(self) -> None:
  5451. """Unit test for get_tree_changes modify."""
  5452. # Make a dummy file, stage, commit, modify
  5453. filename = "foo"
  5454. fullpath = os.path.join(self.repo.path, filename)
  5455. with open(fullpath, "w") as f:
  5456. f.write("stuff")
  5457. porcelain.add(repo=self.repo.path, paths=fullpath)
  5458. porcelain.commit(
  5459. repo=self.repo.path,
  5460. message=b"test status",
  5461. author=b"author <email>",
  5462. committer=b"committer <email>",
  5463. )
  5464. with open(fullpath, "w") as f:
  5465. f.write("otherstuff")
  5466. porcelain.add(repo=self.repo.path, paths=fullpath)
  5467. changes = porcelain.get_tree_changes(self.repo.path)
  5468. self.assertEqual(changes["modify"][0], filename.encode("ascii"))
  5469. self.assertEqual(len(changes["add"]), 0)
  5470. self.assertEqual(len(changes["modify"]), 1)
  5471. self.assertEqual(len(changes["delete"]), 0)
  5472. def test_get_tree_changes_delete(self) -> None:
  5473. """Unit test for get_tree_changes delete."""
  5474. # Make a dummy file, stage, commit, remove
  5475. filename = "foo"
  5476. fullpath = os.path.join(self.repo.path, filename)
  5477. with open(fullpath, "w") as f:
  5478. f.write("stuff")
  5479. porcelain.add(repo=self.repo.path, paths=fullpath)
  5480. porcelain.commit(
  5481. repo=self.repo.path,
  5482. message=b"test status",
  5483. author=b"author <email>",
  5484. committer=b"committer <email>",
  5485. )
  5486. cwd = os.getcwd()
  5487. self.addCleanup(os.chdir, cwd)
  5488. os.chdir(self.repo.path)
  5489. porcelain.remove(repo=self.repo.path, paths=[filename])
  5490. changes = porcelain.get_tree_changes(self.repo.path)
  5491. self.assertEqual(changes["delete"][0], filename.encode("ascii"))
  5492. self.assertEqual(len(changes["add"]), 0)
  5493. self.assertEqual(len(changes["modify"]), 0)
  5494. self.assertEqual(len(changes["delete"]), 1)
  5495. def test_get_untracked_paths(self) -> None:
  5496. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5497. f.write("ignored\n")
  5498. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  5499. f.write("blah\n")
  5500. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5501. f.write("blah\n")
  5502. os.symlink(
  5503. os.path.join(self.repo.path, os.pardir, "external_target"),
  5504. os.path.join(self.repo.path, "link"),
  5505. )
  5506. self.assertEqual(
  5507. {"ignored", "notignored", ".gitignore", "link"},
  5508. set(
  5509. porcelain.get_untracked_paths(
  5510. self.repo.path, self.repo.path, self.repo.open_index()
  5511. )
  5512. ),
  5513. )
  5514. self.assertEqual(
  5515. {".gitignore", "notignored", "link"},
  5516. set(porcelain.status(self.repo).untracked),
  5517. )
  5518. self.assertEqual(
  5519. {".gitignore", "notignored", "ignored", "link"},
  5520. set(porcelain.status(self.repo, ignored=True).untracked),
  5521. )
  5522. def test_get_untracked_paths_subrepo(self) -> None:
  5523. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5524. f.write("nested/\n")
  5525. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5526. f.write("blah\n")
  5527. subrepo = Repo.init(os.path.join(self.repo.path, "nested"), mkdir=True)
  5528. with open(os.path.join(subrepo.path, "ignored"), "w") as f:
  5529. f.write("bleep\n")
  5530. with open(os.path.join(subrepo.path, "with"), "w") as f:
  5531. f.write("bloop\n")
  5532. with open(os.path.join(subrepo.path, "manager"), "w") as f:
  5533. f.write("blop\n")
  5534. self.assertEqual(
  5535. {".gitignore", "notignored", os.path.join("nested", "")},
  5536. set(
  5537. porcelain.get_untracked_paths(
  5538. self.repo.path, self.repo.path, self.repo.open_index()
  5539. )
  5540. ),
  5541. )
  5542. self.assertEqual(
  5543. {".gitignore", "notignored"},
  5544. set(
  5545. porcelain.get_untracked_paths(
  5546. self.repo.path,
  5547. self.repo.path,
  5548. self.repo.open_index(),
  5549. exclude_ignored=True,
  5550. )
  5551. ),
  5552. )
  5553. self.assertEqual(
  5554. {"ignored", "with", "manager"},
  5555. set(
  5556. porcelain.get_untracked_paths(
  5557. subrepo.path, subrepo.path, subrepo.open_index()
  5558. )
  5559. ),
  5560. )
  5561. self.assertEqual(
  5562. set(),
  5563. set(
  5564. porcelain.get_untracked_paths(
  5565. subrepo.path,
  5566. self.repo.path,
  5567. self.repo.open_index(),
  5568. )
  5569. ),
  5570. )
  5571. self.assertEqual(
  5572. {
  5573. os.path.join("nested", "ignored"),
  5574. os.path.join("nested", "with"),
  5575. os.path.join("nested", "manager"),
  5576. },
  5577. set(
  5578. porcelain.get_untracked_paths(
  5579. self.repo.path,
  5580. subrepo.path,
  5581. self.repo.open_index(),
  5582. )
  5583. ),
  5584. )
  5585. def test_get_untracked_paths_nested_gitignore(self) -> None:
  5586. """Test directories with nested .gitignore files that ignore all contents."""
  5587. # Create cache directories with .gitignore files that contain "*"
  5588. cache_dirs = [".ruff_cache", ".pytest_cache", "__pycache__"]
  5589. for cache_dir in cache_dirs:
  5590. cache_path = os.path.join(self.repo.path, cache_dir)
  5591. os.mkdir(cache_path)
  5592. # Create .gitignore with * pattern (ignores everything)
  5593. with open(os.path.join(cache_path, ".gitignore"), "w") as f:
  5594. f.write("*\n")
  5595. # Create some files in the cache directory
  5596. with open(os.path.join(cache_path, "somefile.txt"), "w") as f:
  5597. f.write("cached data\n")
  5598. with open(os.path.join(cache_path, "data.json"), "w") as f:
  5599. f.write("{}\n")
  5600. # Create a normal untracked file
  5601. with open(os.path.join(self.repo.path, "untracked.txt"), "w") as f:
  5602. f.write("untracked content\n")
  5603. # Test with exclude_ignored=True (default for status)
  5604. untracked = set(
  5605. porcelain.get_untracked_paths(
  5606. self.repo.path,
  5607. self.repo.path,
  5608. self.repo.open_index(),
  5609. exclude_ignored=True,
  5610. untracked_files="normal",
  5611. )
  5612. )
  5613. # Cache directories should NOT be in untracked since all their contents are ignored
  5614. self.assertEqual({"untracked.txt"}, untracked)
  5615. # Test with exclude_ignored=False
  5616. untracked_with_ignored = set(
  5617. porcelain.get_untracked_paths(
  5618. self.repo.path,
  5619. self.repo.path,
  5620. self.repo.open_index(),
  5621. exclude_ignored=False,
  5622. untracked_files="normal",
  5623. )
  5624. )
  5625. # Cache directories should be included when not excluding ignored
  5626. expected = {"untracked.txt"}
  5627. for cache_dir in cache_dirs:
  5628. expected.add(cache_dir + os.sep)
  5629. self.assertEqual(expected, untracked_with_ignored)
  5630. # Test status() which uses exclude_ignored=True by default
  5631. status = porcelain.status(self.repo)
  5632. self.assertEqual(["untracked.txt"], status.untracked)
  5633. # Test status() with ignored=True which uses exclude_ignored=False
  5634. status_with_ignored = porcelain.status(self.repo, ignored=True)
  5635. # Should include cache directories
  5636. self.assertIn("untracked.txt", status_with_ignored.untracked)
  5637. for cache_dir in cache_dirs:
  5638. self.assertIn(cache_dir + "/", status_with_ignored.untracked)
  5639. def test_get_untracked_paths_mixed_directory(self) -> None:
  5640. """Test directory with both ignored and non-ignored files."""
  5641. # Create a directory with mixed content
  5642. mixed_dir = os.path.join(self.repo.path, "mixed")
  5643. os.mkdir(mixed_dir)
  5644. # Create .gitignore that ignores .log files
  5645. with open(os.path.join(mixed_dir, ".gitignore"), "w") as f:
  5646. f.write("*.log\n")
  5647. # Create ignored and non-ignored files
  5648. with open(os.path.join(mixed_dir, "debug.log"), "w") as f:
  5649. f.write("debug info\n")
  5650. with open(os.path.join(mixed_dir, "readme.txt"), "w") as f:
  5651. f.write("important\n")
  5652. # Test with exclude_ignored=True and normal mode
  5653. untracked = set(
  5654. porcelain.get_untracked_paths(
  5655. self.repo.path,
  5656. self.repo.path,
  5657. self.repo.open_index(),
  5658. exclude_ignored=True,
  5659. untracked_files="normal",
  5660. )
  5661. )
  5662. # In normal mode, should show the directory (matching git behavior)
  5663. self.assertEqual({os.path.join("mixed", "")}, untracked)
  5664. # Test with untracked_files="all"
  5665. untracked_all = set(
  5666. porcelain.get_untracked_paths(
  5667. self.repo.path,
  5668. self.repo.path,
  5669. self.repo.open_index(),
  5670. exclude_ignored=True,
  5671. untracked_files="all",
  5672. )
  5673. )
  5674. # Should list the non-ignored files
  5675. expected = {
  5676. os.path.join("mixed", ".gitignore"),
  5677. os.path.join("mixed", "readme.txt"),
  5678. }
  5679. self.assertEqual(expected, untracked_all)
  5680. def test_get_untracked_paths_specific_ignore_pattern(self) -> None:
  5681. """Test directory with .gitignore that ignores specific files, not all."""
  5682. # Create a directory
  5683. test_dir = os.path.join(self.repo.path, "testdir")
  5684. os.mkdir(test_dir)
  5685. # Create .gitignore that ignores only files named "test"
  5686. with open(os.path.join(test_dir, ".gitignore"), "w") as f:
  5687. f.write("test\n")
  5688. # Create files
  5689. with open(os.path.join(test_dir, "test"), "w") as f:
  5690. f.write("ignored\n")
  5691. with open(os.path.join(test_dir, "other.txt"), "w") as f:
  5692. f.write("not ignored\n")
  5693. # Test with exclude_ignored=True and normal mode
  5694. untracked = set(
  5695. porcelain.get_untracked_paths(
  5696. self.repo.path,
  5697. self.repo.path,
  5698. self.repo.open_index(),
  5699. exclude_ignored=True,
  5700. untracked_files="normal",
  5701. )
  5702. )
  5703. # Directory should be shown because it has non-ignored files
  5704. self.assertEqual({os.path.join("testdir", "")}, untracked)
  5705. def test_get_untracked_paths_nested_subdirs_all_ignored(self) -> None:
  5706. """Test directory containing only subdirectories where all files are ignored."""
  5707. # Create parent directory with .gitignore that ignores everything
  5708. parent_dir = os.path.join(self.repo.path, "parent")
  5709. os.mkdir(parent_dir)
  5710. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5711. f.write("*\n")
  5712. # Create subdirectories with files (all should be ignored by parent's .gitignore)
  5713. sub1 = os.path.join(parent_dir, "sub1")
  5714. sub2 = os.path.join(parent_dir, "sub2")
  5715. os.mkdir(sub1)
  5716. os.mkdir(sub2)
  5717. # Create files in subdirectories
  5718. with open(os.path.join(sub1, "file1.txt"), "w") as f:
  5719. f.write("content1\n")
  5720. with open(os.path.join(sub2, "file2.txt"), "w") as f:
  5721. f.write("content2\n")
  5722. # Create another normal untracked file
  5723. with open(os.path.join(self.repo.path, "normal.txt"), "w") as f:
  5724. f.write("normal\n")
  5725. # Test with exclude_ignored=True
  5726. untracked = set(
  5727. porcelain.get_untracked_paths(
  5728. self.repo.path,
  5729. self.repo.path,
  5730. self.repo.open_index(),
  5731. exclude_ignored=True,
  5732. untracked_files="normal",
  5733. )
  5734. )
  5735. # Parent directory should NOT be shown since all nested files are ignored
  5736. self.assertEqual({"normal.txt"}, untracked)
  5737. def test_get_untracked_paths_nested_subdirs_mixed(self) -> None:
  5738. """Test directory containing only subdirectories where some files are ignored, some aren't."""
  5739. # Create parent directory with .gitignore that ignores .log files
  5740. parent_dir = os.path.join(self.repo.path, "parent")
  5741. os.mkdir(parent_dir)
  5742. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5743. f.write("*.log\n")
  5744. # Create subdirectories
  5745. sub1 = os.path.join(parent_dir, "sub1")
  5746. sub2 = os.path.join(parent_dir, "sub2")
  5747. os.mkdir(sub1)
  5748. os.mkdir(sub2)
  5749. # sub1: only ignored files
  5750. with open(os.path.join(sub1, "debug.log"), "w") as f:
  5751. f.write("log content\n")
  5752. with open(os.path.join(sub1, "error.log"), "w") as f:
  5753. f.write("error log\n")
  5754. # sub2: mix of ignored and non-ignored files
  5755. with open(os.path.join(sub2, "access.log"), "w") as f:
  5756. f.write("access log\n")
  5757. with open(os.path.join(sub2, "readme.txt"), "w") as f:
  5758. f.write("important info\n")
  5759. # Test with exclude_ignored=True
  5760. untracked = set(
  5761. porcelain.get_untracked_paths(
  5762. self.repo.path,
  5763. self.repo.path,
  5764. self.repo.open_index(),
  5765. exclude_ignored=True,
  5766. untracked_files="normal",
  5767. )
  5768. )
  5769. # Parent directory SHOULD be shown since sub2 has non-ignored files
  5770. self.assertEqual({os.path.join("parent", "")}, untracked)
  5771. def test_get_untracked_paths_deeply_nested_all_ignored(self) -> None:
  5772. """Test deeply nested directories where all files are eventually ignored."""
  5773. # Create nested structure: parent/sub/subsub/
  5774. parent_dir = os.path.join(self.repo.path, "parent")
  5775. sub_dir = os.path.join(parent_dir, "sub")
  5776. subsub_dir = os.path.join(sub_dir, "subsub")
  5777. os.makedirs(subsub_dir)
  5778. # Parent has .gitignore that ignores everything
  5779. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5780. f.write("*\n")
  5781. # Create files at different levels
  5782. with open(os.path.join(subsub_dir, "deep_file.txt"), "w") as f:
  5783. f.write("deep content\n")
  5784. with open(os.path.join(sub_dir, "mid_file.txt"), "w") as f:
  5785. f.write("mid content\n")
  5786. # Test with exclude_ignored=True
  5787. untracked = set(
  5788. porcelain.get_untracked_paths(
  5789. self.repo.path,
  5790. self.repo.path,
  5791. self.repo.open_index(),
  5792. exclude_ignored=True,
  5793. untracked_files="normal",
  5794. )
  5795. )
  5796. # Parent directory should NOT be shown since all nested files are ignored
  5797. self.assertEqual(set(), untracked)
  5798. def test_get_untracked_paths_subdir(self) -> None:
  5799. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5800. f.write("subdir/\nignored")
  5801. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5802. f.write("blah\n")
  5803. os.mkdir(os.path.join(self.repo.path, "subdir"))
  5804. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  5805. f.write("foo")
  5806. with open(os.path.join(self.repo.path, "subdir", "ignored"), "w") as f:
  5807. f.write("foo")
  5808. self.assertEqual(
  5809. {
  5810. ".gitignore",
  5811. "notignored",
  5812. "ignored",
  5813. os.path.join("subdir", ""),
  5814. },
  5815. set(
  5816. porcelain.get_untracked_paths(
  5817. self.repo.path,
  5818. self.repo.path,
  5819. self.repo.open_index(),
  5820. )
  5821. ),
  5822. )
  5823. self.assertEqual(
  5824. {".gitignore", "notignored"},
  5825. set(
  5826. porcelain.get_untracked_paths(
  5827. self.repo.path,
  5828. self.repo.path,
  5829. self.repo.open_index(),
  5830. exclude_ignored=True,
  5831. )
  5832. ),
  5833. )
  5834. def test_get_untracked_paths_invalid_untracked_files(self) -> None:
  5835. with self.assertRaises(ValueError):
  5836. list(
  5837. porcelain.get_untracked_paths(
  5838. self.repo.path,
  5839. self.repo.path,
  5840. self.repo.open_index(),
  5841. untracked_files="invalid_value",
  5842. )
  5843. )
  5844. def test_get_untracked_paths_normal(self) -> None:
  5845. # Create an untracked directory with files
  5846. untracked_dir = os.path.join(self.repo.path, "untracked_dir")
  5847. os.mkdir(untracked_dir)
  5848. with open(os.path.join(untracked_dir, "file1.txt"), "w") as f:
  5849. f.write("untracked content")
  5850. with open(os.path.join(untracked_dir, "file2.txt"), "w") as f:
  5851. f.write("more untracked content")
  5852. # Test that "normal" mode works and returns only the directory
  5853. _, _, untracked = porcelain.status(
  5854. repo=self.repo.path, untracked_files="normal"
  5855. )
  5856. self.assertEqual(untracked, ["untracked_dir/"])
  5857. def test_get_untracked_paths_top_level_issue_1247(self) -> None:
  5858. """Test for issue #1247: ensure top-level untracked files are detected."""
  5859. # Create a single top-level untracked file
  5860. with open(os.path.join(self.repo.path, "sample.txt"), "w") as f:
  5861. f.write("test content")
  5862. # Test get_untracked_paths directly
  5863. untracked = list(
  5864. porcelain.get_untracked_paths(
  5865. self.repo.path, self.repo.path, self.repo.open_index()
  5866. )
  5867. )
  5868. self.assertIn(
  5869. "sample.txt",
  5870. untracked,
  5871. "Top-level file 'sample.txt' should be in untracked list",
  5872. )
  5873. # Test via status
  5874. status = porcelain.status(self.repo)
  5875. self.assertIn(
  5876. "sample.txt",
  5877. status.untracked,
  5878. "Top-level file 'sample.txt' should be in status.untracked",
  5879. )
  5880. # TODO(jelmer): Add test for dulwich.porcelain.daemon
  5881. class ShortlogTests(PorcelainTestCase):
  5882. def test_shortlog(self) -> None:
  5883. """Test porcelain.shortlog function with multiple authors and commits."""
  5884. # Create first file and commit
  5885. file_a = os.path.join(self.repo.path, "a.txt")
  5886. with open(file_a, "w") as f:
  5887. f.write("hello")
  5888. porcelain.add(self.repo.path, paths=[file_a])
  5889. porcelain.commit(
  5890. repo=self.repo.path,
  5891. message=b"Initial commit",
  5892. author=b"John <john@example.com>",
  5893. )
  5894. # Create second file and commit
  5895. file_b = os.path.join(self.repo.path, "b.txt")
  5896. with open(file_b, "w") as f:
  5897. f.write("update")
  5898. porcelain.add(self.repo.path, paths=[file_b])
  5899. porcelain.commit(
  5900. repo=self.repo.path,
  5901. message=b"Update file",
  5902. author=b"Doe <doe@example.com>",
  5903. )
  5904. # Call shortlog
  5905. output = porcelain.shortlog(self.repo.path)
  5906. expected = [
  5907. {"author": "John <john@example.com>", "messages": "Initial commit"},
  5908. {"author": "Doe <doe@example.com>", "messages": "Update file"},
  5909. ]
  5910. self.assertCountEqual(output, expected)
  5911. # Test summary output (count of messages)
  5912. output_summary = [
  5913. {"author": entry["author"], "count": len(entry["messages"].splitlines())}
  5914. for entry in output
  5915. ]
  5916. expected_summary = [
  5917. {"author": "John <john@example.com>", "count": 1},
  5918. {"author": "Doe <doe@example.com>", "count": 1},
  5919. ]
  5920. self.assertCountEqual(output_summary, expected_summary)
  5921. class UploadPackTests(PorcelainTestCase):
  5922. """Tests for upload_pack."""
  5923. def test_upload_pack(self) -> None:
  5924. outf = BytesIO()
  5925. exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf)
  5926. outlines = outf.getvalue().splitlines()
  5927. self.assertEqual([b"0000"], outlines)
  5928. self.assertEqual(0, exitcode)
  5929. class ReceivePackTests(PorcelainTestCase):
  5930. """Tests for receive_pack."""
  5931. def test_receive_pack(self) -> None:
  5932. filename = "foo"
  5933. fullpath = os.path.join(self.repo.path, filename)
  5934. with open(fullpath, "w") as f:
  5935. f.write("stuff")
  5936. porcelain.add(repo=self.repo.path, paths=fullpath)
  5937. self.repo.get_worktree().commit(
  5938. message=b"test status",
  5939. committer=b"committer <email>",
  5940. author=b"author <email>",
  5941. commit_timestamp=1402354300,
  5942. commit_timezone=0,
  5943. author_timestamp=1402354300,
  5944. author_timezone=0,
  5945. )
  5946. outf = BytesIO()
  5947. exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf)
  5948. outlines = outf.getvalue().splitlines()
  5949. self.assertEqual(
  5950. [
  5951. b"00a4319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status "
  5952. b"delete-refs quiet ofs-delta side-band-64k "
  5953. b"no-done object-format=sha1 symref=HEAD:refs/heads/master",
  5954. b"003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master",
  5955. b"0000",
  5956. ],
  5957. outlines,
  5958. )
  5959. self.assertEqual(0, exitcode)
  5960. class BranchListTests(PorcelainTestCase):
  5961. def test_standard(self) -> None:
  5962. self.assertEqual(set(), set(porcelain.branch_list(self.repo)))
  5963. def test_new_branch(self) -> None:
  5964. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5965. self.repo[b"HEAD"] = c1.id
  5966. porcelain.branch_create(self.repo, b"foo")
  5967. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  5968. def test_sort_by_refname(self) -> None:
  5969. """Test branch.sort=refname (default alphabetical)."""
  5970. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5971. self.repo[b"HEAD"] = c1.id
  5972. # Create branches in non-alphabetical order
  5973. porcelain.branch_create(self.repo, b"zebra")
  5974. porcelain.branch_create(self.repo, b"alpha")
  5975. porcelain.branch_create(self.repo, b"beta")
  5976. # Set branch.sort to refname (though it's the default)
  5977. config = self.repo.get_config()
  5978. config.set((b"branch",), b"sort", b"refname")
  5979. config.write_to_path()
  5980. # Should be sorted alphabetically
  5981. branches = porcelain.branch_list(self.repo)
  5982. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5983. def test_sort_by_refname_reverse(self) -> None:
  5984. """Test branch.sort=-refname (reverse alphabetical)."""
  5985. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5986. self.repo[b"HEAD"] = c1.id
  5987. # Create branches
  5988. porcelain.branch_create(self.repo, b"zebra")
  5989. porcelain.branch_create(self.repo, b"alpha")
  5990. porcelain.branch_create(self.repo, b"beta")
  5991. # Set branch.sort to -refname
  5992. config = self.repo.get_config()
  5993. config.set((b"branch",), b"sort", b"-refname")
  5994. config.write_to_path()
  5995. # Should be sorted reverse alphabetically
  5996. branches = porcelain.branch_list(self.repo)
  5997. self.assertEqual([b"zebra", b"master", b"beta", b"alpha"], branches)
  5998. def test_sort_by_committerdate(self) -> None:
  5999. """Test branch.sort=committerdate."""
  6000. # Use build_commit_graph to create proper commits with specific times
  6001. c1, c2, c3 = build_commit_graph(
  6002. self.repo.object_store,
  6003. [[1], [2], [3]],
  6004. attrs={
  6005. 1: {"commit_time": 1000}, # oldest
  6006. 2: {"commit_time": 2000}, # newest
  6007. 3: {"commit_time": 1500}, # middle
  6008. },
  6009. )
  6010. self.repo[b"HEAD"] = c1.id
  6011. # Create branches pointing to different commits
  6012. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  6013. self.repo.refs[b"refs/heads/oldest"] = c1.id
  6014. self.repo.refs[b"refs/heads/newest"] = c2.id
  6015. self.repo.refs[b"refs/heads/middle"] = c3.id
  6016. # Set branch.sort to committerdate
  6017. config = self.repo.get_config()
  6018. config.set((b"branch",), b"sort", b"committerdate")
  6019. config.write_to_path()
  6020. # Should be sorted by commit time (oldest first)
  6021. branches = porcelain.branch_list(self.repo)
  6022. self.assertEqual([b"master", b"oldest", b"middle", b"newest"], branches)
  6023. def test_sort_by_committerdate_reverse(self) -> None:
  6024. """Test branch.sort=-committerdate."""
  6025. # Use build_commit_graph to create proper commits with specific times
  6026. c1, c2, c3 = build_commit_graph(
  6027. self.repo.object_store,
  6028. [[1], [2], [3]],
  6029. attrs={
  6030. 1: {"commit_time": 1000}, # oldest
  6031. 2: {"commit_time": 2000}, # newest
  6032. 3: {"commit_time": 1500}, # middle
  6033. },
  6034. )
  6035. self.repo[b"HEAD"] = c1.id
  6036. # Create branches pointing to different commits
  6037. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  6038. self.repo.refs[b"refs/heads/oldest"] = c1.id
  6039. self.repo.refs[b"refs/heads/newest"] = c2.id
  6040. self.repo.refs[b"refs/heads/middle"] = c3.id
  6041. # Set branch.sort to -committerdate
  6042. config = self.repo.get_config()
  6043. config.set((b"branch",), b"sort", b"-committerdate")
  6044. config.write_to_path()
  6045. # Should be sorted by commit time (newest first)
  6046. branches = porcelain.branch_list(self.repo)
  6047. self.assertEqual([b"newest", b"middle", b"master", b"oldest"], branches)
  6048. def test_sort_default(self) -> None:
  6049. """Test default sorting (no config)."""
  6050. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6051. self.repo[b"HEAD"] = c1.id
  6052. # Create branches in non-alphabetical order
  6053. porcelain.branch_create(self.repo, b"zebra")
  6054. porcelain.branch_create(self.repo, b"alpha")
  6055. porcelain.branch_create(self.repo, b"beta")
  6056. # No config set - should default to alphabetical
  6057. branches = porcelain.branch_list(self.repo)
  6058. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  6059. class BranchRemoteListTests(PorcelainTestCase):
  6060. def test_no_remote_branches(self) -> None:
  6061. """Test with no remote branches."""
  6062. result = porcelain.branch_remotes_list(self.repo)
  6063. self.assertEqual([], result)
  6064. def test_remote_branches_refname_sort(self) -> None:
  6065. """Test remote branches sorting with refname (alphabetical)."""
  6066. # Create some remote branches
  6067. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6068. # Create remote branches is non-alphabetical order
  6069. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  6070. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  6071. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  6072. self.repo.refs[b"refs/remotes/origin/feature-4"] = c1.id
  6073. # Set branch.sort to refname
  6074. config = self.repo.get_config()
  6075. config.set((b"branch",), b"sort", b"refname")
  6076. config.write_to_path()
  6077. # Should return only branch names, sorted alphabetically
  6078. branches = porcelain.branch_remotes_list(self.repo)
  6079. expected = [
  6080. b"origin/feature-1",
  6081. b"origin/feature-2",
  6082. b"origin/feature-3",
  6083. b"origin/feature-4",
  6084. ]
  6085. self.assertEqual(expected, branches)
  6086. def test_remote_branches_refname_reverse_sort(self) -> None:
  6087. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6088. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  6089. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  6090. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  6091. self.repo.refs[b"refs/remotes/origin/feature-4"] = c1.id
  6092. # Set branch.sort to -refname
  6093. config = self.repo.get_config()
  6094. config.set((b"branch",), b"sort", b"-refname")
  6095. config.write_to_path()
  6096. branches = porcelain.branch_remotes_list(self.repo)
  6097. expected = [
  6098. b"origin/feature-4",
  6099. b"origin/feature-3",
  6100. b"origin/feature-2",
  6101. b"origin/feature-1",
  6102. ]
  6103. self.assertEqual(expected, branches)
  6104. def test_remote_branches_committerdate_sort(self) -> None:
  6105. """Test remote branches sorting with committerdate"""
  6106. # Create commits with different timestamps
  6107. c1, c2, c3 = build_commit_graph(
  6108. self.repo.object_store,
  6109. [[1], [2], [3]],
  6110. attrs={
  6111. 1: {"commit_time": 1000},
  6112. 2: {"commit_time": 2000},
  6113. 3: {"commit_time": 3000},
  6114. },
  6115. )
  6116. self.repo.refs[b"refs/remotes/origin/oldest"] = c1.id
  6117. self.repo.refs[b"refs/remotes/origin/middle"] = c2.id
  6118. self.repo.refs[b"refs/remotes/origin/newest"] = c3.id
  6119. # Set branch.sort to committerdate
  6120. config = self.repo.get_config()
  6121. config.set((b"branch",), b"sort", b"committerdate")
  6122. config.write_to_path()
  6123. branches = porcelain.branch_remotes_list(self.repo)
  6124. # Should be sorted by commit time (oldest first), then alphabetically for same time
  6125. expected = [b"origin/oldest", b"origin/middle", b"origin/newest"]
  6126. self.assertEqual(expected, branches)
  6127. def test_remote_branches_committerdate_reverse_sort(self) -> None:
  6128. """Test remote branches sorting with -committerdate."""
  6129. c1, c2, c3 = build_commit_graph(
  6130. self.repo.object_store,
  6131. [[1], [2], [3]],
  6132. attrs={
  6133. 1: {"commit_time": 1000},
  6134. 2: {"commit_time": 2000},
  6135. 3: {"commit_time": 1500},
  6136. },
  6137. )
  6138. self.repo.refs[b"refs/remotes/origin/oldest"] = c1.id
  6139. self.repo.refs[b"refs/remotes/origin/newest"] = c2.id
  6140. self.repo.refs[b"refs/remotes/origin/middle"] = c3.id
  6141. # Set branch.sort to -committerdate
  6142. config = self.repo.get_config()
  6143. config.set((b"branch",), b"sort", b"-committerdate")
  6144. config.write_to_path()
  6145. branches = porcelain.branch_remotes_list(self.repo)
  6146. # Should be sorted by commit time (newest first), then alphabetically for same time
  6147. expected = [b"origin/newest", b"origin/middle", b"origin/oldest"]
  6148. self.assertEqual(expected, branches)
  6149. def test_remote_branches_authordate_sort(self) -> None:
  6150. """Test remote branches sorting with authordate."""
  6151. c1, c2, c3 = build_commit_graph(
  6152. self.repo.object_store,
  6153. [[1], [2], [3]],
  6154. attrs={
  6155. 1: {"author_time": 1500},
  6156. 2: {"author_time": 2000},
  6157. 3: {"author_time": 1000},
  6158. },
  6159. )
  6160. self.repo.refs[b"refs/remotes/origin/middle"] = c1.id
  6161. self.repo.refs[b"refs/remotes/origin/newest"] = c2.id
  6162. self.repo.refs[b"refs/remotes/origin/oldest"] = c3.id
  6163. # Set branch.sort to authordate
  6164. config = self.repo.get_config()
  6165. config.set((b"branch",), b"sort", b"authordate")
  6166. config.write_to_path()
  6167. branches = porcelain.branch_remotes_list(self.repo)
  6168. expected = [b"origin/oldest", b"origin/middle", b"origin/newest"]
  6169. self.assertEqual(expected, branches)
  6170. def test_unknown_sort_key(self) -> None:
  6171. """Test that unknown sort key raises ValueError."""
  6172. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6173. self.repo.refs[b"refs/remotes/origin/master"] = c1.id
  6174. # Set branch.sort to unknown key
  6175. config = self.repo.get_config()
  6176. config.set((b"branch",), b"sort", b"unknown")
  6177. config.write_to_path()
  6178. with self.assertRaises(ValueError) as cm:
  6179. porcelain.branch_remotes_list(self.repo)
  6180. self.assertIn("Unknown sort key: unknown", str(cm.exception))
  6181. def test_default_sort_no_config(self) -> None:
  6182. """Test default sorting when no config is set."""
  6183. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6184. self.repo.refs[b"refs/remotes/origin/feature-1"] = c1.id
  6185. self.repo.refs[b"refs/remotes/origin/feature-2"] = c1.id
  6186. self.repo.refs[b"refs/remotes/origin/feature-3"] = c1.id
  6187. # No config set - should default to alphabetical
  6188. branches = porcelain.branch_remotes_list(self.repo)
  6189. expected = [b"origin/feature-1", b"origin/feature-2", b"origin/feature-3"]
  6190. self.assertEqual(expected, branches)
  6191. class BranchMergedTests(PorcelainTestCase):
  6192. def test_no_merged_branches(self) -> None:
  6193. """Test with no merged branches."""
  6194. # Create complete graph: c1 → c2 (master), c1 → c3 (feature)
  6195. [_c1, c2, c3] = build_commit_graph(
  6196. self.repo.object_store,
  6197. [
  6198. [1], # c1
  6199. [2, 1], # c2 → c1 (master line)
  6200. [3, 1], # c3 → c1 (diverged feature branch)
  6201. ],
  6202. )
  6203. self.repo.refs[b"HEAD"] = c2.id
  6204. self.repo.refs[b"refs/heads/master"] = c2.id
  6205. self.repo.refs[b"refs/heads/feature"] = c3.id
  6206. result = list(porcelain.merged_branches(self.repo))
  6207. self.assertEqual([b"master"], result)
  6208. def test_all_branches_merged(self) -> None:
  6209. """Test when all branches are merged into current."""
  6210. # Create linear history: c1 → c2 → c3 (HEAD)
  6211. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  6212. self.repo.refs[b"HEAD"] = c3.id
  6213. self.repo.refs[b"refs/heads/master"] = c3.id
  6214. self.repo.refs[b"refs/heads/feature-1"] = c2.id # Merged (ancestor)
  6215. self.repo.refs[b"refs/heads/feature-2"] = c1.id # Merged (ancestor)
  6216. branches = list(porcelain.merged_branches(self.repo))
  6217. expected = [b"feature-1", b"master", b"feature-2"]
  6218. expected.sort()
  6219. branches.sort()
  6220. self.assertEqual(expected, branches)
  6221. def test_some_branches_merged(self) -> None:
  6222. """Test when some branches are merged, some are not."""
  6223. # c1 → c2 → c3 (HEAD/master)
  6224. # c1 → c4 → c5 (feature-1 - diverged)
  6225. [_c1, c2, c3, _c4, c5] = build_commit_graph(
  6226. self.repo.object_store,
  6227. [
  6228. [1], # c1
  6229. [2, 1], # c2 → c1 (master line)
  6230. [3, 2], # c3 → c2 (HEAD)
  6231. [4, 1], # c4 → c1 (feature branch)
  6232. [5, 4], # c5 → c4 (feature branch)
  6233. ],
  6234. )
  6235. self.repo.refs[b"HEAD"] = c3.id
  6236. self.repo.refs[b"refs/heads/master"] = c3.id
  6237. self.repo.refs[b"refs/heads/feature-1"] = c5.id # Not merged (diverged)
  6238. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Merged (ancestor)
  6239. branches = list(porcelain.merged_branches(self.repo))
  6240. expected = [b"feature-2", b"master"]
  6241. expected.sort()
  6242. branches.sort()
  6243. self.assertEqual(expected, branches)
  6244. def test_only_current_branch_merged(self) -> None:
  6245. """Test when only current branch exists."""
  6246. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6247. self.repo.refs[b"HEAD"] = c1.id
  6248. self.repo.refs[b"refs/heads/master"] = c1.id
  6249. result = list(porcelain.merged_branches(self.repo))
  6250. self.assertEqual([b"master"], result)
  6251. class BranchNoMergedTests(PorcelainTestCase):
  6252. def test_all_branches_merged(self) -> None:
  6253. """Test when all branches are merged - should return empty list."""
  6254. # Create linear history: c1 → c2 → c3 (HEAD)
  6255. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  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-1"] = c2.id # Merged (ancestor)
  6259. self.repo.refs[b"refs/heads/feature-2"] = c1.id # Merged (ancestor)
  6260. result = list(porcelain.no_merged_branches(self.repo))
  6261. self.assertEqual([], result)
  6262. def test_no_merged_branches(self) -> None:
  6263. """Test with some non-merged branches."""
  6264. # Create complete graph: c1 → c2 (master), c1 → c3 (feature)
  6265. [_c1, c2, c3] = build_commit_graph(
  6266. self.repo.object_store,
  6267. [
  6268. [1], # c1
  6269. [2, 1], # c2 → c1 (master line)
  6270. [3, 1], # c3 → c1 (diverged feature branch)
  6271. ],
  6272. )
  6273. self.repo.refs[b"HEAD"] = c2.id
  6274. self.repo.refs[b"refs/heads/master"] = c2.id
  6275. self.repo.refs[b"refs/heads/feature"] = c3.id
  6276. result = list(porcelain.no_merged_branches(self.repo))
  6277. self.assertEqual([b"feature"], result)
  6278. def test_some_branches_not_merged(self) -> None:
  6279. """Test when some branches are merged, some are not."""
  6280. # c1 → c2 → c3 (HEAD/master)
  6281. # c1 → c4 → c5 (feature-1 - diverged)
  6282. [_c1, c2, c3, _c4, c5] = build_commit_graph(
  6283. self.repo.object_store,
  6284. [
  6285. [1], # c1
  6286. [2, 1], # c2 → c1 (master line)
  6287. [3, 2], # c3 → c2 (HEAD)
  6288. [4, 1], # c4 → c1 (feature branch)
  6289. [5, 4], # c5 → c4 (feature branch)
  6290. ],
  6291. )
  6292. self.repo.refs[b"HEAD"] = c3.id
  6293. self.repo.refs[b"refs/heads/master"] = c3.id
  6294. self.repo.refs[b"refs/heads/feature-1"] = c5.id # Not merged (diverged)
  6295. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Merged (ancestor)
  6296. result = list(porcelain.no_merged_branches(self.repo))
  6297. self.assertEqual([b"feature-1"], result)
  6298. def test_multiple_branches_not_merged(self) -> None:
  6299. """Test with multiple non-merged branches."""
  6300. # c1 → c2 (HEAD/master)
  6301. # c1 → c3 (feature-1 - diverged)
  6302. # c1 → c4 (feature-2 - diverged)
  6303. [_c1, c2, c3, c4] = build_commit_graph(
  6304. self.repo.object_store,
  6305. [
  6306. [1], # c1
  6307. [2, 1], # c2 → c1 (master line)
  6308. [3, 1], # c3 → c1 (feature-1 branch)
  6309. [4, 1], # c4 → c1 (feature-2 branch)
  6310. ],
  6311. )
  6312. self.repo.refs[b"HEAD"] = c2.id
  6313. self.repo.refs[b"refs/heads/master"] = c2.id
  6314. self.repo.refs[b"refs/heads/feature-1"] = c3.id # Not merged (diverged)
  6315. self.repo.refs[b"refs/heads/feature-2"] = c4.id # Not merged (diverged)
  6316. branches = list(porcelain.no_merged_branches(self.repo))
  6317. expected = [b"feature-1", b"feature-2"]
  6318. expected.sort()
  6319. branches.sort()
  6320. self.assertEqual(expected, branches)
  6321. def test_only_current_branch_exists(self) -> None:
  6322. """Test when only current branch exists - should return empty list."""
  6323. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6324. self.repo.refs[b"HEAD"] = c1.id
  6325. self.repo.refs[b"refs/heads/master"] = c1.id
  6326. result = list(porcelain.no_merged_branches(self.repo))
  6327. self.assertEqual([], result)
  6328. class BranchContainsTests(PorcelainTestCase):
  6329. def test_commit_in_single_branch(self) -> None:
  6330. """Test commit contained in only one branch."""
  6331. # Create: c1 → c2 (master), c1 → c3 (feature)
  6332. [_c1, c2, c3] = build_commit_graph(
  6333. self.repo.object_store,
  6334. [
  6335. [1], # c1
  6336. [2, 1], # c2 → c1 (master line)
  6337. [3, 1], # c3 → c1 (feature branch)
  6338. ],
  6339. )
  6340. self.repo.refs[b"HEAD"] = c2.id
  6341. self.repo.refs[b"refs/heads/master"] = c2.id
  6342. self.repo.refs[b"refs/heads/feature"] = c3.id
  6343. # c2 is only in master branch
  6344. result = list(porcelain.branches_containing(self.repo, c2.id.decode()))
  6345. self.assertEqual([b"master"], result)
  6346. # c3 is only in feature branch
  6347. result = list(porcelain.branches_containing(self.repo, c3.id.decode()))
  6348. self.assertEqual([b"feature"], result)
  6349. def test_commit_in_multiple_branches(self) -> None:
  6350. """Test commit contained in multiple branches."""
  6351. # Create: c1 → c2 → c3 (master), c2 → c4 (feature)
  6352. [c1, c2, c3, c4] = build_commit_graph(
  6353. self.repo.object_store,
  6354. [
  6355. [1], # c1
  6356. [2, 1], # c2 → c1
  6357. [3, 2], # c3 → c2 (master)
  6358. [4, 2], # c4 → c2 (feature)
  6359. ],
  6360. )
  6361. self.repo.refs[b"HEAD"] = c3.id
  6362. self.repo.refs[b"refs/heads/master"] = c3.id
  6363. self.repo.refs[b"refs/heads/feature"] = c4.id
  6364. # c2 is in both branches (common ancestor)
  6365. branches = list(porcelain.branches_containing(self.repo, c2.id.decode()))
  6366. expected = [b"master", b"feature"]
  6367. expected.sort()
  6368. branches.sort()
  6369. self.assertEqual(expected, branches)
  6370. # c1 is in both branches (older common ancestor)
  6371. branches = list(porcelain.branches_containing(self.repo, c1.id.decode()))
  6372. expected = [b"master", b"feature"]
  6373. expected.sort()
  6374. branches.sort()
  6375. self.assertEqual(expected, branches)
  6376. def test_commit_in_all_branches(self) -> None:
  6377. """Test commit contained in all branches."""
  6378. # Create linear history: c1 → c2 → c3 (HEAD/master)
  6379. [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  6380. self.repo.refs[b"HEAD"] = c3.id
  6381. self.repo.refs[b"refs/heads/master"] = c3.id
  6382. self.repo.refs[b"refs/heads/feature-1"] = c3.id # Same as master
  6383. self.repo.refs[b"refs/heads/feature-2"] = c2.id # Ancestor
  6384. # c1 is in all branches
  6385. branches = list(porcelain.branches_containing(self.repo, c1.id.decode()))
  6386. expected = [b"master", b"feature-1", b"feature-2"]
  6387. expected.sort()
  6388. branches.sort()
  6389. self.assertEqual(expected, branches)
  6390. def test_commit_in_no_branches(self) -> None:
  6391. """Test commit not contained in any branch."""
  6392. # Create: c1 → c2 (master), c1 → c3 (feature), orphan c4
  6393. [_c1, c2, c3, c4] = build_commit_graph(
  6394. self.repo.object_store,
  6395. [
  6396. [1], # c1
  6397. [2, 1], # c2 → c1 (master)
  6398. [3, 1], # c3 → c1 (feature)
  6399. [4], # c4 (orphan commit)
  6400. ],
  6401. )
  6402. self.repo.refs[b"HEAD"] = c2.id
  6403. self.repo.refs[b"refs/heads/master"] = c2.id
  6404. self.repo.refs[b"refs/heads/feature"] = c3.id
  6405. # c4 is not in any branch
  6406. result = list(porcelain.branches_containing(self.repo, c4.id.decode()))
  6407. self.assertEqual([], result)
  6408. def test_commit_ref_by_branch_name(self) -> None:
  6409. """Test using branch name as commit reference."""
  6410. # Create: c1 → c2 (master), c1 → c3 (feature)
  6411. [_c1, c2, c3] = build_commit_graph(
  6412. self.repo.object_store,
  6413. [
  6414. [1], # c1
  6415. [2, 1], # c2 → c1 (master)
  6416. [3, 1], # c3 → c1 (feature)
  6417. ],
  6418. )
  6419. self.repo.refs[b"HEAD"] = c2.id
  6420. self.repo.refs[b"refs/heads/master"] = c2.id
  6421. self.repo.refs[b"refs/heads/feature"] = c3.id
  6422. # Use "master" as commit reference - should find master branch
  6423. result = list(porcelain.branches_containing(self.repo, "master"))
  6424. self.assertEqual([b"master"], result)
  6425. # Use "feature" as commit reference - should find feature branch
  6426. result = list(porcelain.branches_containing(self.repo, "feature"))
  6427. self.assertEqual([b"feature"], result)
  6428. def test_commit_ref_by_head(self) -> None:
  6429. """Test using HEAD as commit reference."""
  6430. # Create: c1 → c2 → c3 (HEAD/master)
  6431. [_c1, c2, c3] = build_commit_graph(
  6432. self.repo.object_store, [[1], [2, 1], [3, 2]]
  6433. )
  6434. self.repo.refs[b"HEAD"] = c3.id
  6435. self.repo.refs[b"refs/heads/master"] = c3.id
  6436. self.repo.refs[b"refs/heads/feature"] = c2.id # Ancestor
  6437. # Use "HEAD" as commit reference
  6438. result = list(porcelain.branches_containing(self.repo, "HEAD"))
  6439. self.assertEqual([b"master"], result)
  6440. def test_invalid_commit_ref(self) -> None:
  6441. """Test with invalid commit reference."""
  6442. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6443. self.repo.refs[b"HEAD"] = c1.id
  6444. self.repo.refs[b"refs/heads/master"] = c1.id
  6445. # Test with non-existent commit
  6446. with self.assertRaises(KeyError) as cm:
  6447. list(porcelain.branches_containing(self.repo, "nonexistent"))
  6448. self.assertEqual(b"nonexistent", cm.exception.args[0])
  6449. # Test with invalid SHA
  6450. with self.assertRaises(KeyError) as cm:
  6451. list(porcelain.branches_containing(self.repo, "invalid-sha"))
  6452. self.assertEqual(b"invalid-sha", cm.exception.args[0])
  6453. def test_short_sha_reference(self) -> None:
  6454. """Test using short SHA as commit reference."""
  6455. # Create: c1 → c2 (master)
  6456. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2, 1]])
  6457. self.repo.refs[b"HEAD"] = c2.id
  6458. self.repo.refs[b"refs/heads/master"] = c2.id
  6459. # Use short SHA (first 7 characters)
  6460. short_sha = c1.id.decode()[:7]
  6461. result = list(porcelain.branches_containing(self.repo, short_sha))
  6462. self.assertEqual([b"master"], result)
  6463. class FilterBranchesByPatternTests(PorcelainTestCase):
  6464. """Tests for filter_branches_by_pattern function."""
  6465. def test_empty_branches(self) -> None:
  6466. """Test with empty branches list."""
  6467. result = porcelain.filter_branches_by_pattern([], "feature-*")
  6468. self.assertEqual([], result)
  6469. def test_star_pattern(self) -> None:
  6470. """Test wildcard pattern matching."""
  6471. branches = [b"main", b"feature-1", b"feature-2", b"develop", b"hotfix-bug"]
  6472. result = porcelain.filter_branches_by_pattern(branches, "feature-*")
  6473. expected = [b"feature-1", b"feature-2"]
  6474. self.assertEqual(expected, result)
  6475. def test_question_mark_pattern(self) -> None:
  6476. """Test single character wildcard pattern."""
  6477. branches = [b"main", b"feature-1", b"feature-2", b"feature-a", b"develop"]
  6478. result = porcelain.filter_branches_by_pattern(branches, "feature-?")
  6479. expected = [b"feature-1", b"feature-2", b"feature-a"]
  6480. self.assertEqual(expected, result)
  6481. def test_specific_pattern(self) -> None:
  6482. """Test exact match pattern."""
  6483. branches = [b"main", b"feature-1", b"feature-2", b"develop"]
  6484. result = porcelain.filter_branches_by_pattern(branches, "feature-1")
  6485. expected = [b"feature-1"]
  6486. self.assertEqual(expected, result)
  6487. def test_no_matches(self) -> None:
  6488. """Test pattern that matches no branches."""
  6489. branches = [b"main", b"feature-1", b"develop"]
  6490. result = porcelain.filter_branches_by_pattern(branches, "release-*")
  6491. self.assertEqual([], result)
  6492. def test_case_sensitive_pattern(self) -> None:
  6493. """Test case-sensitive pattern matching."""
  6494. branches = [b"Main", b"main", b"MAIN", b"develop"]
  6495. result = porcelain.filter_branches_by_pattern(branches, "main")
  6496. expected = [b"main"]
  6497. self.assertEqual(expected, result)
  6498. def test_multiple_patterns_behavior(self) -> None:
  6499. """Test that pattern works with multiple wildcards."""
  6500. branches = [
  6501. b"feature-login",
  6502. b"feature-signup",
  6503. b"bugfix-login",
  6504. b"hotfix-signup",
  6505. ]
  6506. result = porcelain.filter_branches_by_pattern(branches, "feature-*")
  6507. expected = [b"feature-login", b"feature-signup"]
  6508. self.assertEqual(expected, result)
  6509. def test_mixed_encoding_branches(self) -> None:
  6510. """Test with branches that have special characters."""
  6511. branches = [b"feature-1", b"feature/test", b"feature@prod", b"develop"]
  6512. result = porcelain.filter_branches_by_pattern(branches, "feature/*")
  6513. expected = [b"feature/test"]
  6514. self.assertEqual(expected, result)
  6515. def test_pattern_with_square_brackets(self) -> None:
  6516. """Test pattern with character classes."""
  6517. branches = [b"feature-1", b"feature-2", b"feature-a", b"feature-b", b"develop"]
  6518. result = porcelain.filter_branches_by_pattern(branches, "feature-[12]")
  6519. expected = [b"feature-1", b"feature-2"]
  6520. self.assertEqual(expected, result)
  6521. class BranchCreateTests(PorcelainTestCase):
  6522. def test_branch_exists(self) -> None:
  6523. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6524. self.repo[b"HEAD"] = c1.id
  6525. porcelain.branch_create(self.repo, b"foo")
  6526. self.assertRaises(porcelain.Error, porcelain.branch_create, self.repo, b"foo")
  6527. porcelain.branch_create(self.repo, b"foo", force=True)
  6528. def test_new_branch(self) -> None:
  6529. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6530. self.repo[b"HEAD"] = c1.id
  6531. porcelain.branch_create(self.repo, b"foo")
  6532. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  6533. def test_auto_setup_merge_true_from_remote_tracking(self) -> None:
  6534. """Test branch.autoSetupMerge=true sets up tracking from remote-tracking branch."""
  6535. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6536. self.repo[b"HEAD"] = c1.id
  6537. # Create a remote-tracking branch
  6538. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6539. # Set branch.autoSetupMerge to true (default)
  6540. config = self.repo.get_config()
  6541. config.set((b"branch",), b"autoSetupMerge", b"true")
  6542. config.write_to_path()
  6543. # Create branch from remote-tracking branch
  6544. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6545. # Verify tracking was set up
  6546. config = self.repo.get_config()
  6547. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6548. self.assertEqual(
  6549. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6550. )
  6551. def test_auto_setup_merge_false(self) -> None:
  6552. """Test branch.autoSetupMerge=false disables tracking setup."""
  6553. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6554. self.repo[b"HEAD"] = c1.id
  6555. # Create a remote-tracking branch
  6556. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6557. # Set branch.autoSetupMerge to false
  6558. config = self.repo.get_config()
  6559. config.set((b"branch",), b"autoSetupMerge", b"false")
  6560. config.write_to_path()
  6561. # Create branch from remote-tracking branch
  6562. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6563. # Verify tracking was NOT set up
  6564. config = self.repo.get_config()
  6565. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"remote")
  6566. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"merge")
  6567. def test_auto_setup_merge_always(self) -> None:
  6568. """Test branch.autoSetupMerge=always sets up tracking even from local branches."""
  6569. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6570. self.repo[b"HEAD"] = c1.id
  6571. self.repo.refs[b"refs/heads/main"] = c1.id
  6572. # Set branch.autoSetupMerge to always
  6573. config = self.repo.get_config()
  6574. config.set((b"branch",), b"autoSetupMerge", b"always")
  6575. config.write_to_path()
  6576. # Create branch from local branch - normally wouldn't set up tracking
  6577. porcelain.branch_create(self.repo, "feature", "main")
  6578. # With always, tracking should NOT be set up from local branches
  6579. # (Git only sets up tracking from remote-tracking branches even with always)
  6580. config = self.repo.get_config()
  6581. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"remote")
  6582. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"merge")
  6583. def test_auto_setup_merge_always_from_remote(self) -> None:
  6584. """Test branch.autoSetupMerge=always still sets up tracking from remote branches."""
  6585. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6586. self.repo[b"HEAD"] = c1.id
  6587. # Create a remote-tracking branch
  6588. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6589. # Set branch.autoSetupMerge to always
  6590. config = self.repo.get_config()
  6591. config.set((b"branch",), b"autoSetupMerge", b"always")
  6592. config.write_to_path()
  6593. # Create branch from remote-tracking branch
  6594. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6595. # Verify tracking was set up
  6596. config = self.repo.get_config()
  6597. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6598. self.assertEqual(
  6599. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6600. )
  6601. def test_auto_setup_merge_default(self) -> None:
  6602. """Test default behavior (no config) is same as true."""
  6603. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6604. self.repo[b"HEAD"] = c1.id
  6605. # Create a remote-tracking branch
  6606. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  6607. # Don't set any config - should default to true
  6608. # Create branch from remote-tracking branch
  6609. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  6610. # Verify tracking was set up
  6611. config = self.repo.get_config()
  6612. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  6613. self.assertEqual(
  6614. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  6615. )
  6616. class BranchDeleteTests(PorcelainTestCase):
  6617. def test_simple(self) -> None:
  6618. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6619. self.repo[b"HEAD"] = c1.id
  6620. porcelain.branch_create(self.repo, b"foo")
  6621. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  6622. porcelain.branch_delete(self.repo, b"foo")
  6623. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  6624. def test_simple_unicode(self) -> None:
  6625. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6626. self.repo[b"HEAD"] = c1.id
  6627. porcelain.branch_create(self.repo, "foo")
  6628. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  6629. porcelain.branch_delete(self.repo, "foo")
  6630. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  6631. class FetchTests(PorcelainTestCase):
  6632. def test_simple(self) -> None:
  6633. outstream = BytesIO()
  6634. errstream = BytesIO()
  6635. # create a file for initial commit
  6636. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6637. os.close(handle)
  6638. porcelain.add(repo=self.repo.path, paths=fullpath)
  6639. porcelain.commit(
  6640. repo=self.repo.path,
  6641. message=b"test",
  6642. author=b"test <email>",
  6643. committer=b"test <email>",
  6644. )
  6645. # Setup target repo
  6646. target_path = tempfile.mkdtemp()
  6647. self.addCleanup(shutil.rmtree, target_path)
  6648. target_repo = porcelain.clone(
  6649. self.repo.path, target=target_path, errstream=errstream
  6650. )
  6651. # create a second file to be pushed
  6652. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6653. os.close(handle)
  6654. porcelain.add(repo=self.repo.path, paths=fullpath)
  6655. porcelain.commit(
  6656. repo=self.repo.path,
  6657. message=b"test2",
  6658. author=b"test2 <email>",
  6659. committer=b"test2 <email>",
  6660. )
  6661. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  6662. target_repo.close()
  6663. # Fetch changes into the cloned repo
  6664. porcelain.fetch(target_path, "origin", outstream=outstream, errstream=errstream)
  6665. # Assert that fetch updated the local image of the remote
  6666. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  6667. # Check the target repo for pushed changes
  6668. with Repo(target_path) as r:
  6669. self.assertIn(self.repo[b"HEAD"].id, r)
  6670. def test_with_remote_name(self) -> None:
  6671. remote_name = "origin"
  6672. outstream = BytesIO()
  6673. errstream = BytesIO()
  6674. # create a file for initial commit
  6675. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6676. os.close(handle)
  6677. porcelain.add(repo=self.repo.path, paths=fullpath)
  6678. porcelain.commit(
  6679. repo=self.repo.path,
  6680. message=b"test",
  6681. author=b"test <email>",
  6682. committer=b"test <email>",
  6683. )
  6684. # Setup target repo
  6685. target_path = tempfile.mkdtemp()
  6686. self.addCleanup(shutil.rmtree, target_path)
  6687. target_repo = porcelain.clone(
  6688. self.repo.path, target=target_path, errstream=errstream
  6689. )
  6690. # Capture current refs
  6691. target_refs = target_repo.get_refs()
  6692. # create a second file to be pushed
  6693. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6694. os.close(handle)
  6695. porcelain.add(repo=self.repo.path, paths=fullpath)
  6696. porcelain.commit(
  6697. repo=self.repo.path,
  6698. message=b"test2",
  6699. author=b"test2 <email>",
  6700. committer=b"test2 <email>",
  6701. )
  6702. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  6703. target_config = target_repo.get_config()
  6704. target_config.set(
  6705. (b"remote", remote_name.encode()), b"url", self.repo.path.encode()
  6706. )
  6707. target_repo.close()
  6708. # Fetch changes into the cloned repo
  6709. porcelain.fetch(
  6710. target_path, remote_name, outstream=outstream, errstream=errstream
  6711. )
  6712. # Assert that fetch updated the local image of the remote
  6713. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  6714. # Check the target repo for pushed changes, as well as updates
  6715. # for the refs
  6716. with Repo(target_path) as r:
  6717. self.assertIn(self.repo[b"HEAD"].id, r)
  6718. self.assertNotEqual(self.repo.get_refs(), target_refs)
  6719. def assert_correct_remote_refs(
  6720. self, local_refs, remote_refs, remote_name=b"origin"
  6721. ) -> None:
  6722. """Assert that known remote refs corresponds to actual remote refs."""
  6723. local_ref_prefix = b"refs/heads"
  6724. remote_ref_prefix = b"refs/remotes/" + remote_name
  6725. locally_known_remote_refs = {
  6726. k[len(remote_ref_prefix) + 1 :]: v
  6727. for k, v in local_refs.items()
  6728. if k.startswith(remote_ref_prefix)
  6729. }
  6730. normalized_remote_refs = {
  6731. k[len(local_ref_prefix) + 1 :]: v
  6732. for k, v in remote_refs.items()
  6733. if k.startswith(local_ref_prefix)
  6734. }
  6735. if b"HEAD" in locally_known_remote_refs and b"HEAD" in remote_refs:
  6736. normalized_remote_refs[b"HEAD"] = remote_refs[b"HEAD"]
  6737. self.assertEqual(locally_known_remote_refs, normalized_remote_refs)
  6738. class RepackTests(PorcelainTestCase):
  6739. def test_empty(self) -> None:
  6740. porcelain.repack(self.repo)
  6741. def test_simple(self) -> None:
  6742. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6743. os.close(handle)
  6744. porcelain.add(repo=self.repo.path, paths=fullpath)
  6745. porcelain.repack(self.repo)
  6746. def test_write_bitmaps(self) -> None:
  6747. """Test that write_bitmaps generates bitmap files."""
  6748. # Create some content
  6749. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  6750. os.close(handle)
  6751. with open(fullpath, "w") as f:
  6752. f.write("test content")
  6753. porcelain.add(repo=self.repo.path, paths=fullpath)
  6754. porcelain.commit(
  6755. repo=self.repo.path,
  6756. message=b"test commit",
  6757. author=b"Test Author <test@example.com>",
  6758. committer=b"Test Committer <test@example.com>",
  6759. )
  6760. # Repack with bitmaps
  6761. porcelain.repack(self.repo, write_bitmaps=True)
  6762. # Check that bitmap files were created
  6763. pack_dir = os.path.join(self.repo.path, ".git", "objects", "pack")
  6764. bitmap_files = [f for f in os.listdir(pack_dir) if f.endswith(".bitmap")]
  6765. self.assertGreater(len(bitmap_files), 0)
  6766. class LsTreeTests(PorcelainTestCase):
  6767. def test_empty(self) -> None:
  6768. porcelain.commit(
  6769. repo=self.repo.path,
  6770. message=b"test status",
  6771. author=b"author <email>",
  6772. committer=b"committer <email>",
  6773. )
  6774. f = StringIO()
  6775. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  6776. self.assertEqual(f.getvalue(), "")
  6777. def test_simple(self) -> None:
  6778. # Commit a dummy file then modify it
  6779. fullpath = os.path.join(self.repo.path, "foo")
  6780. with open(fullpath, "w") as f:
  6781. f.write("origstuff")
  6782. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6783. porcelain.commit(
  6784. repo=self.repo.path,
  6785. message=b"test status",
  6786. author=b"author <email>",
  6787. committer=b"committer <email>",
  6788. )
  6789. output = StringIO()
  6790. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  6791. self.assertEqual(
  6792. output.getvalue(),
  6793. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n",
  6794. )
  6795. def test_recursive(self) -> None:
  6796. # Create a directory then write a dummy file in it
  6797. dirpath = os.path.join(self.repo.path, "adir")
  6798. filepath = os.path.join(dirpath, "afile")
  6799. os.mkdir(dirpath)
  6800. with open(filepath, "w") as f:
  6801. f.write("origstuff")
  6802. porcelain.add(repo=self.repo.path, paths=[filepath])
  6803. porcelain.commit(
  6804. repo=self.repo.path,
  6805. message=b"test status",
  6806. author=b"author <email>",
  6807. committer=b"committer <email>",
  6808. )
  6809. output = StringIO()
  6810. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  6811. self.assertEqual(
  6812. output.getvalue(),
  6813. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n",
  6814. )
  6815. output2 = StringIO()
  6816. porcelain.ls_tree(self.repo, b"HEAD", outstream=output2, recursive=True)
  6817. self.assertEqual(
  6818. output2.getvalue(),
  6819. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n"
  6820. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir"
  6821. "/afile\n",
  6822. )
  6823. class LsRemoteTests(PorcelainTestCase):
  6824. def test_empty(self) -> None:
  6825. result = porcelain.ls_remote(self.repo.path)
  6826. self.assertEqual({}, result.refs)
  6827. self.assertEqual({}, result.symrefs)
  6828. def test_some(self) -> None:
  6829. cid = porcelain.commit(
  6830. repo=self.repo.path,
  6831. message=b"test status",
  6832. author=b"author <email>",
  6833. committer=b"committer <email>",
  6834. )
  6835. result = porcelain.ls_remote(self.repo.path)
  6836. self.assertEqual(
  6837. {b"refs/heads/master": cid, b"HEAD": cid},
  6838. result.refs,
  6839. )
  6840. # HEAD should be a symref to refs/heads/master
  6841. self.assertEqual({b"HEAD": b"refs/heads/master"}, result.symrefs)
  6842. class LsFilesTests(PorcelainTestCase):
  6843. def test_empty(self) -> None:
  6844. self.assertEqual([], list(porcelain.ls_files(self.repo)))
  6845. def test_simple(self) -> None:
  6846. # Commit a dummy file then modify it
  6847. fullpath = os.path.join(self.repo.path, "foo")
  6848. with open(fullpath, "w") as f:
  6849. f.write("origstuff")
  6850. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6851. self.assertEqual([b"foo"], list(porcelain.ls_files(self.repo)))
  6852. class RemoteAddTests(PorcelainTestCase):
  6853. def test_new(self) -> None:
  6854. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6855. c = self.repo.get_config()
  6856. self.assertEqual(
  6857. c.get((b"remote", b"jelmer"), b"url"),
  6858. b"git://jelmer.uk/code/dulwich",
  6859. )
  6860. def test_exists(self) -> None:
  6861. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6862. self.assertRaises(
  6863. porcelain.RemoteExists,
  6864. porcelain.remote_add,
  6865. self.repo,
  6866. "jelmer",
  6867. "git://jelmer.uk/code/dulwich",
  6868. )
  6869. class RemoteRemoveTests(PorcelainTestCase):
  6870. def test_remove(self) -> None:
  6871. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  6872. c = self.repo.get_config()
  6873. self.assertEqual(
  6874. c.get((b"remote", b"jelmer"), b"url"),
  6875. b"git://jelmer.uk/code/dulwich",
  6876. )
  6877. porcelain.remote_remove(self.repo, "jelmer")
  6878. self.assertRaises(KeyError, porcelain.remote_remove, self.repo, "jelmer")
  6879. c = self.repo.get_config()
  6880. self.assertRaises(KeyError, c.get, (b"remote", b"jelmer"), b"url")
  6881. class CheckIgnoreTests(PorcelainTestCase):
  6882. def test_check_ignored(self) -> None:
  6883. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6884. f.write("foo")
  6885. foo_path = os.path.join(self.repo.path, "foo")
  6886. with open(foo_path, "w") as f:
  6887. f.write("BAR")
  6888. bar_path = os.path.join(self.repo.path, "bar")
  6889. with open(bar_path, "w") as f:
  6890. f.write("BAR")
  6891. self.assertEqual(["foo"], list(porcelain.check_ignore(self.repo, [foo_path])))
  6892. self.assertEqual([], list(porcelain.check_ignore(self.repo, [bar_path])))
  6893. def test_check_added_abs(self) -> None:
  6894. path = os.path.join(self.repo.path, "foo")
  6895. with open(path, "w") as f:
  6896. f.write("BAR")
  6897. self.repo.get_worktree().stage(["foo"])
  6898. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6899. f.write("foo\n")
  6900. self.assertEqual([], list(porcelain.check_ignore(self.repo, [path])))
  6901. self.assertEqual(
  6902. ["foo"],
  6903. list(porcelain.check_ignore(self.repo, [path], no_index=True)),
  6904. )
  6905. def test_check_added_rel(self) -> None:
  6906. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  6907. f.write("BAR")
  6908. self.repo.get_worktree().stage(["foo"])
  6909. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  6910. f.write("foo\n")
  6911. cwd = os.getcwd()
  6912. self.addCleanup(os.chdir, cwd)
  6913. os.mkdir(os.path.join(self.repo.path, "bar"))
  6914. os.chdir(os.path.join(self.repo.path, "bar"))
  6915. self.assertEqual(list(porcelain.check_ignore(self.repo, ["../foo"])), [])
  6916. self.assertEqual(
  6917. ["../foo"],
  6918. list(porcelain.check_ignore(self.repo, ["../foo"], no_index=True)),
  6919. )
  6920. class UpdateHeadTests(PorcelainTestCase):
  6921. def test_set_to_branch(self) -> None:
  6922. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6923. self.repo.refs[b"refs/heads/blah"] = c1.id
  6924. porcelain.update_head(self.repo, "blah")
  6925. self.assertEqual(c1.id, self.repo.head())
  6926. self.assertEqual(b"ref: refs/heads/blah", self.repo.refs.read_ref(b"HEAD"))
  6927. def test_set_to_branch_detached(self) -> None:
  6928. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6929. self.repo.refs[b"refs/heads/blah"] = c1.id
  6930. porcelain.update_head(self.repo, "blah", detached=True)
  6931. self.assertEqual(c1.id, self.repo.head())
  6932. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  6933. def test_set_to_commit_detached(self) -> None:
  6934. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6935. self.repo.refs[b"refs/heads/blah"] = c1.id
  6936. porcelain.update_head(self.repo, c1.id, detached=True)
  6937. self.assertEqual(c1.id, self.repo.head())
  6938. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  6939. def test_set_new_branch(self) -> None:
  6940. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  6941. self.repo.refs[b"refs/heads/blah"] = c1.id
  6942. porcelain.update_head(self.repo, "blah", new_branch="bar")
  6943. self.assertEqual(c1.id, self.repo.head())
  6944. self.assertEqual(b"ref: refs/heads/bar", self.repo.refs.read_ref(b"HEAD"))
  6945. class MailmapTests(PorcelainTestCase):
  6946. def test_no_mailmap(self) -> None:
  6947. self.assertEqual(
  6948. b"Jelmer Vernooij <jelmer@samba.org>",
  6949. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  6950. )
  6951. def test_mailmap_lookup(self) -> None:
  6952. with open(os.path.join(self.repo.path, ".mailmap"), "wb") as f:
  6953. f.write(
  6954. b"""\
  6955. Jelmer Vernooij <jelmer@debian.org>
  6956. """
  6957. )
  6958. self.assertEqual(
  6959. b"Jelmer Vernooij <jelmer@debian.org>",
  6960. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  6961. )
  6962. class FsckTests(PorcelainTestCase):
  6963. def test_none(self) -> None:
  6964. self.assertEqual([], list(porcelain.fsck(self.repo)))
  6965. def test_git_dir(self) -> None:
  6966. obj = Tree()
  6967. a = Blob()
  6968. a.data = b"foo"
  6969. obj.add(b".git", 0o100644, a.id)
  6970. self.repo.object_store.add_objects([(a, None), (obj, None)])
  6971. self.assertEqual(
  6972. [(obj.id, "invalid name .git")],
  6973. [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)],
  6974. )
  6975. class DescribeTests(PorcelainTestCase):
  6976. def test_no_commits(self) -> None:
  6977. self.assertRaises(KeyError, porcelain.describe, self.repo.path)
  6978. def test_single_commit(self) -> None:
  6979. fullpath = os.path.join(self.repo.path, "foo")
  6980. with open(fullpath, "w") as f:
  6981. f.write("BAR")
  6982. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6983. sha = porcelain.commit(
  6984. self.repo.path,
  6985. message=b"Some message",
  6986. author=b"Joe <joe@example.com>",
  6987. committer=b"Bob <bob@example.com>",
  6988. )
  6989. self.assertEqual(
  6990. "g{}".format(sha[:7].decode("ascii")),
  6991. porcelain.describe(self.repo.path),
  6992. )
  6993. def test_tag(self) -> None:
  6994. fullpath = os.path.join(self.repo.path, "foo")
  6995. with open(fullpath, "w") as f:
  6996. f.write("BAR")
  6997. porcelain.add(repo=self.repo.path, paths=[fullpath])
  6998. porcelain.commit(
  6999. self.repo.path,
  7000. message=b"Some message",
  7001. author=b"Joe <joe@example.com>",
  7002. committer=b"Bob <bob@example.com>",
  7003. )
  7004. porcelain.tag_create(
  7005. self.repo.path,
  7006. b"tryme",
  7007. b"foo <foo@bar.com>",
  7008. b"bar",
  7009. annotated=True,
  7010. )
  7011. self.assertEqual("tryme", porcelain.describe(self.repo.path))
  7012. def test_tag_and_commit(self) -> None:
  7013. fullpath = os.path.join(self.repo.path, "foo")
  7014. with open(fullpath, "w") as f:
  7015. f.write("BAR")
  7016. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7017. porcelain.commit(
  7018. self.repo.path,
  7019. message=b"Some message",
  7020. author=b"Joe <joe@example.com>",
  7021. committer=b"Bob <bob@example.com>",
  7022. )
  7023. porcelain.tag_create(
  7024. self.repo.path,
  7025. b"tryme",
  7026. b"foo <foo@bar.com>",
  7027. b"bar",
  7028. annotated=True,
  7029. )
  7030. with open(fullpath, "w") as f:
  7031. f.write("BAR2")
  7032. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7033. sha = porcelain.commit(
  7034. self.repo.path,
  7035. message=b"Some message",
  7036. author=b"Joe <joe@example.com>",
  7037. committer=b"Bob <bob@example.com>",
  7038. )
  7039. self.assertEqual(
  7040. "tryme-1-g{}".format(sha[:7].decode("ascii")),
  7041. porcelain.describe(self.repo.path),
  7042. )
  7043. def test_tag_and_commit_full(self) -> None:
  7044. fullpath = os.path.join(self.repo.path, "foo")
  7045. with open(fullpath, "w") as f:
  7046. f.write("BAR")
  7047. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7048. porcelain.commit(
  7049. self.repo.path,
  7050. message=b"Some message",
  7051. author=b"Joe <joe@example.com>",
  7052. committer=b"Bob <bob@example.com>",
  7053. )
  7054. porcelain.tag_create(
  7055. self.repo.path,
  7056. b"tryme",
  7057. b"foo <foo@bar.com>",
  7058. b"bar",
  7059. annotated=True,
  7060. )
  7061. with open(fullpath, "w") as f:
  7062. f.write("BAR2")
  7063. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7064. sha = porcelain.commit(
  7065. self.repo.path,
  7066. message=b"Some message",
  7067. author=b"Joe <joe@example.com>",
  7068. committer=b"Bob <bob@example.com>",
  7069. )
  7070. self.assertEqual(
  7071. "tryme-1-g{}".format(sha.decode("ascii")),
  7072. porcelain.describe(self.repo.path, abbrev=40),
  7073. )
  7074. def test_untagged_commit_abbreviation(self) -> None:
  7075. _, _, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]])
  7076. self.repo.refs[b"HEAD"] = c3.id
  7077. brief_description, complete_description = (
  7078. porcelain.describe(self.repo),
  7079. porcelain.describe(self.repo, abbrev=40),
  7080. )
  7081. self.assertTrue(complete_description.startswith(brief_description))
  7082. self.assertEqual(
  7083. "g{}".format(c3.id.decode("ascii")),
  7084. complete_description,
  7085. )
  7086. def test_hash_length_dynamic(self) -> None:
  7087. """Test that hash length adjusts based on uniqueness."""
  7088. fullpath = os.path.join(self.repo.path, "foo")
  7089. with open(fullpath, "w") as f:
  7090. f.write("content")
  7091. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7092. sha = porcelain.commit(
  7093. self.repo.path,
  7094. message=b"commit",
  7095. author=b"Joe <joe@example.com>",
  7096. committer=b"Bob <bob@example.com>",
  7097. )
  7098. # When abbrev is None, it should use find_unique_abbrev
  7099. result = porcelain.describe(self.repo.path)
  7100. # Should start with 'g' and have at least 7 characters
  7101. self.assertTrue(result.startswith("g"))
  7102. self.assertGreaterEqual(len(result[1:]), 7)
  7103. # Should be a prefix of the full SHA
  7104. self.assertTrue(sha.decode("ascii").startswith(result[1:]))
  7105. class PathToTreeTests(PorcelainTestCase):
  7106. def setUp(self) -> None:
  7107. super().setUp()
  7108. self.fp = os.path.join(self.test_dir, "bar")
  7109. with open(self.fp, "w") as f:
  7110. f.write("something")
  7111. oldcwd = os.getcwd()
  7112. self.addCleanup(os.chdir, oldcwd)
  7113. os.chdir(self.test_dir)
  7114. def test_path_to_tree_path_base(self) -> None:
  7115. self.assertEqual(b"bar", porcelain.path_to_tree_path(self.test_dir, self.fp))
  7116. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  7117. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "bar"))
  7118. cwd = os.getcwd()
  7119. self.assertEqual(
  7120. b"bar", porcelain.path_to_tree_path(".", os.path.join(cwd, "bar"))
  7121. )
  7122. self.assertEqual(b"bar", porcelain.path_to_tree_path(cwd, "bar"))
  7123. def test_path_to_tree_path_syntax(self) -> None:
  7124. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  7125. def test_path_to_tree_path_error(self) -> None:
  7126. with self.assertRaises(ValueError):
  7127. with tempfile.TemporaryDirectory() as od:
  7128. porcelain.path_to_tree_path(od, self.fp)
  7129. def test_path_to_tree_path_rel(self) -> None:
  7130. cwd = os.getcwd()
  7131. self.addCleanup(os.chdir, cwd)
  7132. os.mkdir(os.path.join(self.repo.path, "foo"))
  7133. os.mkdir(os.path.join(self.repo.path, "foo/bar"))
  7134. os.chdir(os.path.join(self.repo.path, "foo/bar"))
  7135. with open("baz", "w") as f:
  7136. f.write("contents")
  7137. self.assertEqual(b"bar/baz", porcelain.path_to_tree_path("..", "baz"))
  7138. self.assertEqual(
  7139. b"bar/baz",
  7140. porcelain.path_to_tree_path(
  7141. os.path.join(os.getcwd(), ".."),
  7142. os.path.join(os.getcwd(), "baz"),
  7143. ),
  7144. )
  7145. self.assertEqual(
  7146. b"bar/baz",
  7147. porcelain.path_to_tree_path("..", os.path.join(os.getcwd(), "baz")),
  7148. )
  7149. self.assertEqual(
  7150. b"bar/baz",
  7151. porcelain.path_to_tree_path(os.path.join(os.getcwd(), ".."), "baz"),
  7152. )
  7153. class GetObjectByPathTests(PorcelainTestCase):
  7154. def test_simple(self) -> None:
  7155. fullpath = os.path.join(self.repo.path, "foo")
  7156. with open(fullpath, "w") as f:
  7157. f.write("BAR")
  7158. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7159. porcelain.commit(
  7160. self.repo.path,
  7161. message=b"Some message",
  7162. author=b"Joe <joe@example.com>",
  7163. committer=b"Bob <bob@example.com>",
  7164. )
  7165. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  7166. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  7167. def test_encoding(self) -> None:
  7168. fullpath = os.path.join(self.repo.path, "foo")
  7169. with open(fullpath, "w") as f:
  7170. f.write("BAR")
  7171. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7172. porcelain.commit(
  7173. self.repo.path,
  7174. message=b"Some message",
  7175. author=b"Joe <joe@example.com>",
  7176. committer=b"Bob <bob@example.com>",
  7177. encoding=b"utf-8",
  7178. )
  7179. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  7180. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  7181. def test_missing(self) -> None:
  7182. self.assertRaises(KeyError, porcelain.get_object_by_path, self.repo, "foo")
  7183. class WriteTreeTests(PorcelainTestCase):
  7184. def test_simple(self) -> None:
  7185. fullpath = os.path.join(self.repo.path, "foo")
  7186. with open(fullpath, "w") as f:
  7187. f.write("BAR")
  7188. porcelain.add(repo=self.repo.path, paths=[fullpath])
  7189. self.assertEqual(
  7190. b"d2092c8a9f311f0311083bf8d177f2ca0ab5b241",
  7191. porcelain.write_tree(self.repo),
  7192. )
  7193. class ActiveBranchTests(PorcelainTestCase):
  7194. def test_simple(self) -> None:
  7195. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  7196. class BranchTrackingTests(PorcelainTestCase):
  7197. def test_get_branch_merge(self) -> None:
  7198. # Set up branch tracking configuration
  7199. config = self.repo.get_config()
  7200. config.set((b"branch", b"master"), b"remote", b"origin")
  7201. config.set((b"branch", b"master"), b"merge", b"refs/heads/main")
  7202. config.write_to_path()
  7203. # Test getting merge ref for current branch
  7204. merge_ref = porcelain.get_branch_merge(self.repo)
  7205. self.assertEqual(b"refs/heads/main", merge_ref)
  7206. # Test getting merge ref for specific branch
  7207. merge_ref = porcelain.get_branch_merge(self.repo, b"master")
  7208. self.assertEqual(b"refs/heads/main", merge_ref)
  7209. # Test branch without merge config
  7210. with self.assertRaises(KeyError):
  7211. porcelain.get_branch_merge(self.repo, b"nonexistent")
  7212. def test_set_branch_tracking(self) -> None:
  7213. # Create a new branch
  7214. _sha, _ = _commit_file_with_content(self.repo, "foo", "content\n")
  7215. porcelain.branch_create(self.repo, "feature")
  7216. # Set up tracking
  7217. porcelain.set_branch_tracking(
  7218. self.repo, b"feature", b"upstream", b"refs/heads/main"
  7219. )
  7220. # Verify configuration was written
  7221. config = self.repo.get_config()
  7222. self.assertEqual(b"upstream", config.get((b"branch", b"feature"), b"remote"))
  7223. self.assertEqual(
  7224. b"refs/heads/main", config.get((b"branch", b"feature"), b"merge")
  7225. )
  7226. class FindUniqueAbbrevTests(PorcelainTestCase):
  7227. def test_simple(self) -> None:
  7228. c1, _c2, c3 = build_commit_graph(
  7229. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  7230. )
  7231. self.repo.refs[b"HEAD"] = c3.id
  7232. self.assertEqual(
  7233. c1.id.decode("ascii")[:7],
  7234. porcelain.find_unique_abbrev(self.repo.object_store, c1.id),
  7235. )
  7236. class PackRefsTests(PorcelainTestCase):
  7237. def test_all(self) -> None:
  7238. c1, c2, c3 = build_commit_graph(
  7239. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  7240. )
  7241. self.repo.refs[b"HEAD"] = c3.id
  7242. self.repo.refs[b"refs/heads/master"] = c2.id
  7243. self.repo.refs[b"refs/tags/foo"] = c1.id
  7244. porcelain.pack_refs(self.repo, all=True)
  7245. self.assertEqual(
  7246. self.repo.refs.get_packed_refs(),
  7247. {
  7248. b"refs/heads/master": c2.id,
  7249. b"refs/tags/foo": c1.id,
  7250. },
  7251. )
  7252. def test_not_all(self) -> None:
  7253. c1, c2, c3 = build_commit_graph(
  7254. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  7255. )
  7256. self.repo.refs[b"HEAD"] = c3.id
  7257. self.repo.refs[b"refs/heads/master"] = c2.id
  7258. self.repo.refs[b"refs/tags/foo"] = c1.id
  7259. porcelain.pack_refs(self.repo)
  7260. self.assertEqual(
  7261. self.repo.refs.get_packed_refs(),
  7262. {
  7263. b"refs/tags/foo": c1.id,
  7264. },
  7265. )
  7266. class ServerTests(PorcelainTestCase):
  7267. @contextlib.contextmanager
  7268. def _serving(self):
  7269. with make_server("localhost", 0, self.app) as server:
  7270. thread = threading.Thread(target=server.serve_forever, daemon=True)
  7271. thread.start()
  7272. try:
  7273. yield f"http://localhost:{server.server_port}"
  7274. finally:
  7275. server.shutdown()
  7276. thread.join(10)
  7277. def setUp(self) -> None:
  7278. super().setUp()
  7279. self.served_repo_path = os.path.join(self.test_dir, "served_repo.git")
  7280. self.served_repo = Repo.init_bare(self.served_repo_path, mkdir=True)
  7281. self.addCleanup(self.served_repo.close)
  7282. backend = DictBackend({"/": self.served_repo})
  7283. self.app = make_wsgi_chain(backend)
  7284. def test_pull(self) -> None:
  7285. (c1,) = build_commit_graph(self.served_repo.object_store, [[1]])
  7286. self.served_repo.refs[b"refs/heads/master"] = c1.id
  7287. with self._serving() as url:
  7288. porcelain.pull(self.repo, url, "master")
  7289. def test_push(self) -> None:
  7290. (c1,) = build_commit_graph(self.repo.object_store, [[1]])
  7291. self.repo.refs[b"refs/heads/master"] = c1.id
  7292. with self._serving() as url:
  7293. porcelain.push(self.repo, url, "master")
  7294. class ForEachTests(PorcelainTestCase):
  7295. def setUp(self) -> None:
  7296. super().setUp()
  7297. c1, c2, c3, c4 = build_commit_graph(
  7298. self.repo.object_store, [[1], [2, 1], [3, 1, 2], [4]]
  7299. )
  7300. porcelain.tag_create(
  7301. self.repo.path,
  7302. b"v0.1",
  7303. objectish=c1.id,
  7304. annotated=True,
  7305. message=b"0.1",
  7306. )
  7307. porcelain.tag_create(
  7308. self.repo.path,
  7309. b"v1.0",
  7310. objectish=c2.id,
  7311. annotated=True,
  7312. message=b"1.0",
  7313. )
  7314. porcelain.tag_create(self.repo.path, b"simple-tag", objectish=c3.id)
  7315. porcelain.tag_create(
  7316. self.repo.path,
  7317. b"v1.1",
  7318. objectish=c4.id,
  7319. annotated=True,
  7320. message=b"1.1",
  7321. )
  7322. porcelain.branch_create(
  7323. self.repo.path, b"feat", objectish=c2.id.decode("ascii")
  7324. )
  7325. self.repo.refs[b"HEAD"] = c4.id
  7326. def test_for_each_ref(self) -> None:
  7327. refs = porcelain.for_each_ref(self.repo)
  7328. self.assertEqual(
  7329. [(object_type, tag) for _, object_type, tag in refs],
  7330. [
  7331. (b"commit", b"refs/heads/feat"),
  7332. (b"commit", b"refs/heads/master"),
  7333. (b"commit", b"refs/tags/simple-tag"),
  7334. (b"tag", b"refs/tags/v0.1"),
  7335. (b"tag", b"refs/tags/v1.0"),
  7336. (b"tag", b"refs/tags/v1.1"),
  7337. ],
  7338. )
  7339. def test_for_each_ref_pattern(self) -> None:
  7340. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v*")
  7341. self.assertEqual(
  7342. [(object_type, tag) for _, object_type, tag in versions],
  7343. [
  7344. (b"tag", b"refs/tags/v0.1"),
  7345. (b"tag", b"refs/tags/v1.0"),
  7346. (b"tag", b"refs/tags/v1.1"),
  7347. ],
  7348. )
  7349. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v1.?")
  7350. self.assertEqual(
  7351. [(object_type, tag) for _, object_type, tag in versions],
  7352. [
  7353. (b"tag", b"refs/tags/v1.0"),
  7354. (b"tag", b"refs/tags/v1.1"),
  7355. ],
  7356. )
  7357. class SparseCheckoutTests(PorcelainTestCase):
  7358. """Integration tests for Dulwich's sparse checkout feature."""
  7359. # NOTE: We do NOT override `setUp()` here because the parent class
  7360. # (PorcelainTestCase) already:
  7361. # 1) Creates self.test_dir = a unique temp dir
  7362. # 2) Creates a subdir named "repo"
  7363. # 3) Calls Repo.init() on that path
  7364. # Re-initializing again caused FileExistsError.
  7365. #
  7366. # Utility/Placeholder
  7367. #
  7368. def sparse_checkout(self, repo, patterns, force=False):
  7369. """Wrapper around the actual porcelain.sparse_checkout function
  7370. to handle any test-specific setup or logging.
  7371. """
  7372. return porcelain.sparse_checkout(repo, patterns, force=force)
  7373. def _write_file(self, rel_path, content):
  7374. """Helper to write a file in the repository working tree."""
  7375. abs_path = os.path.join(self.repo_path, rel_path)
  7376. os.makedirs(os.path.dirname(abs_path), exist_ok=True)
  7377. with open(abs_path, "w") as f:
  7378. f.write(content)
  7379. return abs_path
  7380. def _commit_file(self, rel_path, content):
  7381. """Helper to write, add, and commit a file."""
  7382. abs_path = self._write_file(rel_path, content)
  7383. add(self.repo_path, paths=[abs_path])
  7384. commit(self.repo_path, message=b"Added " + rel_path.encode("utf-8"))
  7385. def _list_wtree_files(self):
  7386. """Return a set of all files (not dirs) present
  7387. in the working tree, ignoring .git/.
  7388. """
  7389. found_files = set()
  7390. for root, dirs, files in os.walk(self.repo_path):
  7391. # Skip .git in the walk
  7392. if ".git" in dirs:
  7393. dirs.remove(".git")
  7394. for filename in files:
  7395. file_rel = os.path.relpath(os.path.join(root, filename), self.repo_path)
  7396. found_files.add(file_rel)
  7397. return found_files
  7398. def test_only_included_paths_appear_in_wtree(self):
  7399. """Only included paths remain in the working tree, excluded paths are removed.
  7400. Commits two files, "keep_me.txt" and "exclude_me.txt". Then applies a
  7401. sparse-checkout pattern containing only "keep_me.txt". Ensures that
  7402. the latter remains in the working tree, while "exclude_me.txt" is
  7403. removed. This verifies correct application of sparse-checkout patterns
  7404. to remove files not listed.
  7405. """
  7406. self._commit_file("keep_me.txt", "I'll stay\n")
  7407. self._commit_file("exclude_me.txt", "I'll be excluded\n")
  7408. patterns = ["keep_me.txt"]
  7409. self.sparse_checkout(self.repo, patterns)
  7410. actual_files = self._list_wtree_files()
  7411. expected_files = {"keep_me.txt"}
  7412. self.assertEqual(
  7413. expected_files,
  7414. actual_files,
  7415. f"Expected only {expected_files}, but found {actual_files}",
  7416. )
  7417. def test_previously_included_paths_become_excluded(self):
  7418. """Previously included files become excluded after pattern changes.
  7419. Verifies that files initially brought into the working tree (e.g.,
  7420. by including `data/`) can later be excluded by narrowing the
  7421. sparse-checkout pattern to just `data/included_1.txt`. Confirms that
  7422. the file `data/included_2.txt` remains in the index with
  7423. skip-worktree set (rather than being removed entirely), ensuring
  7424. data is not lost and Dulwich correctly updates the index flags.
  7425. """
  7426. self._commit_file("data/included_1.txt", "some content\n")
  7427. self._commit_file("data/included_2.txt", "other content\n")
  7428. initial_patterns = ["data/"]
  7429. self.sparse_checkout(self.repo, initial_patterns)
  7430. updated_patterns = ["data/included_1.txt"]
  7431. self.sparse_checkout(self.repo, updated_patterns)
  7432. actual_files = self._list_wtree_files()
  7433. expected_files = {os.path.join("data", "included_1.txt")}
  7434. self.assertEqual(expected_files, actual_files)
  7435. idx = self.repo.open_index()
  7436. self.assertIn(b"data/included_2.txt", idx)
  7437. entry = idx[b"data/included_2.txt"]
  7438. self.assertTrue(entry.skip_worktree)
  7439. def test_force_removes_local_changes_for_excluded_paths(self):
  7440. """Forced sparse checkout removes local modifications for newly excluded paths.
  7441. Verifies that specifying force=True allows destructive operations
  7442. which discard uncommitted changes. First, we commit "file1.txt" and
  7443. then modify it. Next, we apply a pattern that excludes the file,
  7444. using force=True. The local modifications (and the file) should
  7445. be removed, leaving the working tree empty.
  7446. """
  7447. self._commit_file("file1.txt", "original content\n")
  7448. file1_path = os.path.join(self.repo_path, "file1.txt")
  7449. with open(file1_path, "a") as f:
  7450. f.write("local changes!\n")
  7451. new_patterns = ["some_other_file.txt"]
  7452. self.sparse_checkout(self.repo, new_patterns, force=True)
  7453. actual_files = self._list_wtree_files()
  7454. self.assertEqual(
  7455. set(),
  7456. actual_files,
  7457. "Force-sparse-checkout did not remove file with local changes.",
  7458. )
  7459. def test_destructive_refuse_uncommitted_changes_without_force(self):
  7460. """Fail on uncommitted changes for newly excluded paths without force.
  7461. Ensures that a sparse checkout is blocked if it would remove local
  7462. modifications from the working tree. We commit 'config.yaml', then
  7463. modify it, and finally attempt to exclude it via new patterns without
  7464. using force=True. This should raise a CheckoutError rather than
  7465. discarding the local changes.
  7466. """
  7467. self._commit_file("config.yaml", "initial\n")
  7468. cfg_path = os.path.join(self.repo_path, "config.yaml")
  7469. with open(cfg_path, "a") as f:
  7470. f.write("local modifications\n")
  7471. exclude_patterns = ["docs/"]
  7472. with self.assertRaises(CheckoutError):
  7473. self.sparse_checkout(self.repo, exclude_patterns, force=False)
  7474. def test_fnmatch_gitignore_pattern_expansion(self):
  7475. """Reading/writing patterns align with gitignore/fnmatch expansions.
  7476. Ensures that `sparse_checkout` interprets wildcard patterns (like `*.py`)
  7477. in the same way Git's sparse-checkout would. Multiple files are committed
  7478. to `src/` (e.g. `foo.py`, `foo_test.py`, `foo_helper.py`) and to `docs/`.
  7479. Then the pattern `src/foo*.py` is applied, confirming that only the
  7480. matching Python files remain in the working tree while the Markdown file
  7481. under `docs/` is excluded.
  7482. Finally, verifies that the `.git/info/sparse-checkout` file contains the
  7483. specified wildcard pattern (`src/foo*.py`), ensuring correct round-trip
  7484. of user-supplied patterns.
  7485. """
  7486. self._commit_file("src/foo.py", "print('hello')\n")
  7487. self._commit_file("src/foo_test.py", "print('test')\n")
  7488. self._commit_file("docs/readme.md", "# docs\n")
  7489. self._commit_file("src/foo_helper.py", "print('helper')\n")
  7490. patterns = ["src/foo*.py"]
  7491. self.sparse_checkout(self.repo, patterns)
  7492. actual_files = self._list_wtree_files()
  7493. expected_files = {
  7494. os.path.join("src", "foo.py"),
  7495. os.path.join("src", "foo_test.py"),
  7496. os.path.join("src", "foo_helper.py"),
  7497. }
  7498. self.assertEqual(
  7499. expected_files,
  7500. actual_files,
  7501. "Wildcard pattern not matched as expected. Either too strict or too broad.",
  7502. )
  7503. sc_file = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7504. self.assertTrue(os.path.isfile(sc_file))
  7505. with open(sc_file) as f:
  7506. lines = f.read().strip().split()
  7507. self.assertIn("src/foo*.py", lines)
  7508. class ConeModeTests(PorcelainTestCase):
  7509. """Provide integration tests for Dulwich's cone mode sparse checkout.
  7510. This test suite verifies the expected behavior for:
  7511. * cone_mode_init
  7512. * cone_mode_set
  7513. * cone_mode_add
  7514. Although Dulwich does not yet implement cone mode, these tests are
  7515. prepared in advance to guide future development.
  7516. """
  7517. def setUp(self):
  7518. """Set up a fresh repository for each test.
  7519. This method creates a new empty repo_path and Repo object
  7520. as provided by the PorcelainTestCase base class.
  7521. """
  7522. super().setUp()
  7523. def _commit_file(self, rel_path, content=b"contents"):
  7524. """Add a file at the given relative path and commit it.
  7525. Creates necessary directories, writes the file content,
  7526. stages, and commits. The commit message and author/committer
  7527. are also provided.
  7528. """
  7529. full_path = os.path.join(self.repo_path, rel_path)
  7530. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  7531. with open(full_path, "wb") as f:
  7532. f.write(content)
  7533. porcelain.add(self.repo_path, paths=[full_path])
  7534. porcelain.commit(
  7535. self.repo_path,
  7536. message=b"Adding " + rel_path.encode("utf-8"),
  7537. author=b"Test Author <author@example.com>",
  7538. committer=b"Test Committer <committer@example.com>",
  7539. )
  7540. def _list_wtree_files(self):
  7541. """Return a set of all file paths relative to the repository root.
  7542. Walks the working tree, skipping the .git directory.
  7543. """
  7544. found_files = set()
  7545. for root, dirs, files in os.walk(self.repo_path):
  7546. if ".git" in dirs:
  7547. dirs.remove(".git")
  7548. for fn in files:
  7549. relp = os.path.relpath(os.path.join(root, fn), self.repo_path)
  7550. found_files.add(relp)
  7551. return found_files
  7552. def test_init_excludes_everything(self):
  7553. """Verify that cone_mode_init writes minimal patterns and empties the working tree.
  7554. Make some dummy files, commit them, then call cone_mode_init. Confirm
  7555. that the working tree is empty, the sparse-checkout file has the
  7556. minimal patterns (/*, !/*/), and the relevant config values are set.
  7557. """
  7558. self._commit_file("docs/readme.md", b"# doc\n")
  7559. self._commit_file("src/main.py", b"print('hello')\n")
  7560. porcelain.cone_mode_init(self.repo)
  7561. actual_files = self._list_wtree_files()
  7562. self.assertEqual(
  7563. set(),
  7564. actual_files,
  7565. "cone_mode_init did not exclude all files from the working tree.",
  7566. )
  7567. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7568. with open(sp_path) as f:
  7569. lines = [ln.strip() for ln in f if ln.strip()]
  7570. self.assertIn("/*", lines)
  7571. self.assertIn("!/*/", lines)
  7572. config = self.repo.get_config()
  7573. self.assertEqual(config.get((b"core",), b"sparseCheckout"), b"true")
  7574. self.assertEqual(config.get((b"core",), b"sparseCheckoutCone"), b"true")
  7575. def test_set_specific_dirs(self):
  7576. """Verify that cone_mode_set overwrites the included directories to only the specified ones.
  7577. Initializes cone mode, commits some files, then calls cone_mode_set with
  7578. a list of directories. Expects that only those directories remain in the
  7579. working tree.
  7580. """
  7581. porcelain.cone_mode_init(self.repo)
  7582. self._commit_file("docs/readme.md", b"# doc\n")
  7583. self._commit_file("src/main.py", b"print('hello')\n")
  7584. self._commit_file("tests/test_foo.py", b"# tests\n")
  7585. # Everything is still excluded initially by init.
  7586. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  7587. actual_files = self._list_wtree_files()
  7588. expected_files = {
  7589. os.path.join("docs", "readme.md"),
  7590. os.path.join("src", "main.py"),
  7591. }
  7592. self.assertEqual(
  7593. expected_files,
  7594. actual_files,
  7595. "Did not see only the 'docs/' and 'src/' dirs in the working tree.",
  7596. )
  7597. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7598. with open(sp_path) as f:
  7599. lines = [ln.strip() for ln in f if ln.strip()]
  7600. # For standard cone mode, we'd expect lines like:
  7601. # /* (include top-level files)
  7602. # !/*/ (exclude subdirectories)
  7603. # !/docs/ (re-include docs)
  7604. # !/src/ (re-include src)
  7605. # Instead of the wildcard-based lines the old test used.
  7606. self.assertIn("/*", lines)
  7607. self.assertIn("!/*/", lines)
  7608. self.assertIn("/docs/", lines)
  7609. self.assertIn("/src/", lines)
  7610. self.assertNotIn("/tests/", lines)
  7611. def test_set_overwrites_old_dirs(self):
  7612. """Ensure that calling cone_mode_set again overwrites old includes.
  7613. Initializes cone mode, includes two directories, then calls
  7614. cone_mode_set again with a different directory to confirm the
  7615. new set of includes replaces the old.
  7616. """
  7617. porcelain.cone_mode_init(self.repo)
  7618. self._commit_file("docs/readme.md")
  7619. self._commit_file("src/main.py")
  7620. self._commit_file("tests/test_bar.py")
  7621. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  7622. self.assertEqual(
  7623. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  7624. self._list_wtree_files(),
  7625. )
  7626. # Overwrite includes, now only 'tests'
  7627. porcelain.cone_mode_set(self.repo, dirs=["tests"], force=True)
  7628. actual_files = self._list_wtree_files()
  7629. expected_files = {os.path.join("tests", "test_bar.py")}
  7630. self.assertEqual(expected_files, actual_files)
  7631. def test_force_removal_of_local_mods(self):
  7632. """Confirm that force=True removes local changes in excluded paths.
  7633. cone_mode_init and cone_mode_set are called, a file is locally modified,
  7634. and then cone_mode_set is called again with force=True to exclude that path.
  7635. The excluded file should be removed with no CheckoutError.
  7636. """
  7637. porcelain.cone_mode_init(self.repo)
  7638. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  7639. self._commit_file("docs/readme.md", b"Docs stuff\n")
  7640. self._commit_file("src/main.py", b"print('hello')\n")
  7641. # Modify src/main.py
  7642. with open(os.path.join(self.repo_path, "src/main.py"), "ab") as f:
  7643. f.write(b"extra line\n")
  7644. # Exclude src/ with force=True
  7645. porcelain.cone_mode_set(self.repo, dirs=["docs"], force=True)
  7646. actual_files = self._list_wtree_files()
  7647. expected_files = {os.path.join("docs", "readme.md")}
  7648. self.assertEqual(expected_files, actual_files)
  7649. def test_add_and_merge_dirs(self):
  7650. """Verify that cone_mode_add merges new directories instead of overwriting them.
  7651. After initializing cone mode and including a single directory, call
  7652. cone_mode_add with a new directory. Confirm that both directories
  7653. remain included. Repeat for an additional directory to ensure it
  7654. is merged, not overwritten.
  7655. """
  7656. porcelain.cone_mode_init(self.repo)
  7657. self._commit_file("docs/readme.md", b"# doc\n")
  7658. self._commit_file("src/main.py", b"print('hello')\n")
  7659. self._commit_file("tests/test_bar.py", b"# tests\n")
  7660. # Include "docs" only
  7661. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  7662. self.assertEqual({os.path.join("docs", "readme.md")}, self._list_wtree_files())
  7663. # Add "src"
  7664. porcelain.cone_mode_add(self.repo, dirs=["src"])
  7665. actual_files = self._list_wtree_files()
  7666. self.assertEqual(
  7667. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  7668. actual_files,
  7669. )
  7670. # Add "tests" as well
  7671. porcelain.cone_mode_add(self.repo, dirs=["tests"])
  7672. actual_files = self._list_wtree_files()
  7673. expected_files = {
  7674. os.path.join("docs", "readme.md"),
  7675. os.path.join("src", "main.py"),
  7676. os.path.join("tests", "test_bar.py"),
  7677. }
  7678. self.assertEqual(expected_files, actual_files)
  7679. # Check .git/info/sparse-checkout
  7680. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  7681. with open(sp_path) as f:
  7682. lines = [ln.strip() for ln in f if ln.strip()]
  7683. # Standard cone mode lines:
  7684. # "/*" -> include top-level
  7685. # "!/*/" -> exclude subdirectories
  7686. # "!/docs/", "!/src/", "!/tests/" -> re-include the directories we added
  7687. self.assertIn("/*", lines)
  7688. self.assertIn("!/*/", lines)
  7689. self.assertIn("/docs/", lines)
  7690. self.assertIn("/src/", lines)
  7691. self.assertIn("/tests/", lines)
  7692. class UnpackObjectsTest(PorcelainTestCase):
  7693. def test_unpack_objects(self):
  7694. """Test unpacking objects from a pack file."""
  7695. # Create a test repository with some objects
  7696. b1 = Blob()
  7697. b1.data = b"test content 1"
  7698. b2 = Blob()
  7699. b2.data = b"test content 2"
  7700. # Add objects to the repo
  7701. self.repo.object_store.add_object(b1)
  7702. self.repo.object_store.add_object(b2)
  7703. # Create a pack file with these objects
  7704. pack_path = os.path.join(self.test_dir, "test_pack")
  7705. with (
  7706. open(pack_path + ".pack", "wb") as pack_f,
  7707. open(pack_path + ".idx", "wb") as idx_f,
  7708. ):
  7709. porcelain.pack_objects(
  7710. self.repo,
  7711. [b1.id, b2.id],
  7712. pack_f,
  7713. idx_f,
  7714. )
  7715. # Create a new repository to unpack into
  7716. target_repo_path = os.path.join(self.test_dir, "target_repo")
  7717. target_repo = Repo.init(target_repo_path, mkdir=True)
  7718. self.addCleanup(target_repo.close)
  7719. # Unpack the objects
  7720. count = porcelain.unpack_objects(pack_path + ".pack", target_repo_path)
  7721. # Verify the objects were unpacked
  7722. self.assertEqual(2, count)
  7723. self.assertIn(b1.id, target_repo.object_store)
  7724. self.assertIn(b2.id, target_repo.object_store)
  7725. # Verify the content is correct
  7726. unpacked_b1 = target_repo.object_store[b1.id]
  7727. unpacked_b2 = target_repo.object_store[b2.id]
  7728. self.assertEqual(b1.data, unpacked_b1.data)
  7729. self.assertEqual(b2.data, unpacked_b2.data)
  7730. class CountObjectsTests(PorcelainTestCase):
  7731. def test_count_objects_empty_repo(self):
  7732. """Test counting objects in an empty repository."""
  7733. stats = porcelain.count_objects(self.repo)
  7734. self.assertEqual(0, stats.count)
  7735. self.assertEqual(0, stats.size)
  7736. def test_count_objects_verbose_empty_repo(self):
  7737. """Test verbose counting in an empty repository."""
  7738. stats = porcelain.count_objects(self.repo, verbose=True)
  7739. self.assertEqual(0, stats.count)
  7740. self.assertEqual(0, stats.size)
  7741. self.assertEqual(0, stats.in_pack)
  7742. self.assertEqual(0, stats.packs)
  7743. self.assertEqual(0, stats.size_pack)
  7744. def test_count_objects_with_loose_objects(self):
  7745. """Test counting loose objects."""
  7746. # Create some loose objects
  7747. blob1 = make_object(Blob, data=b"data1")
  7748. blob2 = make_object(Blob, data=b"data2")
  7749. self.repo.object_store.add_object(blob1)
  7750. self.repo.object_store.add_object(blob2)
  7751. stats = porcelain.count_objects(self.repo)
  7752. self.assertEqual(2, stats.count)
  7753. self.assertGreater(stats.size, 0)
  7754. def test_count_objects_verbose_with_objects(self):
  7755. """Test verbose counting with both loose and packed objects."""
  7756. # Add some loose objects
  7757. for i in range(3):
  7758. blob = make_object(Blob, data=f"data{i}".encode())
  7759. self.repo.object_store.add_object(blob)
  7760. # Create a simple commit to have some objects in a pack
  7761. tree = Tree()
  7762. c1 = make_commit(tree=tree.id, message=b"Test commit")
  7763. self.repo.object_store.add_objects([(tree, None), (c1, None)])
  7764. self.repo.refs[b"HEAD"] = c1.id
  7765. # Repack to create a pack file
  7766. porcelain.repack(self.repo)
  7767. stats = porcelain.count_objects(self.repo, verbose=True)
  7768. # After repacking, loose objects might be cleaned up
  7769. self.assertIsInstance(stats.count, int)
  7770. self.assertIsInstance(stats.size, int)
  7771. self.assertGreater(stats.in_pack, 0) # Should have packed objects
  7772. self.assertGreater(stats.packs, 0) # Should have at least one pack
  7773. self.assertGreater(stats.size_pack, 0) # Pack should have size
  7774. # Verify it's the correct dataclass type
  7775. self.assertIsInstance(stats, CountObjectsResult)
  7776. class PruneTests(PorcelainTestCase):
  7777. def test_prune_removes_old_tempfiles(self):
  7778. """Test that prune removes old temporary files."""
  7779. # Create an old temporary file in the objects directory
  7780. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7781. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_test")
  7782. with open(tmp_pack_path, "wb") as f:
  7783. f.write(b"old temporary data")
  7784. # Make it old
  7785. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  7786. os.utime(tmp_pack_path, (old_time, old_time))
  7787. # Run prune
  7788. porcelain.prune(self.repo.path)
  7789. # Verify the file was removed
  7790. self.assertFalse(os.path.exists(tmp_pack_path))
  7791. def test_prune_keeps_recent_tempfiles(self):
  7792. """Test that prune keeps recent temporary files."""
  7793. # Create a recent temporary file
  7794. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7795. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_recent")
  7796. with open(tmp_pack_path, "wb") as f:
  7797. f.write(b"recent temporary data")
  7798. self.addCleanup(os.remove, tmp_pack_path)
  7799. # Run prune
  7800. porcelain.prune(self.repo.path)
  7801. # Verify the file was NOT removed
  7802. self.assertTrue(os.path.exists(tmp_pack_path))
  7803. def test_prune_with_custom_grace_period(self):
  7804. """Test prune with custom grace period."""
  7805. # Create a 1-hour-old temporary file
  7806. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7807. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_1hour")
  7808. with open(tmp_pack_path, "wb") as f:
  7809. f.write(b"1 hour old data")
  7810. # Make it 1 hour old
  7811. old_time = time.time() - 3600
  7812. os.utime(tmp_pack_path, (old_time, old_time))
  7813. # Prune with 30-minute grace period should remove it
  7814. porcelain.prune(self.repo.path, grace_period=1800)
  7815. # Verify the file was removed
  7816. self.assertFalse(os.path.exists(tmp_pack_path))
  7817. def test_prune_dry_run(self):
  7818. """Test prune in dry-run mode."""
  7819. # Create an old temporary file
  7820. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  7821. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_dryrun")
  7822. with open(tmp_pack_path, "wb") as f:
  7823. f.write(b"old temporary data")
  7824. self.addCleanup(os.remove, tmp_pack_path)
  7825. # Make it old
  7826. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  7827. os.utime(tmp_pack_path, (old_time, old_time))
  7828. # Run prune in dry-run mode
  7829. porcelain.prune(self.repo.path, dry_run=True)
  7830. # Verify the file was NOT removed (dry run)
  7831. self.assertTrue(os.path.exists(tmp_pack_path))
  7832. class FilterBranchTests(PorcelainTestCase):
  7833. def setUp(self):
  7834. super().setUp()
  7835. # Create initial commits with different authors
  7836. from dulwich.objects import Commit, Tree
  7837. # Create actual tree and blob objects
  7838. tree = Tree()
  7839. self.repo.object_store.add_object(tree)
  7840. c1 = Commit()
  7841. c1.tree = tree.id
  7842. c1.parents = []
  7843. c1.author = b"Old Author <old@example.com>"
  7844. c1.author_time = 1000
  7845. c1.author_timezone = 0
  7846. c1.committer = b"Old Committer <old@example.com>"
  7847. c1.commit_time = 1000
  7848. c1.commit_timezone = 0
  7849. c1.message = b"Initial commit"
  7850. self.repo.object_store.add_object(c1)
  7851. c2 = Commit()
  7852. c2.tree = tree.id
  7853. c2.parents = [c1.id]
  7854. c2.author = b"Another Author <another@example.com>"
  7855. c2.author_time = 2000
  7856. c2.author_timezone = 0
  7857. c2.committer = b"Another Committer <another@example.com>"
  7858. c2.commit_time = 2000
  7859. c2.commit_timezone = 0
  7860. c2.message = b"Second commit\n\nWith body"
  7861. self.repo.object_store.add_object(c2)
  7862. c3 = Commit()
  7863. c3.tree = tree.id
  7864. c3.parents = [c2.id]
  7865. c3.author = b"Third Author <third@example.com>"
  7866. c3.author_time = 3000
  7867. c3.author_timezone = 0
  7868. c3.committer = b"Third Committer <third@example.com>"
  7869. c3.commit_time = 3000
  7870. c3.commit_timezone = 0
  7871. c3.message = b"Third commit"
  7872. self.repo.object_store.add_object(c3)
  7873. self.repo.refs[b"refs/heads/master"] = c3.id
  7874. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  7875. # Store IDs for test assertions
  7876. self.c1_id = c1.id
  7877. self.c2_id = c2.id
  7878. self.c3_id = c3.id
  7879. def test_filter_branch_author(self):
  7880. """Test filtering branch with author changes."""
  7881. def filter_author(author):
  7882. # Change all authors to "New Author"
  7883. return b"New Author <new@example.com>"
  7884. result = porcelain.filter_branch(
  7885. self.repo_path, "master", filter_author=filter_author
  7886. )
  7887. # Check that we have mappings for all commits
  7888. self.assertEqual(len(result), 3)
  7889. # Verify the branch ref was updated
  7890. new_head = self.repo.refs[b"refs/heads/master"]
  7891. self.assertNotEqual(new_head, self.c3_id)
  7892. # Verify the original ref was saved
  7893. original_ref = self.repo.refs[b"refs/original/refs/heads/master"]
  7894. self.assertEqual(original_ref, self.c3_id)
  7895. # Check that authors were updated
  7896. new_commit = self.repo[new_head]
  7897. self.assertEqual(new_commit.author, b"New Author <new@example.com>")
  7898. # Check parent chain
  7899. parent = self.repo[new_commit.parents[0]]
  7900. self.assertEqual(parent.author, b"New Author <new@example.com>")
  7901. def test_filter_branch_message(self):
  7902. """Test filtering branch with message changes."""
  7903. def filter_message(message):
  7904. # Add prefix to all messages
  7905. return b"[FILTERED] " + message
  7906. porcelain.filter_branch(self.repo_path, "master", filter_message=filter_message)
  7907. # Verify messages were updated
  7908. new_head = self.repo.refs[b"refs/heads/master"]
  7909. new_commit = self.repo[new_head]
  7910. self.assertTrue(new_commit.message.startswith(b"[FILTERED] "))
  7911. def test_filter_branch_custom_filter(self):
  7912. """Test filtering branch with custom filter function."""
  7913. def custom_filter(commit):
  7914. # Change both author and message
  7915. return {
  7916. "author": b"Custom Author <custom@example.com>",
  7917. "message": b"Custom: " + commit.message,
  7918. }
  7919. porcelain.filter_branch(self.repo_path, "master", filter_fn=custom_filter)
  7920. # Verify custom filter was applied
  7921. new_head = self.repo.refs[b"refs/heads/master"]
  7922. new_commit = self.repo[new_head]
  7923. self.assertEqual(new_commit.author, b"Custom Author <custom@example.com>")
  7924. self.assertTrue(new_commit.message.startswith(b"Custom: "))
  7925. def test_filter_branch_no_changes(self):
  7926. """Test filtering branch with no changes."""
  7927. result = porcelain.filter_branch(self.repo_path, "master")
  7928. # All commits should map to themselves
  7929. for old_sha, new_sha in result.items():
  7930. self.assertEqual(old_sha, new_sha)
  7931. # HEAD should be unchanged
  7932. self.assertEqual(self.repo.refs[b"refs/heads/master"], self.c3_id)
  7933. def test_filter_branch_force(self):
  7934. """Test force filtering a previously filtered branch."""
  7935. # First filter
  7936. porcelain.filter_branch(
  7937. self.repo_path, "master", filter_message=lambda m: b"First: " + m
  7938. )
  7939. # Try again without force - should fail
  7940. with self.assertRaises(porcelain.Error):
  7941. porcelain.filter_branch(
  7942. self.repo_path, "master", filter_message=lambda m: b"Second: " + m
  7943. )
  7944. # Try again with force - should succeed
  7945. porcelain.filter_branch(
  7946. self.repo_path,
  7947. "master",
  7948. filter_message=lambda m: b"Second: " + m,
  7949. force=True,
  7950. )
  7951. # Verify second filter was applied
  7952. new_head = self.repo.refs[b"refs/heads/master"]
  7953. new_commit = self.repo[new_head]
  7954. self.assertTrue(new_commit.message.startswith(b"Second: First: "))
  7955. class StashTests(PorcelainTestCase):
  7956. def setUp(self) -> None:
  7957. super().setUp()
  7958. # Create initial commit
  7959. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  7960. f.write(b"initial content")
  7961. porcelain.add(repo=self.repo.path, paths=["initial.txt"])
  7962. porcelain.commit(
  7963. repo=self.repo.path,
  7964. message=b"Initial commit",
  7965. author=b"Test Author <test@example.com>",
  7966. committer=b"Test Committer <test@example.com>",
  7967. )
  7968. def test_stash_push_and_pop(self) -> None:
  7969. # Create a new file and stage it
  7970. new_file = os.path.join(self.repo.path, "new.txt")
  7971. with open(new_file, "wb") as f:
  7972. f.write(b"new file content")
  7973. porcelain.add(repo=self.repo.path, paths=["new.txt"])
  7974. # Modify existing file
  7975. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  7976. f.write(b"modified content")
  7977. # Push to stash
  7978. porcelain.stash_push(self.repo.path)
  7979. # Verify files are reset
  7980. self.assertFalse(os.path.exists(new_file))
  7981. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  7982. self.assertEqual(b"initial content", f.read())
  7983. # Pop the stash
  7984. porcelain.stash_pop(self.repo.path)
  7985. # Verify files are restored
  7986. self.assertTrue(os.path.exists(new_file))
  7987. with open(new_file, "rb") as f:
  7988. self.assertEqual(b"new file content", f.read())
  7989. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  7990. self.assertEqual(b"modified content", f.read())
  7991. # Verify new file is in the index
  7992. from dulwich.index import Index
  7993. index = Index(os.path.join(self.repo.path, ".git", "index"))
  7994. self.assertIn(b"new.txt", index)
  7995. def test_stash_list(self) -> None:
  7996. # Initially no stashes
  7997. stashes = list(porcelain.stash_list(self.repo.path))
  7998. self.assertEqual(0, len(stashes))
  7999. # Create a file and stash it
  8000. test_file = os.path.join(self.repo.path, "test.txt")
  8001. with open(test_file, "wb") as f:
  8002. f.write(b"test content")
  8003. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  8004. # Push first stash
  8005. porcelain.stash_push(self.repo.path)
  8006. # Create another file and stash it
  8007. test_file2 = os.path.join(self.repo.path, "test2.txt")
  8008. with open(test_file2, "wb") as f:
  8009. f.write(b"test content 2")
  8010. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  8011. # Push second stash
  8012. porcelain.stash_push(self.repo.path)
  8013. # Check stash list
  8014. stashes = list(porcelain.stash_list(self.repo.path))
  8015. self.assertEqual(2, len(stashes))
  8016. # Stashes are returned in order (most recent first)
  8017. self.assertEqual(0, stashes[0][0])
  8018. self.assertEqual(1, stashes[1][0])
  8019. def test_stash_drop(self) -> None:
  8020. # Create and stash some changes
  8021. test_file = os.path.join(self.repo.path, "test.txt")
  8022. with open(test_file, "wb") as f:
  8023. f.write(b"test content")
  8024. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  8025. porcelain.stash_push(self.repo.path)
  8026. # Create another stash
  8027. test_file2 = os.path.join(self.repo.path, "test2.txt")
  8028. with open(test_file2, "wb") as f:
  8029. f.write(b"test content 2")
  8030. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  8031. porcelain.stash_push(self.repo.path)
  8032. # Verify we have 2 stashes
  8033. stashes = list(porcelain.stash_list(self.repo.path))
  8034. self.assertEqual(2, len(stashes))
  8035. # Drop the first stash (index 0)
  8036. porcelain.stash_drop(self.repo.path, 0)
  8037. # Verify we have 1 stash left
  8038. stashes = list(porcelain.stash_list(self.repo.path))
  8039. self.assertEqual(1, len(stashes))
  8040. # The remaining stash should be the one we created first
  8041. # Pop it and verify it's the first file
  8042. porcelain.stash_pop(self.repo.path)
  8043. self.assertTrue(os.path.exists(test_file))
  8044. self.assertFalse(os.path.exists(test_file2))
  8045. def test_stash_pop_empty(self) -> None:
  8046. # Attempting to pop from empty stash should raise an error
  8047. with self.assertRaises(IndexError):
  8048. porcelain.stash_pop(self.repo.path)
  8049. def test_stash_with_untracked_files(self) -> None:
  8050. # Create an untracked file
  8051. untracked_file = os.path.join(self.repo.path, "untracked.txt")
  8052. with open(untracked_file, "wb") as f:
  8053. f.write(b"untracked content")
  8054. # Create a tracked change
  8055. tracked_file = os.path.join(self.repo.path, "tracked.txt")
  8056. with open(tracked_file, "wb") as f:
  8057. f.write(b"tracked content")
  8058. porcelain.add(repo=self.repo.path, paths=["tracked.txt"])
  8059. # Stash (by default, untracked files are not included)
  8060. porcelain.stash_push(self.repo.path)
  8061. # Untracked file should still exist
  8062. self.assertTrue(os.path.exists(untracked_file))
  8063. # Tracked file should be gone
  8064. self.assertFalse(os.path.exists(tracked_file))
  8065. # Pop the stash
  8066. porcelain.stash_pop(self.repo.path)
  8067. # Tracked file should be restored
  8068. self.assertTrue(os.path.exists(tracked_file))
  8069. class BisectTests(PorcelainTestCase):
  8070. """Tests for bisect porcelain functions."""
  8071. def test_bisect_start(self):
  8072. """Test starting a bisect session."""
  8073. # Create some commits
  8074. _c1, _c2, c3 = build_commit_graph(
  8075. self.repo.object_store,
  8076. [[1], [2, 1], [3, 2]],
  8077. attrs={
  8078. 1: {"message": b"initial"},
  8079. 2: {"message": b"second"},
  8080. 3: {"message": b"third"},
  8081. },
  8082. )
  8083. self.repo.refs[b"refs/heads/master"] = c3.id
  8084. self.repo.refs[b"HEAD"] = c3.id
  8085. # Start bisect
  8086. porcelain.bisect_start(self.repo_path)
  8087. # Check that bisect state files exist
  8088. self.assertTrue(
  8089. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  8090. )
  8091. self.assertTrue(
  8092. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_TERMS"))
  8093. )
  8094. self.assertTrue(
  8095. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_NAMES"))
  8096. )
  8097. self.assertTrue(
  8098. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_LOG"))
  8099. )
  8100. def test_bisect_workflow(self):
  8101. """Test a complete bisect workflow."""
  8102. # Create some commits
  8103. c1, c2, c3, c4 = build_commit_graph(
  8104. self.repo.object_store,
  8105. [[1], [2, 1], [3, 2], [4, 3]],
  8106. attrs={
  8107. 1: {"message": b"good commit 1"},
  8108. 2: {"message": b"good commit 2"},
  8109. 3: {"message": b"bad commit"},
  8110. 4: {"message": b"bad commit 2"},
  8111. },
  8112. )
  8113. self.repo.refs[b"refs/heads/master"] = c4.id
  8114. self.repo.refs[b"HEAD"] = c4.id
  8115. # Start bisect with bad and good
  8116. next_sha = porcelain.bisect_start(self.repo_path, bad=c4.id, good=c1.id)
  8117. # Should return the middle commit
  8118. self.assertIsNotNone(next_sha)
  8119. self.assertIn(next_sha, [c2.id, c3.id])
  8120. # Mark the middle commit as good or bad
  8121. if next_sha == c2.id:
  8122. # c2 is good, next should be c3
  8123. next_sha = porcelain.bisect_good(self.repo_path)
  8124. self.assertEqual(next_sha, c3.id)
  8125. # Mark c3 as bad - bisect complete
  8126. next_sha = porcelain.bisect_bad(self.repo_path)
  8127. self.assertIsNone(next_sha)
  8128. else:
  8129. # c3 is bad, next should be c2
  8130. next_sha = porcelain.bisect_bad(self.repo_path)
  8131. self.assertEqual(next_sha, c2.id)
  8132. # Mark c2 as good - bisect complete
  8133. next_sha = porcelain.bisect_good(self.repo_path)
  8134. self.assertIsNone(next_sha)
  8135. def test_bisect_log(self):
  8136. """Test getting bisect log."""
  8137. # Create some commits
  8138. c1, _c2, c3 = build_commit_graph(
  8139. self.repo.object_store,
  8140. [[1], [2, 1], [3, 2]],
  8141. attrs={
  8142. 1: {"message": b"initial"},
  8143. 2: {"message": b"second"},
  8144. 3: {"message": b"third"},
  8145. },
  8146. )
  8147. self.repo.refs[b"refs/heads/master"] = c3.id
  8148. self.repo.refs[b"HEAD"] = c3.id
  8149. # Start bisect and mark commits
  8150. porcelain.bisect_start(self.repo_path)
  8151. porcelain.bisect_bad(self.repo_path, c3.id)
  8152. porcelain.bisect_good(self.repo_path, c1.id)
  8153. # Get log
  8154. log = porcelain.bisect_log(self.repo_path)
  8155. self.assertIn("git bisect start", log)
  8156. self.assertIn("git bisect bad", log)
  8157. self.assertIn("git bisect good", log)
  8158. def test_bisect_reset(self):
  8159. """Test resetting bisect state."""
  8160. # Create some commits
  8161. c1, _c2, c3 = build_commit_graph(
  8162. self.repo.object_store,
  8163. [[1], [2, 1], [3, 2]],
  8164. attrs={
  8165. 1: {"message": b"initial"},
  8166. 2: {"message": b"second"},
  8167. 3: {"message": b"third"},
  8168. },
  8169. )
  8170. self.repo.refs[b"refs/heads/master"] = c3.id
  8171. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  8172. # Start bisect
  8173. porcelain.bisect_start(self.repo_path)
  8174. porcelain.bisect_bad(self.repo_path)
  8175. porcelain.bisect_good(self.repo_path, c1.id)
  8176. # Reset
  8177. porcelain.bisect_reset(self.repo_path)
  8178. # Check that bisect state files are removed
  8179. self.assertFalse(
  8180. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  8181. )
  8182. self.assertFalse(
  8183. os.path.exists(os.path.join(self.repo.controldir(), "refs", "bisect"))
  8184. )
  8185. # HEAD should be back to being a symbolic ref to master
  8186. head_target, _ = self.repo.refs.follow(b"HEAD")
  8187. self.assertEqual(head_target[-1], b"refs/heads/master")
  8188. def test_bisect_skip(self):
  8189. """Test skipping commits during bisect."""
  8190. # Create some commits
  8191. c1, c2, _c3, _c4, c5 = build_commit_graph(
  8192. self.repo.object_store,
  8193. [[1], [2, 1], [3, 2], [4, 3], [5, 4]],
  8194. attrs={
  8195. 1: {"message": b"good"},
  8196. 2: {"message": b"skip this"},
  8197. 3: {"message": b"bad"},
  8198. 4: {"message": b"bad"},
  8199. 5: {"message": b"bad"},
  8200. },
  8201. )
  8202. self.repo.refs[b"refs/heads/master"] = c5.id
  8203. self.repo.refs[b"HEAD"] = c5.id
  8204. # Start bisect
  8205. porcelain.bisect_start(self.repo_path, bad=c5.id, good=c1.id)
  8206. # Skip c2 if it's selected
  8207. next_sha = porcelain.bisect_skip(self.repo_path, [c2.id])
  8208. self.assertIsNotNone(next_sha)
  8209. class ReflogTest(PorcelainTestCase):
  8210. def test_reflog_head(self):
  8211. """Test reading HEAD reflog."""
  8212. # Create a commit
  8213. blob = Blob.from_string(b"test content")
  8214. self.repo.object_store.add_object(blob)
  8215. tree = Tree()
  8216. tree.add(b"test", 0o100644, blob.id)
  8217. self.repo.object_store.add_object(tree)
  8218. commit = Commit()
  8219. commit.tree = tree.id
  8220. commit.author = b"Test Author <test@example.com>"
  8221. commit.committer = b"Test Author <test@example.com>"
  8222. commit.commit_time = 1234567890
  8223. commit.commit_timezone = 0
  8224. commit.author_time = 1234567890
  8225. commit.author_timezone = 0
  8226. commit.message = b"Initial commit"
  8227. self.repo.object_store.add_object(commit)
  8228. # Write a reflog entry
  8229. self.repo._write_reflog(
  8230. b"HEAD",
  8231. ZERO_SHA,
  8232. commit.id,
  8233. b"Test Author <test@example.com>",
  8234. 1234567890,
  8235. 0,
  8236. b"commit (initial): Initial commit",
  8237. )
  8238. # Read reflog using porcelain
  8239. entries = list(porcelain.reflog(self.repo_path))
  8240. self.assertEqual(1, len(entries))
  8241. self.assertEqual(ZERO_SHA, entries[0].old_sha)
  8242. self.assertEqual(commit.id, entries[0].new_sha)
  8243. self.assertEqual(b"Test Author <test@example.com>", entries[0].committer)
  8244. self.assertEqual(1234567890, entries[0].timestamp)
  8245. self.assertEqual(0, entries[0].timezone)
  8246. self.assertEqual(b"commit (initial): Initial commit", entries[0].message)
  8247. def test_reflog_with_string_ref(self):
  8248. """Test reading reflog with string reference."""
  8249. # Create a commit
  8250. blob = Blob.from_string(b"test content")
  8251. self.repo.object_store.add_object(blob)
  8252. tree = Tree()
  8253. tree.add(b"test", 0o100644, blob.id)
  8254. self.repo.object_store.add_object(tree)
  8255. commit = Commit()
  8256. commit.tree = tree.id
  8257. commit.author = b"Test Author <test@example.com>"
  8258. commit.committer = b"Test Author <test@example.com>"
  8259. commit.commit_time = 1234567890
  8260. commit.commit_timezone = 0
  8261. commit.author_time = 1234567890
  8262. commit.author_timezone = 0
  8263. commit.message = b"Initial commit"
  8264. self.repo.object_store.add_object(commit)
  8265. # Write a reflog entry
  8266. self.repo._write_reflog(
  8267. b"refs/heads/master",
  8268. ZERO_SHA,
  8269. commit.id,
  8270. b"Test Author <test@example.com>",
  8271. 1234567890,
  8272. 0,
  8273. b"commit (initial): Initial commit",
  8274. )
  8275. # Read reflog using porcelain with string ref
  8276. entries = list(porcelain.reflog(self.repo_path, "refs/heads/master"))
  8277. self.assertEqual(1, len(entries))
  8278. self.assertEqual(commit.id, entries[0].new_sha)
  8279. def test_reflog_all(self):
  8280. """Test reading all reflogs."""
  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 = 1234567890
  8292. commit.commit_timezone = 0
  8293. commit.author_time = 1234567890
  8294. commit.author_timezone = 0
  8295. commit.message = b"Initial commit"
  8296. self.repo.object_store.add_object(commit)
  8297. # Write reflog entries for HEAD and master
  8298. self.repo._write_reflog(
  8299. b"HEAD",
  8300. ZERO_SHA,
  8301. commit.id,
  8302. b"Test Author <test@example.com>",
  8303. 1234567890,
  8304. 0,
  8305. b"commit (initial): Initial 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. 1234567891,
  8313. 0,
  8314. b"branch: Created from HEAD",
  8315. )
  8316. # Read all reflogs using porcelain
  8317. entries = list(porcelain.reflog(self.repo_path, all=True))
  8318. # Should have at least 2 entries (HEAD and refs/heads/master)
  8319. self.assertGreaterEqual(len(entries), 2)
  8320. # Check that we got entries from different refs
  8321. refs_seen = set()
  8322. for ref, entry in entries:
  8323. refs_seen.add(ref)
  8324. self.assertEqual(commit.id, entry.new_sha)
  8325. # Should have seen at least HEAD and refs/heads/master
  8326. self.assertIn(b"HEAD", refs_seen)
  8327. self.assertIn(b"refs/heads/master", refs_seen)
  8328. def test_reflog_expire_by_time(self):
  8329. """Test expiring reflog entries by timestamp."""
  8330. # Create commits
  8331. blob = Blob.from_string(b"test content")
  8332. self.repo.object_store.add_object(blob)
  8333. tree = Tree()
  8334. tree.add(b"test", 0o100644, blob.id)
  8335. self.repo.object_store.add_object(tree)
  8336. commit1 = Commit()
  8337. commit1.tree = tree.id
  8338. commit1.author = b"Test Author <test@example.com>"
  8339. commit1.committer = b"Test Author <test@example.com>"
  8340. commit1.commit_time = 1000000000
  8341. commit1.commit_timezone = 0
  8342. commit1.author_time = 1000000000
  8343. commit1.author_timezone = 0
  8344. commit1.message = b"Old commit"
  8345. self.repo.object_store.add_object(commit1)
  8346. commit2 = Commit()
  8347. commit2.tree = tree.id
  8348. commit2.author = b"Test Author <test@example.com>"
  8349. commit2.committer = b"Test Author <test@example.com>"
  8350. commit2.commit_time = 2000000000
  8351. commit2.commit_timezone = 0
  8352. commit2.author_time = 2000000000
  8353. commit2.author_timezone = 0
  8354. commit2.message = b"Recent commit"
  8355. self.repo.object_store.add_object(commit2)
  8356. # Write reflog entries with different timestamps
  8357. self.repo._write_reflog(
  8358. b"HEAD",
  8359. ZERO_SHA,
  8360. commit1.id,
  8361. b"Test Author <test@example.com>",
  8362. 1000000000,
  8363. 0,
  8364. b"commit: Old commit",
  8365. )
  8366. self.repo._write_reflog(
  8367. b"HEAD",
  8368. commit1.id,
  8369. commit2.id,
  8370. b"Test Author <test@example.com>",
  8371. 2000000000,
  8372. 0,
  8373. b"commit: Recent commit",
  8374. )
  8375. # Expire entries older than timestamp 1500000000
  8376. result = porcelain.reflog_expire(
  8377. self.repo_path, ref=b"HEAD", expire_time=1500000000
  8378. )
  8379. self.assertEqual(1, result[b"HEAD"])
  8380. # Check that only the recent entry remains
  8381. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8382. self.assertEqual(1, len(entries))
  8383. self.assertEqual(commit2.id, entries[0].new_sha)
  8384. def test_reflog_expire_all(self):
  8385. """Test expiring reflog entries for all refs."""
  8386. # Create a commit
  8387. blob = Blob.from_string(b"test content")
  8388. self.repo.object_store.add_object(blob)
  8389. tree = Tree()
  8390. tree.add(b"test", 0o100644, blob.id)
  8391. self.repo.object_store.add_object(tree)
  8392. commit = Commit()
  8393. commit.tree = tree.id
  8394. commit.author = b"Test Author <test@example.com>"
  8395. commit.committer = b"Test Author <test@example.com>"
  8396. commit.commit_time = 1000000000
  8397. commit.commit_timezone = 0
  8398. commit.author_time = 1000000000
  8399. commit.author_timezone = 0
  8400. commit.message = b"Test commit"
  8401. self.repo.object_store.add_object(commit)
  8402. # Write old reflog entries for multiple refs
  8403. self.repo._write_reflog(
  8404. b"HEAD",
  8405. ZERO_SHA,
  8406. commit.id,
  8407. b"Test Author <test@example.com>",
  8408. 1000000000,
  8409. 0,
  8410. b"commit: Test commit",
  8411. )
  8412. self.repo._write_reflog(
  8413. b"refs/heads/master",
  8414. ZERO_SHA,
  8415. commit.id,
  8416. b"Test Author <test@example.com>",
  8417. 1000000000,
  8418. 0,
  8419. b"commit: Test commit",
  8420. )
  8421. # Expire all old entries
  8422. result = porcelain.reflog_expire(
  8423. self.repo_path, all=True, expire_time=2000000000
  8424. )
  8425. # Should have expired entries from both refs
  8426. self.assertIn(b"HEAD", result)
  8427. self.assertIn(b"refs/heads/master", result)
  8428. self.assertEqual(1, result[b"HEAD"])
  8429. self.assertEqual(1, result[b"refs/heads/master"])
  8430. def test_reflog_expire_dry_run(self):
  8431. """Test dry-run mode for reflog expire."""
  8432. # Create a commit
  8433. blob = Blob.from_string(b"test content")
  8434. self.repo.object_store.add_object(blob)
  8435. tree = Tree()
  8436. tree.add(b"test", 0o100644, blob.id)
  8437. self.repo.object_store.add_object(tree)
  8438. commit = Commit()
  8439. commit.tree = tree.id
  8440. commit.author = b"Test Author <test@example.com>"
  8441. commit.committer = b"Test Author <test@example.com>"
  8442. commit.commit_time = 1000000000
  8443. commit.commit_timezone = 0
  8444. commit.author_time = 1000000000
  8445. commit.author_timezone = 0
  8446. commit.message = b"Test commit"
  8447. self.repo.object_store.add_object(commit)
  8448. # Write old reflog entry
  8449. self.repo._write_reflog(
  8450. b"HEAD",
  8451. ZERO_SHA,
  8452. commit.id,
  8453. b"Test Author <test@example.com>",
  8454. 1000000000,
  8455. 0,
  8456. b"commit: Test commit",
  8457. )
  8458. # Dry run expire
  8459. result = porcelain.reflog_expire(
  8460. self.repo_path, ref=b"HEAD", expire_time=2000000000, dry_run=True
  8461. )
  8462. self.assertEqual(1, result[b"HEAD"])
  8463. # Entry should still exist
  8464. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8465. self.assertEqual(1, len(entries))
  8466. def test_reflog_delete(self):
  8467. """Test deleting specific reflog entry."""
  8468. # Create commits
  8469. blob = Blob.from_string(b"test content")
  8470. self.repo.object_store.add_object(blob)
  8471. tree = Tree()
  8472. tree.add(b"test", 0o100644, blob.id)
  8473. self.repo.object_store.add_object(tree)
  8474. commit1 = Commit()
  8475. commit1.tree = tree.id
  8476. commit1.author = b"Test Author <test@example.com>"
  8477. commit1.committer = b"Test Author <test@example.com>"
  8478. commit1.commit_time = 1000000000
  8479. commit1.commit_timezone = 0
  8480. commit1.author_time = 1000000000
  8481. commit1.author_timezone = 0
  8482. commit1.message = b"First commit"
  8483. self.repo.object_store.add_object(commit1)
  8484. commit2 = Commit()
  8485. commit2.tree = tree.id
  8486. commit2.author = b"Test Author <test@example.com>"
  8487. commit2.committer = b"Test Author <test@example.com>"
  8488. commit2.commit_time = 2000000000
  8489. commit2.commit_timezone = 0
  8490. commit2.author_time = 2000000000
  8491. commit2.author_timezone = 0
  8492. commit2.message = b"Second commit"
  8493. self.repo.object_store.add_object(commit2)
  8494. # Write two reflog entries
  8495. self.repo._write_reflog(
  8496. b"HEAD",
  8497. ZERO_SHA,
  8498. commit1.id,
  8499. b"Test Author <test@example.com>",
  8500. 1000000000,
  8501. 0,
  8502. b"commit: First commit",
  8503. )
  8504. self.repo._write_reflog(
  8505. b"HEAD",
  8506. commit1.id,
  8507. commit2.id,
  8508. b"Test Author <test@example.com>",
  8509. 2000000000,
  8510. 0,
  8511. b"commit: Second commit",
  8512. )
  8513. # Delete the most recent entry (index 0)
  8514. porcelain.reflog_delete(self.repo_path, ref=b"HEAD", index=0)
  8515. # Should only have one entry left
  8516. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8517. self.assertEqual(1, len(entries))
  8518. self.assertEqual(commit1.id, entries[0].new_sha)
  8519. def test_reflog_expire_unreachable(self):
  8520. """Test expiring unreachable reflog entries."""
  8521. # Create commits
  8522. blob = Blob.from_string(b"test content")
  8523. self.repo.object_store.add_object(blob)
  8524. tree = Tree()
  8525. tree.add(b"test", 0o100644, blob.id)
  8526. self.repo.object_store.add_object(tree)
  8527. # Create commit 1 - will be reachable (pointed to by HEAD)
  8528. commit1 = Commit()
  8529. commit1.tree = tree.id
  8530. commit1.author = b"Test Author <test@example.com>"
  8531. commit1.committer = b"Test Author <test@example.com>"
  8532. commit1.commit_time = 1000000000
  8533. commit1.commit_timezone = 0
  8534. commit1.author_time = 1000000000
  8535. commit1.author_timezone = 0
  8536. commit1.message = b"Reachable commit"
  8537. self.repo.object_store.add_object(commit1)
  8538. # Create commit 2 - will be unreachable
  8539. commit2 = Commit()
  8540. commit2.tree = tree.id
  8541. commit2.author = b"Test Author <test@example.com>"
  8542. commit2.committer = b"Test Author <test@example.com>"
  8543. commit2.commit_time = 1500000000
  8544. commit2.commit_timezone = 0
  8545. commit2.author_time = 1500000000
  8546. commit2.author_timezone = 0
  8547. commit2.message = b"Unreachable commit"
  8548. self.repo.object_store.add_object(commit2)
  8549. # Create commit 3 - will also be reachable (pointed to by master)
  8550. commit3 = Commit()
  8551. commit3.tree = tree.id
  8552. commit3.author = b"Test Author <test@example.com>"
  8553. commit3.committer = b"Test Author <test@example.com>"
  8554. commit3.commit_time = 2000000000
  8555. commit3.commit_timezone = 0
  8556. commit3.author_time = 2000000000
  8557. commit3.author_timezone = 0
  8558. commit3.message = b"Another reachable commit"
  8559. self.repo.object_store.add_object(commit3)
  8560. # Set up refs to make commit1 and commit3 reachable
  8561. # HEAD is a symbolic ref to refs/heads/master by default, so we set master first
  8562. self.repo.refs[b"refs/heads/master"] = commit1.id
  8563. # Create another branch pointing to commit3
  8564. self.repo.refs[b"refs/heads/feature"] = commit3.id
  8565. # Write reflog entries for all three commits
  8566. self.repo._write_reflog(
  8567. b"HEAD",
  8568. ZERO_SHA,
  8569. commit1.id,
  8570. b"Test Author <test@example.com>",
  8571. 1000000000,
  8572. 0,
  8573. b"commit: Reachable commit",
  8574. )
  8575. self.repo._write_reflog(
  8576. b"HEAD",
  8577. commit1.id,
  8578. commit2.id,
  8579. b"Test Author <test@example.com>",
  8580. 1500000000,
  8581. 0,
  8582. b"commit: Unreachable commit",
  8583. )
  8584. self.repo._write_reflog(
  8585. b"HEAD",
  8586. commit2.id,
  8587. commit3.id,
  8588. b"Test Author <test@example.com>",
  8589. 2000000000,
  8590. 0,
  8591. b"commit: Another reachable commit",
  8592. )
  8593. # Expire unreachable entries older than a time that includes commit2
  8594. # but not the reachable commits
  8595. result = porcelain.reflog_expire(
  8596. self.repo_path,
  8597. ref=b"HEAD",
  8598. expire_unreachable_time=1600000000, # After commit2, before commit3
  8599. )
  8600. # Should have expired only commit2
  8601. self.assertEqual(1, result[b"HEAD"])
  8602. # Verify the remaining entries
  8603. entries = list(porcelain.reflog(self.repo_path, b"HEAD"))
  8604. self.assertEqual(2, len(entries))
  8605. # commit1 and commit3 should remain (both reachable)
  8606. self.assertEqual(commit1.id, entries[0].new_sha)
  8607. self.assertEqual(commit3.id, entries[1].new_sha)
  8608. class WriteCommitGraphTests(PorcelainTestCase):
  8609. """Tests for the write_commit_graph porcelain function."""
  8610. def test_write_commit_graph_empty_repo(self):
  8611. """Test writing commit graph on empty repository."""
  8612. # Should not fail on empty repo
  8613. porcelain.write_commit_graph(self.repo_path)
  8614. # No commit graph should be created for empty repo
  8615. graph_path = os.path.join(
  8616. self.repo_path, ".git", "objects", "info", "commit-graph"
  8617. )
  8618. self.assertFalse(os.path.exists(graph_path))
  8619. def test_write_commit_graph_with_commits(self):
  8620. """Test writing commit graph with commits."""
  8621. # Create some commits
  8622. c1, c2, c3 = build_commit_graph(
  8623. self.repo.object_store,
  8624. [[1], [2, 1], [3, 1, 2]],
  8625. attrs={
  8626. 1: {"message": b"First commit"},
  8627. 2: {"message": b"Second commit"},
  8628. 3: {"message": b"Merge commit"},
  8629. },
  8630. )
  8631. self.repo.refs[b"refs/heads/master"] = c3.id
  8632. self.repo.refs[b"refs/heads/branch"] = c2.id
  8633. # Write commit graph
  8634. porcelain.write_commit_graph(self.repo_path)
  8635. # Verify commit graph was created
  8636. graph_path = os.path.join(
  8637. self.repo_path, ".git", "objects", "info", "commit-graph"
  8638. )
  8639. self.assertTrue(os.path.exists(graph_path))
  8640. # Load and verify the commit graph
  8641. from dulwich.commit_graph import read_commit_graph
  8642. commit_graph = read_commit_graph(graph_path)
  8643. self.assertIsNotNone(commit_graph)
  8644. self.assertEqual(3, len(commit_graph))
  8645. # Verify all commits are in the graph
  8646. for commit_obj in [c1, c2, c3]:
  8647. entry = commit_graph.get_entry_by_oid(commit_obj.id)
  8648. self.assertIsNotNone(entry)
  8649. def test_write_commit_graph_config_disabled(self):
  8650. """Test that commit graph is not written when disabled by config."""
  8651. # Create a commit
  8652. (c1,) = build_commit_graph(
  8653. self.repo.object_store, [[1]], attrs={1: {"message": b"First commit"}}
  8654. )
  8655. self.repo.refs[b"refs/heads/master"] = c1.id
  8656. # Disable commit graph in config
  8657. config = self.repo.get_config()
  8658. config.set((b"core",), b"commitGraph", b"false")
  8659. config.write_to_path()
  8660. # Write commit graph (should respect config)
  8661. porcelain.write_commit_graph(self.repo_path)
  8662. # Verify commit graph still gets written
  8663. # (porcelain.write_commit_graph explicitly writes regardless of config)
  8664. graph_path = os.path.join(
  8665. self.repo_path, ".git", "objects", "info", "commit-graph"
  8666. )
  8667. self.assertTrue(os.path.exists(graph_path))
  8668. def test_write_commit_graph_reachable_false(self):
  8669. """Test writing commit graph with reachable=False."""
  8670. # Create commits
  8671. _c1, _c2, c3 = build_commit_graph(
  8672. self.repo.object_store,
  8673. [[1], [2, 1], [3, 2]],
  8674. attrs={
  8675. 1: {"message": b"First commit"},
  8676. 2: {"message": b"Second commit"},
  8677. 3: {"message": b"Third commit"},
  8678. },
  8679. )
  8680. # Only reference the third commit
  8681. self.repo.refs[b"refs/heads/master"] = c3.id
  8682. # Write commit graph with reachable=False
  8683. porcelain.write_commit_graph(self.repo_path, reachable=False)
  8684. # Verify commit graph was created
  8685. graph_path = os.path.join(
  8686. self.repo_path, ".git", "objects", "info", "commit-graph"
  8687. )
  8688. self.assertTrue(os.path.exists(graph_path))
  8689. # Load and verify the commit graph
  8690. from dulwich.commit_graph import read_commit_graph
  8691. commit_graph = read_commit_graph(graph_path)
  8692. self.assertIsNotNone(commit_graph)
  8693. # With reachable=False, only directly referenced commits should be included
  8694. # In this case, only c3 (from refs/heads/master)
  8695. self.assertEqual(1, len(commit_graph))
  8696. entry = commit_graph.get_entry_by_oid(c3.id)
  8697. self.assertIsNotNone(entry)
  8698. class WorktreePorcelainTests(PorcelainTestCase):
  8699. """Tests for porcelain worktree functions."""
  8700. def test_worktree_list_single(self):
  8701. """Test listing worktrees when only main worktree exists."""
  8702. # Create initial commit
  8703. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8704. f.write("test content")
  8705. porcelain.add(self.repo_path, ["test.txt"])
  8706. porcelain.commit(self.repo_path, message=b"Initial commit")
  8707. # List worktrees
  8708. worktrees = porcelain.worktree_list(self.repo_path)
  8709. self.assertEqual(len(worktrees), 1)
  8710. self.assertEqual(worktrees[0].path, self.repo_path)
  8711. self.assertFalse(worktrees[0].bare)
  8712. self.assertIsNotNone(worktrees[0].head)
  8713. self.assertIsNotNone(worktrees[0].branch)
  8714. def test_worktree_add_branch(self):
  8715. """Test adding a worktree with a new branch."""
  8716. # Create initial commit
  8717. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8718. f.write("test content")
  8719. porcelain.add(self.repo_path, ["test.txt"])
  8720. porcelain.commit(self.repo_path, message=b"Initial commit")
  8721. # Add worktree
  8722. wt_path = os.path.join(self.test_dir, "worktree1")
  8723. result_path = porcelain.worktree_add(self.repo_path, wt_path, branch=b"feature")
  8724. self.assertEqual(result_path, wt_path)
  8725. self.assertTrue(os.path.exists(wt_path))
  8726. self.assertTrue(os.path.exists(os.path.join(wt_path, ".git")))
  8727. # Check it appears in the list
  8728. worktrees = porcelain.worktree_list(self.repo_path)
  8729. self.assertEqual(len(worktrees), 2)
  8730. # Find the new worktree
  8731. new_wt = None
  8732. for wt in worktrees:
  8733. if wt.path == wt_path:
  8734. new_wt = wt
  8735. break
  8736. self.assertIsNotNone(new_wt)
  8737. self.assertEqual(new_wt.branch, b"refs/heads/feature")
  8738. self.assertFalse(new_wt.detached)
  8739. def test_worktree_add_detached(self):
  8740. """Test adding a detached worktree."""
  8741. # Create initial commit
  8742. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8743. f.write("test content")
  8744. porcelain.add(self.repo_path, ["test.txt"])
  8745. sha = porcelain.commit(self.repo_path, message=b"Initial commit")
  8746. # Add detached worktree
  8747. wt_path = os.path.join(self.test_dir, "detached")
  8748. porcelain.worktree_add(self.repo_path, wt_path, commit=sha, detach=True)
  8749. # Check it's detached
  8750. worktrees = porcelain.worktree_list(self.repo_path)
  8751. for wt in worktrees:
  8752. if wt.path == wt_path:
  8753. self.assertTrue(wt.detached)
  8754. self.assertIsNone(wt.branch)
  8755. self.assertEqual(wt.head, sha)
  8756. def test_worktree_remove(self):
  8757. """Test removing a worktree."""
  8758. # Create initial commit
  8759. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8760. f.write("test content")
  8761. porcelain.add(self.repo_path, ["test.txt"])
  8762. porcelain.commit(self.repo_path, message=b"Initial commit")
  8763. # Add and remove worktree
  8764. wt_path = os.path.join(self.test_dir, "to-remove")
  8765. porcelain.worktree_add(self.repo_path, wt_path)
  8766. # Verify it exists
  8767. self.assertTrue(os.path.exists(wt_path))
  8768. self.assertEqual(len(porcelain.worktree_list(self.repo_path)), 2)
  8769. # Remove it
  8770. porcelain.worktree_remove(self.repo_path, wt_path)
  8771. # Verify it's gone
  8772. self.assertFalse(os.path.exists(wt_path))
  8773. self.assertEqual(len(porcelain.worktree_list(self.repo_path)), 1)
  8774. def test_worktree_prune(self):
  8775. """Test pruning worktrees."""
  8776. # Create initial commit
  8777. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8778. f.write("test content")
  8779. porcelain.add(self.repo_path, ["test.txt"])
  8780. porcelain.commit(self.repo_path, message=b"Initial commit")
  8781. # Add worktree
  8782. wt_path = os.path.join(self.test_dir, "to-prune")
  8783. porcelain.worktree_add(self.repo_path, wt_path)
  8784. # Manually remove directory
  8785. shutil.rmtree(wt_path)
  8786. # Prune should remove the administrative files
  8787. pruned = porcelain.worktree_prune(self.repo_path)
  8788. self.assertEqual(len(pruned), 1)
  8789. # Verify it's gone from the list
  8790. worktrees = porcelain.worktree_list(self.repo_path)
  8791. self.assertEqual(len(worktrees), 1)
  8792. def test_worktree_lock_unlock(self):
  8793. """Test locking and unlocking worktrees."""
  8794. # Create initial commit
  8795. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8796. f.write("test content")
  8797. porcelain.add(self.repo_path, ["test.txt"])
  8798. porcelain.commit(self.repo_path, message=b"Initial commit")
  8799. # Add worktree
  8800. wt_path = os.path.join(self.test_dir, "lockable")
  8801. porcelain.worktree_add(self.repo_path, wt_path)
  8802. # Lock it
  8803. porcelain.worktree_lock(self.repo_path, wt_path, reason="Testing")
  8804. # Verify it's locked
  8805. worktrees = porcelain.worktree_list(self.repo_path)
  8806. for wt in worktrees:
  8807. if wt.path == wt_path:
  8808. self.assertTrue(wt.locked)
  8809. # Unlock it
  8810. porcelain.worktree_unlock(self.repo_path, wt_path)
  8811. # Verify it's unlocked
  8812. worktrees = porcelain.worktree_list(self.repo_path)
  8813. for wt in worktrees:
  8814. if wt.path == wt_path:
  8815. self.assertFalse(wt.locked)
  8816. def test_worktree_move(self):
  8817. """Test moving a worktree."""
  8818. # Create initial commit
  8819. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  8820. f.write("test content")
  8821. porcelain.add(self.repo_path, ["test.txt"])
  8822. porcelain.commit(self.repo_path, message=b"Initial commit")
  8823. # Add worktree
  8824. old_path = os.path.join(self.test_dir, "old-location")
  8825. porcelain.worktree_add(self.repo_path, old_path)
  8826. # Create a file in the worktree
  8827. test_file = os.path.join(old_path, "workspace.txt")
  8828. with open(test_file, "w") as f:
  8829. f.write("workspace content")
  8830. # Move it
  8831. new_path = os.path.join(self.test_dir, "new-location")
  8832. porcelain.worktree_move(self.repo_path, old_path, new_path)
  8833. # Verify old path doesn't exist, new path does
  8834. self.assertFalse(os.path.exists(old_path))
  8835. self.assertTrue(os.path.exists(new_path))
  8836. self.assertTrue(os.path.exists(os.path.join(new_path, "workspace.txt")))
  8837. # Verify it's in the list at new location
  8838. worktrees = porcelain.worktree_list(self.repo_path)
  8839. paths = [wt.path for wt in worktrees]
  8840. self.assertIn(new_path, paths)
  8841. self.assertNotIn(old_path, paths)
  8842. class VarTests(PorcelainTestCase):
  8843. """Tests for the var command."""
  8844. def test_var_author_ident(self):
  8845. """Test getting GIT_AUTHOR_IDENT."""
  8846. # Set up user config
  8847. config = self.repo.get_config()
  8848. config.set((b"user",), b"name", b"Test Author")
  8849. config.set((b"user",), b"email", b"author@example.com")
  8850. config.write_to_path()
  8851. result = porcelain.var(self.repo_path, variable="GIT_AUTHOR_IDENT")
  8852. self.assertIn("Test Author <author@example.com>", result)
  8853. # Check that timestamp and timezone are included
  8854. # Format: Name <email> timestamp timezone
  8855. # "Test Author" is 2 words, so we have: Test, Author, <email>, timestamp, timezone
  8856. parts = result.split()
  8857. self.assertGreaterEqual(
  8858. len(parts), 4
  8859. ) # At least name, <email>, timestamp, timezone
  8860. # Check last two parts are timestamp and timezone
  8861. self.assertTrue(parts[-2].isdigit()) # timestamp
  8862. self.assertRegex(parts[-1], r"[+-]\d{4}") # timezone
  8863. def test_var_committer_ident(self):
  8864. """Test getting GIT_COMMITTER_IDENT."""
  8865. # Set up user config
  8866. config = self.repo.get_config()
  8867. config.set((b"user",), b"name", b"Test Committer")
  8868. config.set((b"user",), b"email", b"committer@example.com")
  8869. config.write_to_path()
  8870. result = porcelain.var(self.repo_path, variable="GIT_COMMITTER_IDENT")
  8871. self.assertIn("Test Committer <committer@example.com>", result)
  8872. # Check that timestamp and timezone are included
  8873. parts = result.split()
  8874. self.assertGreaterEqual(
  8875. len(parts), 4
  8876. ) # At least name, <email>, timestamp, timezone
  8877. # Check last two parts are timestamp and timezone
  8878. self.assertTrue(parts[-2].isdigit()) # timestamp
  8879. self.assertRegex(parts[-1], r"[+-]\d{4}") # timezone
  8880. def test_var_editor(self):
  8881. """Test getting GIT_EDITOR."""
  8882. # Test with environment variable
  8883. self.overrideEnv("GIT_EDITOR", "vim")
  8884. result = porcelain.var(self.repo_path, variable="GIT_EDITOR")
  8885. self.assertEqual(result, "vim")
  8886. def test_var_editor_from_config(self):
  8887. """Test getting GIT_EDITOR from config."""
  8888. # Set up editor in config
  8889. config = self.repo.get_config()
  8890. config.set((b"core",), b"editor", b"emacs")
  8891. config.write_to_path()
  8892. # Make sure env var is not set
  8893. self.overrideEnv("GIT_EDITOR", None)
  8894. result = porcelain.var(self.repo_path, variable="GIT_EDITOR")
  8895. self.assertEqual(result, "emacs")
  8896. def test_var_pager(self):
  8897. """Test getting GIT_PAGER."""
  8898. # Test with environment variable
  8899. self.overrideEnv("GIT_PAGER", "less")
  8900. result = porcelain.var(self.repo_path, variable="GIT_PAGER")
  8901. self.assertEqual(result, "less")
  8902. def test_var_pager_from_config(self):
  8903. """Test getting GIT_PAGER from config."""
  8904. # Set up pager in config
  8905. config = self.repo.get_config()
  8906. config.set((b"core",), b"pager", b"more")
  8907. config.write_to_path()
  8908. # Make sure env var is not set
  8909. self.overrideEnv("GIT_PAGER", None)
  8910. result = porcelain.var(self.repo_path, variable="GIT_PAGER")
  8911. self.assertEqual(result, "more")
  8912. def test_var_default_branch(self):
  8913. """Test getting GIT_DEFAULT_BRANCH."""
  8914. # Set up default branch in config
  8915. config = self.repo.get_config()
  8916. config.set((b"init",), b"defaultBranch", b"main")
  8917. config.write_to_path()
  8918. result = porcelain.var(self.repo_path, variable="GIT_DEFAULT_BRANCH")
  8919. self.assertEqual(result, "main")
  8920. def test_var_default_branch_default(self):
  8921. """Test getting GIT_DEFAULT_BRANCH with default value."""
  8922. result = porcelain.var(self.repo_path, variable="GIT_DEFAULT_BRANCH")
  8923. self.assertEqual(result, "master")
  8924. def test_var_list_all(self):
  8925. """Test listing all logical variables."""
  8926. # Set up some config
  8927. config = self.repo.get_config()
  8928. config.set((b"user",), b"name", b"Test User")
  8929. config.set((b"user",), b"email", b"test@example.com")
  8930. config.write_to_path()
  8931. result = porcelain.var_list(self.repo_path)
  8932. self.assertIsInstance(result, dict)
  8933. # Check that logical variables are present
  8934. self.assertIn("GIT_AUTHOR_IDENT", result)
  8935. self.assertIn("GIT_COMMITTER_IDENT", result)
  8936. self.assertIn("GIT_DEFAULT_BRANCH", result)
  8937. # Config variables should NOT be included (deprecated feature)
  8938. self.assertNotIn("user.name", result)
  8939. self.assertNotIn("user.email", result)
  8940. # Verify only logical variables are present
  8941. for key in result.keys():
  8942. self.assertTrue(key.startswith("GIT_"))
  8943. def test_var_unknown_variable(self):
  8944. """Test requesting an unknown variable."""
  8945. with self.assertRaises(KeyError):
  8946. porcelain.var(self.repo_path, variable="UNKNOWN_VARIABLE")
  8947. class MergeBaseTests(PorcelainTestCase):
  8948. """Tests for merge-base, is_ancestor, and independent_commits."""
  8949. def test_merge_base_linear_history(self):
  8950. """Test merge-base with linear history."""
  8951. # Create linear history: c1 <- c2 <- c3
  8952. _c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  8953. self.repo.refs[b"refs/heads/branch1"] = c2.id
  8954. self.repo.refs[b"refs/heads/branch2"] = c3.id
  8955. result = porcelain.merge_base(
  8956. self.repo.path, committishes=["refs/heads/branch1", "refs/heads/branch2"]
  8957. )
  8958. self.assertEqual([c2.id], result)
  8959. def test_merge_base_diverged(self):
  8960. """Test merge-base with diverged branches."""
  8961. # Create diverged history: c1 <- c2a, c1 <- c2b
  8962. c1, c2a, c2b = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1]])
  8963. self.repo.refs[b"refs/heads/branch-a"] = c2a.id
  8964. self.repo.refs[b"refs/heads/branch-b"] = c2b.id
  8965. result = porcelain.merge_base(
  8966. self.repo.path, committishes=["refs/heads/branch-a", "refs/heads/branch-b"]
  8967. )
  8968. self.assertEqual([c1.id], result)
  8969. def test_merge_base_all(self):
  8970. """Test merge-base with --all flag."""
  8971. # Create history with multiple common ancestors
  8972. commits = build_commit_graph(
  8973. self.repo.object_store,
  8974. [[1], [2, 1], [3, 1], [4, 2, 3], [5, 2, 3]],
  8975. )
  8976. _c1, c2, c3, c4, c5 = commits
  8977. self.repo.refs[b"refs/heads/branch1"] = c4.id
  8978. self.repo.refs[b"refs/heads/branch2"] = c5.id
  8979. # Without --all, should return only first result
  8980. result = porcelain.merge_base(
  8981. self.repo.path,
  8982. committishes=["refs/heads/branch1", "refs/heads/branch2"],
  8983. all=False,
  8984. )
  8985. self.assertEqual(1, len(result))
  8986. # With --all, should return all merge bases
  8987. result_all = porcelain.merge_base(
  8988. self.repo.path,
  8989. committishes=["refs/heads/branch1", "refs/heads/branch2"],
  8990. all=True,
  8991. )
  8992. self.assertEqual(2, len(result_all))
  8993. self.assertIn(c2.id, result_all)
  8994. self.assertIn(c3.id, result_all)
  8995. def test_merge_base_octopus(self):
  8996. """Test merge-base with --octopus flag."""
  8997. # Create three-way diverged history
  8998. commits = build_commit_graph(
  8999. self.repo.object_store, [[1], [2, 1], [3, 1], [4, 1]]
  9000. )
  9001. c1, c2, c3, c4 = commits
  9002. self.repo.refs[b"refs/heads/a"] = c2.id
  9003. self.repo.refs[b"refs/heads/b"] = c3.id
  9004. self.repo.refs[b"refs/heads/c"] = c4.id
  9005. result = porcelain.merge_base(
  9006. self.repo.path,
  9007. committishes=["refs/heads/a", "refs/heads/b", "refs/heads/c"],
  9008. octopus=True,
  9009. )
  9010. self.assertEqual([c1.id], result)
  9011. def test_merge_base_requires_two_commits(self):
  9012. """Test merge-base requires at least two commits."""
  9013. with self.assertRaises(ValueError):
  9014. porcelain.merge_base(self.repo.path, committishes=["HEAD"])
  9015. def test_is_ancestor_true(self):
  9016. """Test is_ancestor returns True when commit is an ancestor."""
  9017. # Create linear history: c1 <- c2 <- c3
  9018. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  9019. self.repo.refs[b"refs/heads/main"] = c3.id
  9020. # c1 is ancestor of c3
  9021. result = porcelain.is_ancestor(
  9022. self.repo.path, ancestor=c1.id.decode(), descendant=c3.id.decode()
  9023. )
  9024. self.assertTrue(result)
  9025. # c2 is ancestor of c3
  9026. result = porcelain.is_ancestor(
  9027. self.repo.path, ancestor=c2.id.decode(), descendant=c3.id.decode()
  9028. )
  9029. self.assertTrue(result)
  9030. def test_is_ancestor_false(self):
  9031. """Test is_ancestor returns False when commit is not an ancestor."""
  9032. # Create diverged history: c1 <- c2a, c1 <- c2b
  9033. _c1, c2a, c2b = build_commit_graph(
  9034. self.repo.object_store, [[1], [2, 1], [3, 1]]
  9035. )
  9036. # c2a is not ancestor of c2b
  9037. result = porcelain.is_ancestor(
  9038. self.repo.path, ancestor=c2a.id.decode(), descendant=c2b.id.decode()
  9039. )
  9040. self.assertFalse(result)
  9041. # c2b is not ancestor of c2a
  9042. result = porcelain.is_ancestor(
  9043. self.repo.path, ancestor=c2b.id.decode(), descendant=c2a.id.decode()
  9044. )
  9045. self.assertFalse(result)
  9046. def test_is_ancestor_requires_both(self):
  9047. """Test is_ancestor requires both ancestor and descendant."""
  9048. with self.assertRaises(ValueError):
  9049. porcelain.is_ancestor(self.repo.path, ancestor="HEAD", descendant=None)
  9050. with self.assertRaises(ValueError):
  9051. porcelain.is_ancestor(self.repo.path, ancestor=None, descendant="HEAD")
  9052. def test_independent_commits_linear(self):
  9053. """Test independent_commits with linear history."""
  9054. # Create linear history: c1 <- c2 <- c3
  9055. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  9056. # Only c3 is independent (c1 and c2 are ancestors)
  9057. result = porcelain.independent_commits(
  9058. self.repo.path,
  9059. committishes=[c1.id.decode(), c2.id.decode(), c3.id.decode()],
  9060. )
  9061. self.assertEqual([c3.id], result)
  9062. def test_independent_commits_diverged(self):
  9063. """Test independent_commits with diverged branches."""
  9064. # Create diverged history: c1 <- c2a, c1 <- c2b
  9065. _c1, c2a, c2b = build_commit_graph(
  9066. self.repo.object_store, [[1], [2, 1], [3, 1]]
  9067. )
  9068. # c2a and c2b are both independent (neither is ancestor of the other)
  9069. result = porcelain.independent_commits(
  9070. self.repo.path, committishes=[c2a.id.decode(), c2b.id.decode()]
  9071. )
  9072. self.assertEqual(2, len(result))
  9073. self.assertIn(c2a.id, result)
  9074. self.assertIn(c2b.id, result)
  9075. def test_independent_commits_mixed(self):
  9076. """Test independent_commits with mixed history."""
  9077. # Create mixed history
  9078. commits = build_commit_graph(
  9079. self.repo.object_store, [[1], [2, 1], [3, 1], [4, 2]]
  9080. )
  9081. _c1, c2, c3, c4 = commits
  9082. # c4 and c3 are independent; c2 is ancestor of c4
  9083. result = porcelain.independent_commits(
  9084. self.repo.path,
  9085. committishes=[c2.id.decode(), c3.id.decode(), c4.id.decode()],
  9086. )
  9087. self.assertEqual(2, len(result))
  9088. self.assertIn(c3.id, result)
  9089. self.assertIn(c4.id, result)
  9090. self.assertNotIn(c2.id, result)
  9091. def test_independent_commits_empty(self):
  9092. """Test independent_commits with empty list."""
  9093. result = porcelain.independent_commits(self.repo.path, committishes=[])
  9094. self.assertEqual([], result)
  9095. class CherryTests(PorcelainTestCase):
  9096. """Tests for cherry command."""
  9097. def test_cherry_no_changes(self):
  9098. """Test cherry when head and upstream are the same."""
  9099. # Create a simple commit
  9100. commit_sha = self.repo.get_worktree().commit(
  9101. b"Initial commit", committer=b"Test <test@example.com>"
  9102. )
  9103. # Cherry should return empty when comparing a commit to itself
  9104. results = porcelain.cherry(
  9105. self.repo.path, upstream=commit_sha.decode(), head=commit_sha.decode()
  9106. )
  9107. self.assertEqual([], results)
  9108. def test_cherry_unique_commits(self):
  9109. """Test cherry with commits unique to head."""
  9110. # Create initial commit
  9111. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  9112. f.write("base content\n")
  9113. self.repo.get_worktree().stage(["file1.txt"])
  9114. base_commit = self.repo.get_worktree().commit(
  9115. b"Base commit", committer=b"Test <test@example.com>"
  9116. )
  9117. # Create a new commit on head
  9118. with open(os.path.join(self.repo_path, "file2.txt"), "w") as f:
  9119. f.write("new content\n")
  9120. self.repo.get_worktree().stage(["file2.txt"])
  9121. head_commit = self.repo.get_worktree().commit(
  9122. b"New commit", committer=b"Test <test@example.com>"
  9123. )
  9124. # Cherry should show the new commit as unique
  9125. results = porcelain.cherry(
  9126. self.repo.path, upstream=base_commit.decode(), head=head_commit.decode()
  9127. )
  9128. self.assertEqual(1, len(results))
  9129. status, commit_sha, message = results[0]
  9130. self.assertEqual("+", status)
  9131. self.assertEqual(head_commit, commit_sha)
  9132. self.assertIsNone(message)
  9133. def test_cherry_verbose(self):
  9134. """Test cherry with verbose flag."""
  9135. # Create initial commit
  9136. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  9137. f.write("base content\n")
  9138. self.repo.get_worktree().stage(["file1.txt"])
  9139. base_commit = self.repo.get_worktree().commit(
  9140. b"Base commit", committer=b"Test <test@example.com>"
  9141. )
  9142. # Create a new commit on head
  9143. with open(os.path.join(self.repo_path, "file2.txt"), "w") as f:
  9144. f.write("new content\n")
  9145. self.repo.get_worktree().stage(["file2.txt"])
  9146. head_commit = self.repo.get_worktree().commit(
  9147. b"New commit on head", committer=b"Test <test@example.com>"
  9148. )
  9149. # Cherry with verbose should include commit message
  9150. results = porcelain.cherry(
  9151. self.repo.path,
  9152. upstream=base_commit.decode(),
  9153. head=head_commit.decode(),
  9154. verbose=True,
  9155. )
  9156. self.assertEqual(1, len(results))
  9157. status, commit_sha, message = results[0]
  9158. self.assertEqual("+", status)
  9159. self.assertEqual(head_commit, commit_sha)
  9160. self.assertEqual(b"New commit on head", message)
  9161. def test_cherry_equivalent_patches(self):
  9162. """Test cherry with equivalent patches (cherry-picked commits)."""
  9163. # Create base commit
  9164. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  9165. f.write("line1\n")
  9166. self.repo.get_worktree().stage(["file.txt"])
  9167. base_commit = self.repo.get_worktree().commit(
  9168. b"Base commit", committer=b"Test <test@example.com>"
  9169. )
  9170. # Create upstream branch with a change
  9171. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  9172. f.write("line1\nline2\n")
  9173. self.repo.get_worktree().stage(["file.txt"])
  9174. upstream_commit = self.repo.get_worktree().commit(
  9175. b"Add line2", committer=b"Test <test@example.com>"
  9176. )
  9177. # Reset to base and create same change on head branch
  9178. self.repo.refs[b"HEAD"] = base_commit
  9179. self.repo.get_worktree().reset_index()
  9180. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  9181. f.write("line1\nline2\n")
  9182. self.repo.get_worktree().stage(["file.txt"])
  9183. head_commit = self.repo.get_worktree().commit(
  9184. b"Add line2 (different metadata)",
  9185. committer=b"Different <different@example.com>",
  9186. )
  9187. # Cherry should mark this as equivalent (-)
  9188. results = porcelain.cherry(
  9189. self.repo.path,
  9190. upstream=upstream_commit.decode(),
  9191. head=head_commit.decode(),
  9192. )
  9193. self.assertEqual(1, len(results))
  9194. status, commit_sha, _message = results[0]
  9195. self.assertEqual("-", status)
  9196. self.assertEqual(head_commit, commit_sha)
  9197. class GrepTests(PorcelainTestCase):
  9198. def test_basic_grep(self) -> None:
  9199. """Test basic pattern matching in files."""
  9200. # Create some test files
  9201. with open(os.path.join(self.repo_path, "foo.txt"), "w") as f:
  9202. f.write("hello world\ngoodbye world\n")
  9203. with open(os.path.join(self.repo_path, "bar.txt"), "w") as f:
  9204. f.write("foo bar\nbaz qux\n")
  9205. porcelain.add(self.repo, paths=["foo.txt", "bar.txt"])
  9206. porcelain.commit(self.repo, message=b"Add test files")
  9207. # Search for "world"
  9208. outstream = StringIO()
  9209. porcelain.grep(self.repo, "world", outstream=outstream)
  9210. output = outstream.getvalue().replace("\r\n", "\n")
  9211. self.assertEqual("foo.txt:hello world\nfoo.txt:goodbye world\n", output)
  9212. def test_grep_with_line_numbers(self) -> None:
  9213. """Test grep with line numbers."""
  9214. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  9215. f.write("line one\nline two\nline three\n")
  9216. porcelain.add(self.repo, paths=["test.txt"])
  9217. porcelain.commit(self.repo, message=b"Add test file")
  9218. outstream = StringIO()
  9219. porcelain.grep(self.repo, "line", outstream=outstream, line_number=True)
  9220. output = outstream.getvalue().replace("\r\n", "\n")
  9221. self.assertEqual(
  9222. "test.txt:1:line one\ntest.txt:2:line two\ntest.txt:3:line three\n",
  9223. output,
  9224. )
  9225. def test_grep_case_insensitive(self) -> None:
  9226. """Test case-insensitive grep."""
  9227. with open(os.path.join(self.repo_path, "case.txt"), "w") as f:
  9228. f.write("Hello WORLD\nGoodbye world\n")
  9229. porcelain.add(self.repo, paths=["case.txt"])
  9230. porcelain.commit(self.repo, message=b"Add case file")
  9231. outstream = StringIO()
  9232. porcelain.grep(self.repo, "HELLO", outstream=outstream, ignore_case=True)
  9233. output = outstream.getvalue().replace("\r\n", "\n")
  9234. self.assertEqual("case.txt:Hello WORLD\n", output)
  9235. def test_grep_with_pathspec(self) -> None:
  9236. """Test grep with pathspec filtering."""
  9237. os.makedirs(os.path.join(self.repo_path, "subdir"))
  9238. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  9239. f.write("pattern match\n")
  9240. with open(os.path.join(self.repo_path, "subdir", "file2.txt"), "w") as f:
  9241. f.write("pattern match\n")
  9242. porcelain.add(self.repo, paths=["file1.txt", "subdir/file2.txt"])
  9243. porcelain.commit(self.repo, message=b"Add files")
  9244. # Search only in subdir
  9245. outstream = StringIO()
  9246. porcelain.grep(self.repo, "pattern", outstream=outstream, pathspecs=["subdir/"])
  9247. output = outstream.getvalue().replace("\r\n", "\n")
  9248. self.assertEqual("subdir/file2.txt:pattern match\n", output)
  9249. def test_grep_no_matches(self) -> None:
  9250. """Test grep with no matches."""
  9251. with open(os.path.join(self.repo_path, "empty.txt"), "w") as f:
  9252. f.write("nothing to see here\n")
  9253. porcelain.add(self.repo, paths=["empty.txt"])
  9254. porcelain.commit(self.repo, message=b"Add empty file")
  9255. outstream = StringIO()
  9256. porcelain.grep(self.repo, "nonexistent", outstream=outstream)
  9257. output = outstream.getvalue()
  9258. self.assertEqual("", output)
  9259. def test_grep_regex_pattern(self) -> None:
  9260. """Test grep with regex patterns."""
  9261. with open(os.path.join(self.repo_path, "regex.txt"), "w") as f:
  9262. f.write("test123\ntest456\nnotest\n")
  9263. porcelain.add(self.repo, paths=["regex.txt"])
  9264. porcelain.commit(self.repo, message=b"Add regex file")
  9265. # Search for "test" followed by digits
  9266. outstream = StringIO()
  9267. porcelain.grep(self.repo, r"test\d+", outstream=outstream)
  9268. output = outstream.getvalue().replace("\r\n", "\n")
  9269. self.assertEqual("regex.txt:test123\nregex.txt:test456\n", output)
  9270. def test_grep_invalid_pattern(self) -> None:
  9271. """Test grep with invalid regex pattern."""
  9272. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  9273. f.write("test\n")
  9274. porcelain.add(self.repo, paths=["test.txt"])
  9275. porcelain.commit(self.repo, message=b"Add test file")
  9276. outstream = StringIO()
  9277. with self.assertRaises(ValueError):
  9278. porcelain.grep(self.repo, "[invalid", outstream=outstream)
  9279. def test_grep_no_head(self) -> None:
  9280. """Test grep fails when there's no HEAD commit."""
  9281. # Create a fresh repo with no commits
  9282. empty_repo_path = os.path.join(self.test_dir, "empty_repo")
  9283. empty_repo = Repo.init(empty_repo_path, mkdir=True)
  9284. self.addCleanup(empty_repo.close)
  9285. outstream = StringIO()
  9286. with self.assertRaises(ValueError):
  9287. porcelain.grep(empty_repo, "pattern", outstream=outstream)
  9288. class ReplaceListTests(PorcelainTestCase):
  9289. def test_empty(self) -> None:
  9290. """Test listing replacements when there are none."""
  9291. replacements = porcelain.replace_list(self.repo)
  9292. self.assertEqual([], replacements)
  9293. def test_list_replacements(self) -> None:
  9294. """Test listing replacement refs."""
  9295. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9296. self.repo[b"HEAD"] = c1.id
  9297. # Create a replacement
  9298. porcelain.replace_create(self.repo, c1.id, c2.id)
  9299. # List replacements
  9300. replacements = porcelain.replace_list(self.repo)
  9301. self.assertEqual(1, len(replacements))
  9302. self.assertEqual((c1.id, c2.id), replacements[0])
  9303. class ReplaceCreateTests(PorcelainTestCase):
  9304. def test_create_replacement(self) -> None:
  9305. """Test creating a replacement ref."""
  9306. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9307. self.repo[b"HEAD"] = c1.id
  9308. # Create a replacement
  9309. porcelain.replace_create(self.repo, c1.id, c2.id)
  9310. # Verify the replacement ref was created (c1.id is already 40-char hex bytes)
  9311. replace_ref = b"refs/replace/" + c1.id
  9312. self.assertIn(replace_ref, self.repo.refs)
  9313. self.assertEqual(c2.id, self.repo.refs[replace_ref])
  9314. def test_create_replacement_with_bytes(self) -> None:
  9315. """Test creating a replacement ref with bytes arguments."""
  9316. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9317. self.repo[b"HEAD"] = c1.id
  9318. # Create a replacement using bytes arguments
  9319. porcelain.replace_create(self.repo, c1.id, c2.id)
  9320. # Verify the replacement ref was created
  9321. replace_ref = b"refs/replace/" + c1.id
  9322. self.assertIn(replace_ref, self.repo.refs)
  9323. self.assertEqual(c2.id, self.repo.refs[replace_ref])
  9324. class ReplaceDeleteTests(PorcelainTestCase):
  9325. def test_delete_replacement(self) -> None:
  9326. """Test deleting a replacement ref."""
  9327. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9328. self.repo[b"HEAD"] = c1.id
  9329. # Create a replacement
  9330. porcelain.replace_create(self.repo, c1.id, c2.id)
  9331. # Verify it exists
  9332. replacements = porcelain.replace_list(self.repo)
  9333. self.assertEqual(1, len(replacements))
  9334. # Delete the replacement
  9335. porcelain.replace_delete(self.repo, c1.id)
  9336. # Verify it's gone
  9337. replacements = porcelain.replace_list(self.repo)
  9338. self.assertEqual(0, len(replacements))
  9339. def test_delete_replacement_with_bytes(self) -> None:
  9340. """Test deleting a replacement ref with bytes argument."""
  9341. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9342. self.repo[b"HEAD"] = c1.id
  9343. # Create a replacement
  9344. porcelain.replace_create(self.repo, c1.id, c2.id)
  9345. # Delete using bytes argument
  9346. porcelain.replace_delete(self.repo, c1.id)
  9347. # Verify it's gone
  9348. replacements = porcelain.replace_list(self.repo)
  9349. self.assertEqual(0, len(replacements))
  9350. def test_delete_nonexistent_replacement(self) -> None:
  9351. """Test deleting a replacement ref that doesn't exist raises KeyError."""
  9352. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9353. self.repo[b"HEAD"] = c1.id
  9354. # Try to delete a non-existent replacement
  9355. with self.assertRaises(KeyError):
  9356. porcelain.replace_delete(self.repo, c1.id)
  9357. class GitReflogActionTests(PorcelainTestCase):
  9358. """Tests for GIT_REFLOG_ACTION environment variable support."""
  9359. def test_reset_with_git_reflog_action(self) -> None:
  9360. """Test that reset respects GIT_REFLOG_ACTION environment variable."""
  9361. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9362. self.repo.refs[b"HEAD"] = c2.id
  9363. # Set GIT_REFLOG_ACTION environment variable
  9364. self.overrideEnv("GIT_REFLOG_ACTION", "custom reset action")
  9365. # Reset to c1
  9366. porcelain.reset(self.repo, "hard", c1.id.decode())
  9367. # Check reflog message - HEAD is a symref to refs/heads/master
  9368. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/master"))
  9369. self.assertEqual(1, len(entries))
  9370. self.assertEqual(b"custom reset action", entries[0].message)
  9371. def test_commit_amend_with_git_reflog_action(self) -> None:
  9372. """Test that commit --amend respects GIT_REFLOG_ACTION environment variable."""
  9373. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9374. self.repo.refs[b"HEAD"] = c1.id
  9375. # Set GIT_REFLOG_ACTION environment variable
  9376. self.overrideEnv("GIT_REFLOG_ACTION", "custom amend action")
  9377. # Amend the commit
  9378. porcelain.commit(self.repo, b"amended message", amend=True)
  9379. # Check reflog message - HEAD is a symref to refs/heads/master
  9380. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/master"))
  9381. self.assertEqual(1, len(entries))
  9382. self.assertEqual(b"custom amend action", entries[0].message)
  9383. def test_branch_create_with_git_reflog_action(self) -> None:
  9384. """Test that branch_create respects GIT_REFLOG_ACTION environment variable."""
  9385. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9386. self.repo.refs[b"HEAD"] = c1.id
  9387. # Set GIT_REFLOG_ACTION environment variable
  9388. self.overrideEnv("GIT_REFLOG_ACTION", "custom branch action")
  9389. # Create a new branch
  9390. porcelain.branch_create(self.repo, b"test-branch")
  9391. # Check reflog message
  9392. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/test-branch"))
  9393. self.assertEqual(1, len(entries))
  9394. self.assertEqual(b"custom branch action", entries[0].message)
  9395. def test_reset_without_git_reflog_action(self) -> None:
  9396. """Test that reset uses default message when GIT_REFLOG_ACTION is not set."""
  9397. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  9398. self.repo.refs[b"HEAD"] = c2.id
  9399. # Reset to c1 without GIT_REFLOG_ACTION
  9400. porcelain.reset(self.repo, "hard", c1.id.decode())
  9401. # Check reflog message contains default format - HEAD is a symref to refs/heads/master
  9402. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/master"))
  9403. self.assertEqual(1, len(entries))
  9404. self.assertTrue(entries[0].message.startswith(b"reset: moving to"))
  9405. def test_branch_create_without_git_reflog_action(self) -> None:
  9406. """Test that branch_create uses default message when GIT_REFLOG_ACTION is not set."""
  9407. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  9408. self.repo.refs[b"HEAD"] = c1.id
  9409. # Create a new branch without GIT_REFLOG_ACTION
  9410. porcelain.branch_create(self.repo, b"test-branch")
  9411. # Check reflog message contains default format
  9412. entries = list(porcelain.reflog(self.repo_path, b"refs/heads/test-branch"))
  9413. self.assertEqual(1, len(entries))
  9414. self.assertTrue(entries[0].message.startswith(b"branch: Created from"))
  9415. class PorcelainMailinfoTests(TestCase):
  9416. """Tests for porcelain.mailinfo function."""
  9417. def test_mailinfo_basic(self) -> None:
  9418. """Test basic mailinfo functionality."""
  9419. from io import BytesIO
  9420. email_content = b"""From: Test User <test@example.com>
  9421. Subject: [PATCH] Add feature
  9422. Date: Mon, 1 Jan 2024 12:00:00 +0000
  9423. Commit message here.
  9424. ---
  9425. diff --git a/file.txt b/file.txt
  9426. """
  9427. result = porcelain.mailinfo(BytesIO(email_content))
  9428. self.assertEqual("Test User", result.author_name)
  9429. self.assertEqual("test@example.com", result.author_email)
  9430. self.assertEqual("Add feature", result.subject)
  9431. self.assertIn("Commit message here.", result.message)
  9432. self.assertIn("diff --git", result.patch)
  9433. def test_mailinfo_write_to_files(self) -> None:
  9434. """Test mailinfo writing message and patch to files."""
  9435. from io import BytesIO
  9436. email_content = b"""From: Test <test@example.com>
  9437. Subject: Test
  9438. Message content
  9439. ---
  9440. Patch content
  9441. """
  9442. with tempfile.TemporaryDirectory() as tmpdir:
  9443. msg_file = os.path.join(tmpdir, "msg")
  9444. patch_file = os.path.join(tmpdir, "patch")
  9445. result = porcelain.mailinfo(
  9446. BytesIO(email_content), msg_file=msg_file, patch_file=patch_file
  9447. )
  9448. # Check that files were written
  9449. self.assertTrue(os.path.exists(msg_file))
  9450. self.assertTrue(os.path.exists(patch_file))
  9451. # Check file contents
  9452. with open(msg_file) as f:
  9453. msg_content = f.read()
  9454. self.assertIn("Message content", msg_content)
  9455. with open(patch_file) as f:
  9456. patch_content = f.read()
  9457. self.assertIn("Patch content", patch_content)
  9458. # Check return value
  9459. self.assertEqual("Test", result.subject)
  9460. def test_mailinfo_with_options(self) -> None:
  9461. """Test mailinfo with various options."""
  9462. from io import BytesIO
  9463. email_content = b"""From: Test <test@example.com>
  9464. Subject: [RFC][PATCH] Feature
  9465. Message-ID: <id@example.com>
  9466. Text before scissors
  9467. -- >8 --
  9468. Text after scissors
  9469. """
  9470. # Test with keep_non_patch, scissors, and message_id
  9471. result = porcelain.mailinfo(
  9472. BytesIO(email_content),
  9473. keep_non_patch=True,
  9474. scissors=True,
  9475. message_id=True,
  9476. )
  9477. self.assertEqual("[RFC] Feature", result.subject)
  9478. self.assertIn("Text after scissors", result.message)
  9479. self.assertNotIn("Text before scissors", result.message)
  9480. self.assertIn("Message-ID:", result.message)
  9481. def test_mailinfo_from_file_path(self) -> None:
  9482. """Test mailinfo reading from file path."""
  9483. email_content = b"""From: Test <test@example.com>
  9484. Subject: Test
  9485. Body
  9486. """
  9487. with tempfile.TemporaryDirectory() as tmpdir:
  9488. email_path = os.path.join(tmpdir, "email.txt")
  9489. with open(email_path, "wb") as f:
  9490. f.write(email_content)
  9491. result = porcelain.mailinfo(input_path=email_path)
  9492. self.assertEqual("Test", result.subject)
  9493. self.assertEqual("test@example.com", result.author_email)