2
0

test_porcelain.py 308 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458
  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. signoff=True,
  555. )
  556. self.assertIsInstance(sha, bytes)
  557. self.assertEqual(len(sha), 40)
  558. commit = self.repo.get_object(sha)
  559. assert isinstance(commit, Commit)
  560. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  561. commit.verify()
  562. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  563. self.import_non_default_key()
  564. self.assertRaises(
  565. gpg.errors.MissingSignatures,
  566. commit.verify,
  567. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  568. )
  569. assert isinstance(commit, Commit)
  570. commit.committer = b"Alice <alice@example.com>"
  571. self.assertRaises(
  572. gpg.errors.BadSignatures,
  573. commit.verify,
  574. )
  575. def test_non_default_key(self) -> None:
  576. c1, c2, c3 = build_commit_graph(
  577. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  578. )
  579. self.repo.refs[b"HEAD"] = c3.id
  580. cfg = self.repo.get_config()
  581. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  582. self.import_non_default_key()
  583. sha = porcelain.commit(
  584. self.repo.path,
  585. message="Some message",
  586. author="Joe <joe@example.com>",
  587. committer="Bob <bob@example.com>",
  588. signoff=PorcelainGpgTestCase.NON_DEFAULT_KEY_ID,
  589. )
  590. self.assertIsInstance(sha, bytes)
  591. self.assertEqual(len(sha), 40)
  592. commit = self.repo.get_object(sha)
  593. assert isinstance(commit, Commit)
  594. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  595. commit.verify()
  596. def test_sign_uses_config_signingkey(self) -> None:
  597. """Test that sign=True uses user.signingKey from config."""
  598. c1, c2, c3 = build_commit_graph(
  599. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  600. )
  601. self.repo.refs[b"HEAD"] = c3.id
  602. # Set up user.signingKey in config
  603. cfg = self.repo.get_config()
  604. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  605. cfg.write_to_path()
  606. self.import_default_key()
  607. # Create commit with sign=True (should use signingKey from config)
  608. sha = porcelain.commit(
  609. self.repo.path,
  610. message="Signed with configured key",
  611. author="Joe <joe@example.com>",
  612. committer="Bob <bob@example.com>",
  613. signoff=True, # This should read user.signingKey from config
  614. )
  615. self.assertIsInstance(sha, bytes)
  616. self.assertEqual(len(sha), 40)
  617. commit = self.repo.get_object(sha)
  618. assert isinstance(commit, Commit)
  619. # Verify the commit is signed with the configured key
  620. commit.verify()
  621. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  622. def test_commit_gpg_sign_config_enabled(self) -> None:
  623. """Test that commit.gpgSign=true automatically signs commits."""
  624. c1, c2, c3 = build_commit_graph(
  625. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  626. )
  627. self.repo.refs[b"HEAD"] = c3.id
  628. # Set up user.signingKey and commit.gpgSign in config
  629. cfg = self.repo.get_config()
  630. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  631. cfg.set(("commit",), "gpgSign", True)
  632. cfg.write_to_path()
  633. self.import_default_key()
  634. # Create commit without explicit signoff parameter (should auto-sign due to config)
  635. sha = porcelain.commit(
  636. self.repo.path,
  637. message="Auto-signed commit",
  638. author="Joe <joe@example.com>",
  639. committer="Bob <bob@example.com>",
  640. # No signoff parameter - should use commit.gpgSign config
  641. )
  642. self.assertIsInstance(sha, bytes)
  643. self.assertEqual(len(sha), 40)
  644. commit = self.repo.get_object(sha)
  645. assert isinstance(commit, Commit)
  646. # Verify the commit is signed due to config
  647. commit.verify()
  648. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  649. def test_commit_gpg_sign_config_disabled(self) -> None:
  650. """Test that commit.gpgSign=false does not sign commits."""
  651. c1, c2, c3 = build_commit_graph(
  652. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  653. )
  654. self.repo.refs[b"HEAD"] = c3.id
  655. # Set up user.signingKey and commit.gpgSign=false in config
  656. cfg = self.repo.get_config()
  657. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  658. cfg.set(("commit",), "gpgSign", False)
  659. cfg.write_to_path()
  660. self.import_default_key()
  661. # Create commit without explicit signoff parameter (should not sign)
  662. sha = porcelain.commit(
  663. self.repo.path,
  664. message="Unsigned commit",
  665. author="Joe <joe@example.com>",
  666. committer="Bob <bob@example.com>",
  667. # No signoff parameter - should use commit.gpgSign=false config
  668. )
  669. self.assertIsInstance(sha, bytes)
  670. self.assertEqual(len(sha), 40)
  671. commit = self.repo.get_object(sha)
  672. assert isinstance(commit, Commit)
  673. # Verify the commit is not signed
  674. self.assertIsNone(commit._gpgsig)
  675. def test_commit_gpg_sign_config_no_signing_key(self) -> None:
  676. """Test that commit.gpgSign=true works without user.signingKey (uses default)."""
  677. c1, c2, c3 = build_commit_graph(
  678. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  679. )
  680. self.repo.refs[b"HEAD"] = c3.id
  681. # Set up commit.gpgSign but no user.signingKey
  682. cfg = self.repo.get_config()
  683. cfg.set(("commit",), "gpgSign", True)
  684. cfg.write_to_path()
  685. self.import_default_key()
  686. # Create commit without explicit signoff parameter (should auto-sign with default key)
  687. sha = porcelain.commit(
  688. self.repo.path,
  689. message="Default signed commit",
  690. author="Joe <joe@example.com>",
  691. committer="Bob <bob@example.com>",
  692. # No signoff parameter - should use commit.gpgSign config with default key
  693. )
  694. self.assertIsInstance(sha, bytes)
  695. self.assertEqual(len(sha), 40)
  696. commit = self.repo.get_object(sha)
  697. assert isinstance(commit, Commit)
  698. # Verify the commit is signed with default key
  699. commit.verify()
  700. def test_explicit_signoff_overrides_config(self) -> None:
  701. """Test that explicit signoff parameter overrides commit.gpgSign config."""
  702. c1, c2, c3 = build_commit_graph(
  703. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  704. )
  705. self.repo.refs[b"HEAD"] = c3.id
  706. # Set up commit.gpgSign=false but explicitly pass signoff=True
  707. cfg = self.repo.get_config()
  708. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  709. cfg.set(("commit",), "gpgSign", False)
  710. cfg.write_to_path()
  711. self.import_default_key()
  712. # Create commit with explicit signoff=True (should override config)
  713. sha = porcelain.commit(
  714. self.repo.path,
  715. message="Explicitly signed commit",
  716. author="Joe <joe@example.com>",
  717. committer="Bob <bob@example.com>",
  718. signoff=True, # This should override commit.gpgSign=false
  719. )
  720. self.assertIsInstance(sha, bytes)
  721. self.assertEqual(len(sha), 40)
  722. commit = self.repo.get_object(sha)
  723. assert isinstance(commit, Commit)
  724. # Verify the commit is signed despite config=false
  725. commit.verify()
  726. commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  727. def test_explicit_false_disables_signing(self) -> None:
  728. """Test that explicit signoff=False disables signing even with config=true."""
  729. c1, c2, c3 = build_commit_graph(
  730. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  731. )
  732. self.repo.refs[b"HEAD"] = c3.id
  733. # Set up commit.gpgSign=true but explicitly pass signoff=False
  734. cfg = self.repo.get_config()
  735. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  736. cfg.set(("commit",), "gpgSign", True)
  737. cfg.write_to_path()
  738. self.import_default_key()
  739. # Create commit with explicit signoff=False (should disable signing)
  740. sha = porcelain.commit(
  741. self.repo.path,
  742. message="Explicitly unsigned commit",
  743. author="Joe <joe@example.com>",
  744. committer="Bob <bob@example.com>",
  745. signoff=False, # This should override commit.gpgSign=true
  746. )
  747. self.assertIsInstance(sha, bytes)
  748. self.assertEqual(len(sha), 40)
  749. commit = self.repo.get_object(sha)
  750. assert isinstance(commit, Commit)
  751. # Verify the commit is NOT signed despite config=true
  752. self.assertIsNone(commit._gpgsig)
  753. class TimezoneTests(PorcelainTestCase):
  754. def put_envs(self, value) -> None:
  755. self.overrideEnv("GIT_AUTHOR_DATE", value)
  756. self.overrideEnv("GIT_COMMITTER_DATE", value)
  757. def fallback(self, value) -> None:
  758. self.put_envs(value)
  759. self.assertRaises(porcelain.TimezoneFormatError, porcelain.get_user_timezones)
  760. def test_internal_format(self) -> None:
  761. self.put_envs("0 +0500")
  762. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  763. def test_rfc_2822(self) -> None:
  764. self.put_envs("Mon, 20 Nov 1995 19:12:08 -0500")
  765. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  766. self.put_envs("Mon, 20 Nov 1995 19:12:08")
  767. self.assertTupleEqual((0, 0), porcelain.get_user_timezones())
  768. def test_iso8601(self) -> None:
  769. self.put_envs("1995-11-20T19:12:08-0501")
  770. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  771. self.put_envs("1995-11-20T19:12:08+0501")
  772. self.assertTupleEqual((18060, 18060), porcelain.get_user_timezones())
  773. self.put_envs("1995-11-20T19:12:08-05:01")
  774. self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones())
  775. self.put_envs("1995-11-20 19:12:08-05")
  776. self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones())
  777. # https://github.com/git/git/blob/96b2d4fa927c5055adc5b1d08f10a5d7352e2989/t/t6300-for-each-ref.sh#L128
  778. self.put_envs("2006-07-03 17:18:44 +0200")
  779. self.assertTupleEqual((7200, 7200), porcelain.get_user_timezones())
  780. def test_missing_or_malformed(self) -> None:
  781. # TODO: add more here
  782. self.fallback("0 + 0500")
  783. self.fallback("a +0500")
  784. self.fallback("1995-11-20T19:12:08")
  785. self.fallback("1995-11-20T19:12:08-05:")
  786. self.fallback("1995.11.20")
  787. self.fallback("11/20/1995")
  788. self.fallback("20.11.1995")
  789. def test_different_envs(self) -> None:
  790. self.overrideEnv("GIT_AUTHOR_DATE", "0 +0500")
  791. self.overrideEnv("GIT_COMMITTER_DATE", "0 +0501")
  792. self.assertTupleEqual((18000, 18060), porcelain.get_user_timezones())
  793. def test_no_envs(self) -> None:
  794. local_timezone = time.localtime().tm_gmtoff
  795. self.put_envs("0 +0500")
  796. self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones())
  797. self.overrideEnv("GIT_COMMITTER_DATE", None)
  798. self.assertTupleEqual((18000, local_timezone), porcelain.get_user_timezones())
  799. self.put_envs("0 +0500")
  800. self.overrideEnv("GIT_AUTHOR_DATE", None)
  801. self.assertTupleEqual((local_timezone, 18000), porcelain.get_user_timezones())
  802. self.put_envs("0 +0500")
  803. self.overrideEnv("GIT_AUTHOR_DATE", None)
  804. self.overrideEnv("GIT_COMMITTER_DATE", None)
  805. self.assertTupleEqual(
  806. (local_timezone, local_timezone), porcelain.get_user_timezones()
  807. )
  808. class CleanTests(PorcelainTestCase):
  809. def put_files(self, tracked, ignored, untracked, empty_dirs) -> None:
  810. """Put the described files in the wd."""
  811. all_files = tracked | ignored | untracked
  812. for file_path in all_files:
  813. abs_path = os.path.join(self.repo.path, file_path)
  814. # File may need to be written in a dir that doesn't exist yet, so
  815. # create the parent dir(s) as necessary
  816. parent_dir = os.path.dirname(abs_path)
  817. try:
  818. os.makedirs(parent_dir)
  819. except FileExistsError:
  820. pass
  821. with open(abs_path, "w") as f:
  822. f.write("")
  823. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  824. f.writelines(ignored)
  825. for dir_path in empty_dirs:
  826. os.mkdir(os.path.join(self.repo.path, "empty_dir"))
  827. files_to_add = [os.path.join(self.repo.path, t) for t in tracked]
  828. porcelain.add(repo=self.repo.path, paths=files_to_add)
  829. porcelain.commit(repo=self.repo.path, message="init commit")
  830. def assert_wd(self, expected_paths) -> None:
  831. """Assert paths of files and dirs in wd are same as expected_paths."""
  832. control_dir_rel = os.path.relpath(self.repo._controldir, self.repo.path)
  833. # normalize paths to simplify comparison across platforms
  834. found_paths = {
  835. os.path.normpath(p)
  836. for p in flat_walk_dir(self.repo.path)
  837. if not p.split(os.sep)[0] == control_dir_rel
  838. }
  839. norm_expected_paths = {os.path.normpath(p) for p in expected_paths}
  840. self.assertEqual(found_paths, norm_expected_paths)
  841. def test_from_root(self) -> None:
  842. self.put_files(
  843. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  844. ignored={"ignored_file"},
  845. untracked={
  846. "untracked_file",
  847. "tracked_dir/untracked_dir/untracked_file",
  848. "untracked_dir/untracked_dir/untracked_file",
  849. },
  850. empty_dirs={"empty_dir"},
  851. )
  852. porcelain.clean(repo=self.repo.path, target_dir=self.repo.path)
  853. self.assert_wd(
  854. {
  855. "tracked_file",
  856. "tracked_dir/tracked_file",
  857. ".gitignore",
  858. "ignored_file",
  859. "tracked_dir",
  860. }
  861. )
  862. def test_from_subdir(self) -> None:
  863. self.put_files(
  864. tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"},
  865. ignored={"ignored_file"},
  866. untracked={
  867. "untracked_file",
  868. "tracked_dir/untracked_dir/untracked_file",
  869. "untracked_dir/untracked_dir/untracked_file",
  870. },
  871. empty_dirs={"empty_dir"},
  872. )
  873. porcelain.clean(
  874. repo=self.repo,
  875. target_dir=os.path.join(self.repo.path, "untracked_dir"),
  876. )
  877. self.assert_wd(
  878. {
  879. "tracked_file",
  880. "tracked_dir/tracked_file",
  881. ".gitignore",
  882. "ignored_file",
  883. "untracked_file",
  884. "tracked_dir/untracked_dir/untracked_file",
  885. "empty_dir",
  886. "untracked_dir",
  887. "tracked_dir",
  888. "tracked_dir/untracked_dir",
  889. }
  890. )
  891. class CloneTests(PorcelainTestCase):
  892. def test_simple_local(self) -> None:
  893. f1_1 = make_object(Blob, data=b"f1")
  894. commit_spec = [[1], [2, 1], [3, 1, 2]]
  895. trees = {
  896. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  897. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  898. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  899. }
  900. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  901. self.repo.refs[b"refs/heads/master"] = c3.id
  902. self.repo.refs[b"refs/tags/foo"] = c3.id
  903. target_path = tempfile.mkdtemp()
  904. errstream = BytesIO()
  905. self.addCleanup(shutil.rmtree, target_path)
  906. r = porcelain.clone(
  907. self.repo.path, target_path, checkout=False, errstream=errstream
  908. )
  909. self.addCleanup(r.close)
  910. self.assertEqual(r.path, target_path)
  911. target_repo = Repo(target_path)
  912. self.addCleanup(target_repo.close)
  913. self.assertEqual(0, len(target_repo.open_index()))
  914. self.assertEqual(c3.id, target_repo.refs[b"refs/tags/foo"])
  915. self.assertNotIn(b"f1", os.listdir(target_path))
  916. self.assertNotIn(b"f2", os.listdir(target_path))
  917. c = r.get_config()
  918. encoded_path = self.repo.path
  919. if not isinstance(encoded_path, bytes):
  920. encoded_path_bytes = encoded_path.encode("utf-8")
  921. else:
  922. encoded_path_bytes = encoded_path
  923. self.assertEqual(encoded_path_bytes, c.get((b"remote", b"origin"), b"url"))
  924. self.assertEqual(
  925. b"+refs/heads/*:refs/remotes/origin/*",
  926. c.get((b"remote", b"origin"), b"fetch"),
  927. )
  928. def test_simple_local_with_checkout(self) -> None:
  929. f1_1 = make_object(Blob, data=b"f1")
  930. commit_spec = [[1], [2, 1], [3, 1, 2]]
  931. trees = {
  932. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  933. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  934. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  935. }
  936. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  937. self.repo.refs[b"refs/heads/master"] = c3.id
  938. target_path = tempfile.mkdtemp()
  939. errstream = BytesIO()
  940. self.addCleanup(shutil.rmtree, target_path)
  941. with porcelain.clone(
  942. self.repo.path, target_path, checkout=True, errstream=errstream
  943. ) as r:
  944. self.assertEqual(r.path, target_path)
  945. with Repo(target_path) as r:
  946. self.assertEqual(r.head(), c3.id)
  947. self.assertIn("f1", os.listdir(target_path))
  948. self.assertIn("f2", os.listdir(target_path))
  949. def test_bare_local_with_checkout(self) -> None:
  950. f1_1 = make_object(Blob, data=b"f1")
  951. commit_spec = [[1], [2, 1], [3, 1, 2]]
  952. trees = {
  953. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  954. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  955. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  956. }
  957. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  958. self.repo.refs[b"refs/heads/master"] = c3.id
  959. target_path = tempfile.mkdtemp()
  960. errstream = BytesIO()
  961. self.addCleanup(shutil.rmtree, target_path)
  962. with porcelain.clone(
  963. self.repo.path, target_path, bare=True, errstream=errstream
  964. ) as r:
  965. self.assertEqual(r.path, target_path)
  966. with Repo(target_path) as r:
  967. r.head()
  968. self.assertRaises(NoIndexPresent, r.open_index)
  969. self.assertNotIn(b"f1", os.listdir(target_path))
  970. self.assertNotIn(b"f2", os.listdir(target_path))
  971. def test_no_checkout_with_bare(self) -> None:
  972. f1_1 = make_object(Blob, data=b"f1")
  973. commit_spec = [[1]]
  974. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  975. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  976. self.repo.refs[b"refs/heads/master"] = c1.id
  977. self.repo.refs[b"HEAD"] = c1.id
  978. target_path = tempfile.mkdtemp()
  979. errstream = BytesIO()
  980. self.addCleanup(shutil.rmtree, target_path)
  981. self.assertRaises(
  982. porcelain.Error,
  983. porcelain.clone,
  984. self.repo.path,
  985. target_path,
  986. checkout=True,
  987. bare=True,
  988. errstream=errstream,
  989. )
  990. def test_no_head_no_checkout(self) -> None:
  991. f1_1 = make_object(Blob, data=b"f1")
  992. commit_spec = [[1]]
  993. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  994. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  995. self.repo.refs[b"refs/heads/master"] = c1.id
  996. target_path = tempfile.mkdtemp()
  997. self.addCleanup(shutil.rmtree, target_path)
  998. errstream = BytesIO()
  999. r = porcelain.clone(
  1000. self.repo.path, target_path, checkout=True, errstream=errstream
  1001. )
  1002. r.close()
  1003. def test_no_head_no_checkout_outstream_errstream_autofallback(self) -> None:
  1004. f1_1 = make_object(Blob, data=b"f1")
  1005. commit_spec = [[1]]
  1006. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1007. (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1008. self.repo.refs[b"refs/heads/master"] = c1.id
  1009. target_path = tempfile.mkdtemp()
  1010. self.addCleanup(shutil.rmtree, target_path)
  1011. errstream = porcelain.NoneStream()
  1012. r = porcelain.clone(
  1013. self.repo.path, target_path, checkout=True, errstream=errstream
  1014. )
  1015. r.close()
  1016. def test_source_broken(self) -> None:
  1017. with tempfile.TemporaryDirectory() as parent:
  1018. target_path = os.path.join(parent, "target")
  1019. self.assertRaises(
  1020. Exception, porcelain.clone, "/nonexistent/repo", target_path
  1021. )
  1022. self.assertFalse(os.path.exists(target_path))
  1023. def test_fetch_symref(self) -> None:
  1024. f1_1 = make_object(Blob, data=b"f1")
  1025. trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]}
  1026. [c1] = build_commit_graph(self.repo.object_store, [[1]], trees)
  1027. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/else")
  1028. self.repo.refs[b"refs/heads/else"] = c1.id
  1029. target_path = tempfile.mkdtemp()
  1030. errstream = BytesIO()
  1031. self.addCleanup(shutil.rmtree, target_path)
  1032. r = porcelain.clone(
  1033. self.repo.path, target_path, checkout=False, errstream=errstream
  1034. )
  1035. self.addCleanup(r.close)
  1036. self.assertEqual(r.path, target_path)
  1037. target_repo = Repo(target_path)
  1038. self.addCleanup(target_repo.close)
  1039. self.assertEqual(0, len(target_repo.open_index()))
  1040. self.assertEqual(c1.id, target_repo.refs[b"refs/heads/else"])
  1041. self.assertEqual(c1.id, target_repo.refs[b"HEAD"])
  1042. self.assertEqual(
  1043. {
  1044. b"HEAD": b"refs/heads/else",
  1045. b"refs/remotes/origin/HEAD": b"refs/remotes/origin/else",
  1046. },
  1047. target_repo.refs.get_symrefs(),
  1048. )
  1049. def test_detached_head(self) -> None:
  1050. f1_1 = make_object(Blob, data=b"f1")
  1051. commit_spec = [[1], [2, 1], [3, 1, 2]]
  1052. trees = {
  1053. 1: [(b"f1", f1_1), (b"f2", f1_1)],
  1054. 2: [(b"f1", f1_1), (b"f2", f1_1)],
  1055. 3: [(b"f1", f1_1), (b"f2", f1_1)],
  1056. }
  1057. c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees)
  1058. self.repo.refs[b"refs/heads/master"] = c2.id
  1059. self.repo.refs.remove_if_equals(b"HEAD", None)
  1060. self.repo.refs[b"HEAD"] = c3.id
  1061. target_path = tempfile.mkdtemp()
  1062. self.addCleanup(shutil.rmtree, target_path)
  1063. errstream = porcelain.NoneStream()
  1064. with porcelain.clone(
  1065. self.repo.path, target_path, checkout=True, errstream=errstream
  1066. ) as r:
  1067. self.assertEqual(c3.id, r.refs[b"HEAD"])
  1068. def test_clone_pathlib(self) -> None:
  1069. from pathlib import Path
  1070. f1_1 = make_object(Blob, data=b"f1")
  1071. commit_spec = [[1]]
  1072. trees = {1: [(b"f1", f1_1)]}
  1073. c1 = build_commit_graph(self.repo.object_store, commit_spec, trees)[0]
  1074. self.repo.refs[b"refs/heads/master"] = c1.id
  1075. target_dir = tempfile.mkdtemp()
  1076. self.addCleanup(shutil.rmtree, target_dir)
  1077. target_path = Path(target_dir) / "clone_repo"
  1078. errstream = BytesIO()
  1079. r = porcelain.clone(
  1080. self.repo.path, target_path, checkout=False, errstream=errstream
  1081. )
  1082. self.addCleanup(r.close)
  1083. self.assertEqual(r.path, str(target_path))
  1084. self.assertTrue(os.path.exists(str(target_path)))
  1085. def test_clone_with_recurse_submodules(self) -> None:
  1086. # Create a submodule repository
  1087. sub_repo_path = tempfile.mkdtemp()
  1088. self.addCleanup(shutil.rmtree, sub_repo_path)
  1089. sub_repo = Repo.init(sub_repo_path)
  1090. self.addCleanup(sub_repo.close)
  1091. # Add a file to the submodule repo
  1092. sub_file = os.path.join(sub_repo_path, "subfile.txt")
  1093. with open(sub_file, "w") as f:
  1094. f.write("submodule content")
  1095. porcelain.add(sub_repo, paths=[sub_file])
  1096. sub_commit = porcelain.commit(
  1097. sub_repo,
  1098. message=b"Initial submodule commit",
  1099. author=b"Test Author <test@example.com>",
  1100. committer=b"Test Committer <test@example.com>",
  1101. )
  1102. # Create main repository with submodule
  1103. main_file = os.path.join(self.repo.path, "main.txt")
  1104. with open(main_file, "w") as f:
  1105. f.write("main content")
  1106. porcelain.add(self.repo, paths=[main_file])
  1107. porcelain.submodule_add(self.repo, sub_repo_path, "sub")
  1108. # Manually add the submodule to the index since submodule_add doesn't do it
  1109. # when the repository is local (to maintain backward compatibility)
  1110. from dulwich.index import IndexEntry
  1111. from dulwich.objects import S_IFGITLINK
  1112. index = self.repo.open_index()
  1113. index[b"sub"] = IndexEntry(
  1114. ctime=0,
  1115. mtime=0,
  1116. dev=0,
  1117. ino=0,
  1118. mode=S_IFGITLINK,
  1119. uid=0,
  1120. gid=0,
  1121. size=0,
  1122. sha=sub_commit,
  1123. flags=0,
  1124. )
  1125. index.write()
  1126. porcelain.add(self.repo, paths=[".gitmodules"])
  1127. porcelain.commit(
  1128. self.repo,
  1129. message=b"Add submodule",
  1130. author=b"Test Author <test@example.com>",
  1131. committer=b"Test Committer <test@example.com>",
  1132. )
  1133. # Clone with recurse_submodules
  1134. target_path = tempfile.mkdtemp()
  1135. self.addCleanup(shutil.rmtree, target_path)
  1136. cloned = porcelain.clone(
  1137. self.repo.path,
  1138. target_path,
  1139. recurse_submodules=True,
  1140. )
  1141. self.addCleanup(cloned.close)
  1142. # Check main file exists
  1143. cloned_main = os.path.join(target_path, "main.txt")
  1144. self.assertTrue(os.path.exists(cloned_main))
  1145. with open(cloned_main) as f:
  1146. self.assertEqual(f.read(), "main content")
  1147. # Check submodule file exists
  1148. cloned_sub_file = os.path.join(target_path, "sub", "subfile.txt")
  1149. self.assertTrue(os.path.exists(cloned_sub_file))
  1150. with open(cloned_sub_file) as f:
  1151. self.assertEqual(f.read(), "submodule content")
  1152. class InitTests(TestCase):
  1153. def test_non_bare(self) -> None:
  1154. repo_dir = tempfile.mkdtemp()
  1155. self.addCleanup(shutil.rmtree, repo_dir)
  1156. porcelain.init(repo_dir)
  1157. def test_bare(self) -> None:
  1158. repo_dir = tempfile.mkdtemp()
  1159. self.addCleanup(shutil.rmtree, repo_dir)
  1160. porcelain.init(repo_dir, bare=True)
  1161. def test_init_pathlib(self) -> None:
  1162. from pathlib import Path
  1163. repo_dir = tempfile.mkdtemp()
  1164. self.addCleanup(shutil.rmtree, repo_dir)
  1165. repo_path = Path(repo_dir)
  1166. # Test non-bare repo with pathlib
  1167. repo = porcelain.init(repo_path)
  1168. self.assertTrue(os.path.exists(os.path.join(repo_dir, ".git")))
  1169. repo.close()
  1170. def test_init_bare_pathlib(self) -> None:
  1171. from pathlib import Path
  1172. repo_dir = tempfile.mkdtemp()
  1173. self.addCleanup(shutil.rmtree, repo_dir)
  1174. repo_path = Path(repo_dir)
  1175. # Test bare repo with pathlib
  1176. repo = porcelain.init(repo_path, bare=True)
  1177. self.assertTrue(os.path.exists(os.path.join(repo_dir, "refs")))
  1178. repo.close()
  1179. class AddTests(PorcelainTestCase):
  1180. def test_add_default_paths(self) -> None:
  1181. # create a file for initial commit
  1182. fullpath = os.path.join(self.repo.path, "blah")
  1183. with open(fullpath, "w") as f:
  1184. f.write("\n")
  1185. porcelain.add(repo=self.repo.path, paths=[fullpath])
  1186. porcelain.commit(
  1187. repo=self.repo.path,
  1188. message=b"test",
  1189. author=b"test <email>",
  1190. committer=b"test <email>",
  1191. )
  1192. # Add a second test file and a file in a directory
  1193. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1194. f.write("\n")
  1195. os.mkdir(os.path.join(self.repo.path, "adir"))
  1196. with open(os.path.join(self.repo.path, "adir", "afile"), "w") as f:
  1197. f.write("\n")
  1198. cwd = os.getcwd()
  1199. self.addCleanup(os.chdir, cwd)
  1200. os.chdir(self.repo.path)
  1201. self.assertEqual({"foo", "blah", "adir", ".git"}, set(os.listdir(".")))
  1202. added, ignored = porcelain.add(self.repo.path)
  1203. # Normalize paths to use forward slashes for comparison
  1204. added_normalized = [path.replace(os.sep, "/") for path in added]
  1205. self.assertEqual(
  1206. (added_normalized, ignored),
  1207. (["foo", "adir/afile"], set()),
  1208. )
  1209. # Check that foo was added and nothing in .git was modified
  1210. index = self.repo.open_index()
  1211. self.assertEqual(sorted(index), [b"adir/afile", b"blah", b"foo"])
  1212. def test_add_default_paths_subdir(self) -> None:
  1213. os.mkdir(os.path.join(self.repo.path, "foo"))
  1214. with open(os.path.join(self.repo.path, "blah"), "w") as f:
  1215. f.write("\n")
  1216. with open(os.path.join(self.repo.path, "foo", "blie"), "w") as f:
  1217. f.write("\n")
  1218. cwd = os.getcwd()
  1219. self.addCleanup(os.chdir, cwd)
  1220. os.chdir(os.path.join(self.repo.path, "foo"))
  1221. porcelain.add(repo=self.repo.path)
  1222. porcelain.commit(
  1223. repo=self.repo.path,
  1224. message=b"test",
  1225. author=b"test <email>",
  1226. committer=b"test <email>",
  1227. )
  1228. index = self.repo.open_index()
  1229. # After fix: add() with no paths should behave like git add -A (add everything)
  1230. self.assertEqual(sorted(index), [b"blah", b"foo/blie"])
  1231. def test_add_file(self) -> None:
  1232. fullpath = os.path.join(self.repo.path, "foo")
  1233. with open(fullpath, "w") as f:
  1234. f.write("BAR")
  1235. porcelain.add(self.repo.path, paths=[fullpath])
  1236. self.assertIn(b"foo", self.repo.open_index())
  1237. def test_add_ignored(self) -> None:
  1238. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1239. f.write("foo\nsubdir/")
  1240. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1241. f.write("BAR")
  1242. with open(os.path.join(self.repo.path, "bar"), "w") as f:
  1243. f.write("BAR")
  1244. os.mkdir(os.path.join(self.repo.path, "subdir"))
  1245. with open(os.path.join(self.repo.path, "subdir", "baz"), "w") as f:
  1246. f.write("BAZ")
  1247. (added, ignored) = porcelain.add(
  1248. self.repo.path,
  1249. paths=[
  1250. os.path.join(self.repo.path, "foo"),
  1251. os.path.join(self.repo.path, "bar"),
  1252. os.path.join(self.repo.path, "subdir"),
  1253. ],
  1254. )
  1255. self.assertIn(b"bar", self.repo.open_index())
  1256. self.assertEqual({"bar"}, set(added))
  1257. self.assertEqual({"foo", "subdir/"}, ignored)
  1258. def test_add_from_ignored_directory(self) -> None:
  1259. # Test for issue #550 - adding files when cwd is in ignored directory
  1260. # Create .gitignore that ignores build/
  1261. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1262. f.write("build/\n")
  1263. # Create ignored directory
  1264. build_dir = os.path.join(self.repo.path, "build")
  1265. os.mkdir(build_dir)
  1266. # Create a file in the repo (not in ignored directory)
  1267. src_file = os.path.join(self.repo.path, "source.py")
  1268. with open(src_file, "w") as f:
  1269. f.write("print('hello')\n")
  1270. # Save current directory and change to ignored directory
  1271. original_cwd = os.getcwd()
  1272. try:
  1273. os.chdir(build_dir)
  1274. # Add file using absolute path from within ignored directory
  1275. (added, ignored) = porcelain.add(self.repo.path, paths=[src_file])
  1276. self.assertIn(b"source.py", self.repo.open_index())
  1277. self.assertEqual({"source.py"}, set(added))
  1278. finally:
  1279. os.chdir(original_cwd)
  1280. def test_add_file_absolute_path(self) -> None:
  1281. # Absolute paths are (not yet) supported
  1282. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  1283. f.write("BAR")
  1284. porcelain.add(self.repo, paths=[os.path.join(self.repo.path, "foo")])
  1285. self.assertIn(b"foo", self.repo.open_index())
  1286. def test_add_not_in_repo(self) -> None:
  1287. with open(os.path.join(self.test_dir, "foo"), "w") as f:
  1288. f.write("BAR")
  1289. self.assertRaises(
  1290. ValueError,
  1291. porcelain.add,
  1292. self.repo,
  1293. paths=[os.path.join(self.test_dir, "foo")],
  1294. )
  1295. self.assertRaises(
  1296. (ValueError, FileNotFoundError),
  1297. porcelain.add,
  1298. self.repo,
  1299. paths=["../foo"],
  1300. )
  1301. self.assertEqual([], list(self.repo.open_index()))
  1302. def test_add_file_clrf_conversion(self) -> None:
  1303. from dulwich.index import IndexEntry
  1304. # Set the right configuration to the repo
  1305. c = self.repo.get_config()
  1306. c.set("core", "autocrlf", "input")
  1307. c.write_to_path()
  1308. # Add a file with CRLF line-ending
  1309. fullpath = os.path.join(self.repo.path, "foo")
  1310. with open(fullpath, "wb") as f:
  1311. f.write(b"line1\r\nline2")
  1312. porcelain.add(self.repo.path, paths=[fullpath])
  1313. # The line-endings should have been converted to LF
  1314. index = self.repo.open_index()
  1315. self.assertIn(b"foo", index)
  1316. entry = index[b"foo"]
  1317. assert isinstance(entry, IndexEntry)
  1318. blob = self.repo[entry.sha]
  1319. self.assertEqual(blob.data, b"line1\nline2")
  1320. def test_add_symlink_outside_repo(self) -> None:
  1321. """Test adding a symlink that points outside the repository."""
  1322. # Create a symlink pointing outside the repository
  1323. symlink_path = os.path.join(self.repo.path, "symlink_to_nowhere")
  1324. os.symlink("/nonexistent/path", symlink_path)
  1325. # Adding the symlink should succeed (matching Git's behavior)
  1326. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1327. # Should successfully add the symlink
  1328. self.assertIn("symlink_to_nowhere", added)
  1329. self.assertEqual(len(ignored), 0)
  1330. # Verify symlink is actually staged
  1331. index = self.repo.open_index()
  1332. self.assertIn(b"symlink_to_nowhere", index)
  1333. def test_add_symlink_to_file_inside_repo(self) -> None:
  1334. """Test adding a symlink that points to a file inside the repository."""
  1335. # Create a regular file
  1336. target_file = os.path.join(self.repo.path, "target.txt")
  1337. with open(target_file, "w") as f:
  1338. f.write("target content")
  1339. # Create a symlink to the file
  1340. symlink_path = os.path.join(self.repo.path, "link_to_target")
  1341. os.symlink("target.txt", symlink_path)
  1342. # Add both the target and the symlink
  1343. added, ignored = porcelain.add(
  1344. self.repo.path, paths=[target_file, symlink_path]
  1345. )
  1346. # Both should be added successfully
  1347. self.assertIn("target.txt", added)
  1348. self.assertIn("link_to_target", added)
  1349. self.assertEqual(len(ignored), 0)
  1350. # Verify both are in the index
  1351. index = self.repo.open_index()
  1352. self.assertIn(b"target.txt", index)
  1353. self.assertIn(b"link_to_target", index)
  1354. def test_add_symlink_to_directory_inside_repo(self) -> None:
  1355. """Test adding a symlink that points to a directory inside the repository."""
  1356. # Create a directory with some files
  1357. target_dir = os.path.join(self.repo.path, "target_dir")
  1358. os.mkdir(target_dir)
  1359. with open(os.path.join(target_dir, "file1.txt"), "w") as f:
  1360. f.write("content1")
  1361. with open(os.path.join(target_dir, "file2.txt"), "w") as f:
  1362. f.write("content2")
  1363. # Create a symlink to the directory
  1364. symlink_path = os.path.join(self.repo.path, "link_to_dir")
  1365. os.symlink("target_dir", symlink_path)
  1366. # Add the symlink
  1367. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1368. # When adding a symlink to a directory, it follows the symlink and adds contents
  1369. self.assertEqual(len(added), 2)
  1370. self.assertIn("link_to_dir/file1.txt", added)
  1371. self.assertIn("link_to_dir/file2.txt", added)
  1372. self.assertEqual(len(ignored), 0)
  1373. # Verify files are added through the symlink path
  1374. index = self.repo.open_index()
  1375. self.assertIn(b"link_to_dir/file1.txt", index)
  1376. self.assertIn(b"link_to_dir/file2.txt", index)
  1377. # The original target directory files are not added
  1378. self.assertNotIn(b"target_dir/file1.txt", index)
  1379. self.assertNotIn(b"target_dir/file2.txt", index)
  1380. def test_add_symlink_chain(self) -> None:
  1381. """Test adding a chain of symlinks (symlink to symlink)."""
  1382. # Create a regular file
  1383. target_file = os.path.join(self.repo.path, "original.txt")
  1384. with open(target_file, "w") as f:
  1385. f.write("original content")
  1386. # Create first symlink
  1387. first_link = os.path.join(self.repo.path, "link1")
  1388. os.symlink("original.txt", first_link)
  1389. # Create second symlink pointing to first
  1390. second_link = os.path.join(self.repo.path, "link2")
  1391. os.symlink("link1", second_link)
  1392. # Add all files
  1393. added, ignored = porcelain.add(
  1394. self.repo.path, paths=[target_file, first_link, second_link]
  1395. )
  1396. # All should be added
  1397. self.assertEqual(len(added), 3)
  1398. self.assertIn("original.txt", added)
  1399. self.assertIn("link1", added)
  1400. self.assertIn("link2", added)
  1401. # Verify all are in the index
  1402. index = self.repo.open_index()
  1403. self.assertIn(b"original.txt", index)
  1404. self.assertIn(b"link1", index)
  1405. self.assertIn(b"link2", index)
  1406. def test_add_broken_symlink(self) -> None:
  1407. """Test adding a broken symlink (points to non-existent target)."""
  1408. # Create a symlink to a non-existent file
  1409. broken_link = os.path.join(self.repo.path, "broken_link")
  1410. os.symlink("does_not_exist.txt", broken_link)
  1411. # Add the broken symlink
  1412. added, ignored = porcelain.add(self.repo.path, paths=[broken_link])
  1413. # Should be added successfully (Git tracks the symlink, not its target)
  1414. self.assertIn("broken_link", added)
  1415. self.assertEqual(len(ignored), 0)
  1416. # Verify it's in the index
  1417. index = self.repo.open_index()
  1418. self.assertIn(b"broken_link", index)
  1419. def test_add_symlink_relative_outside_repo(self) -> None:
  1420. """Test adding a symlink that uses '..' to point outside the repository."""
  1421. # Create a file outside the repo
  1422. outside_file = os.path.join(self.test_dir, "outside.txt")
  1423. with open(outside_file, "w") as f:
  1424. f.write("outside content")
  1425. # Create a symlink using relative path to go outside
  1426. symlink_path = os.path.join(self.repo.path, "link_outside")
  1427. os.symlink("../outside.txt", symlink_path)
  1428. # Add the symlink
  1429. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1430. # Should be added successfully
  1431. self.assertIn("link_outside", added)
  1432. self.assertEqual(len(ignored), 0)
  1433. # Verify it's in the index
  1434. index = self.repo.open_index()
  1435. self.assertIn(b"link_outside", index)
  1436. def test_add_symlink_absolute_to_system(self) -> None:
  1437. """Test adding a symlink with absolute path to system directory."""
  1438. # Create a symlink to a system directory
  1439. symlink_path = os.path.join(self.repo.path, "link_to_tmp")
  1440. if os.name == "nt":
  1441. # On Windows, use a system directory like TEMP
  1442. symlink_target = os.environ["TEMP"]
  1443. else:
  1444. # On Unix-like systems, use /tmp
  1445. symlink_target = "/tmp"
  1446. os.symlink(symlink_target, symlink_path)
  1447. # Adding a symlink to a directory outside the repo should raise ValueError
  1448. with self.assertRaises(ValueError) as cm:
  1449. porcelain.add(self.repo.path, paths=[symlink_path])
  1450. # Check that the error indicates the path is outside the repository
  1451. self.assertIn("is not in the subpath of", str(cm.exception))
  1452. def test_add_file_through_symlink(self) -> None:
  1453. """Test adding a file through a symlinked directory."""
  1454. # Create a directory with a file
  1455. real_dir = os.path.join(self.repo.path, "real_dir")
  1456. os.mkdir(real_dir)
  1457. real_file = os.path.join(real_dir, "file.txt")
  1458. with open(real_file, "w") as f:
  1459. f.write("content")
  1460. # Create a symlink to the directory
  1461. link_dir = os.path.join(self.repo.path, "link_dir")
  1462. os.symlink("real_dir", link_dir)
  1463. # Try to add the file through the symlink path
  1464. symlink_file_path = os.path.join(link_dir, "file.txt")
  1465. # This should add the real file, not create a new entry
  1466. added, ignored = porcelain.add(self.repo.path, paths=[symlink_file_path])
  1467. # The real file should be added
  1468. self.assertIn("real_dir/file.txt", added)
  1469. self.assertEqual(len(added), 1)
  1470. # Verify correct path in index
  1471. index = self.repo.open_index()
  1472. self.assertIn(b"real_dir/file.txt", index)
  1473. # Should not create a separate entry for the symlink path
  1474. self.assertNotIn(b"link_dir/file.txt", index)
  1475. def test_add_repo_path(self) -> None:
  1476. """Test adding the repository path itself should add all untracked files."""
  1477. # Create some untracked files
  1478. with open(os.path.join(self.repo.path, "file1.txt"), "w") as f:
  1479. f.write("content1")
  1480. with open(os.path.join(self.repo.path, "file2.txt"), "w") as f:
  1481. f.write("content2")
  1482. # Add the repository path itself
  1483. added, ignored = porcelain.add(self.repo.path, paths=[self.repo.path])
  1484. # Should add all untracked files, not stage './'
  1485. self.assertIn("file1.txt", added)
  1486. self.assertIn("file2.txt", added)
  1487. self.assertNotIn("./", added)
  1488. # Verify files are actually staged
  1489. index = self.repo.open_index()
  1490. self.assertIn(b"file1.txt", index)
  1491. self.assertIn(b"file2.txt", index)
  1492. def test_add_directory_contents(self) -> None:
  1493. """Test adding a directory adds all files within it."""
  1494. # Create a subdirectory with multiple files
  1495. subdir = os.path.join(self.repo.path, "subdir")
  1496. os.mkdir(subdir)
  1497. with open(os.path.join(subdir, "file1.txt"), "w") as f:
  1498. f.write("content1")
  1499. with open(os.path.join(subdir, "file2.txt"), "w") as f:
  1500. f.write("content2")
  1501. with open(os.path.join(subdir, "file3.txt"), "w") as f:
  1502. f.write("content3")
  1503. # Add the directory
  1504. added, ignored = porcelain.add(self.repo.path, paths=["subdir"])
  1505. # Should add all files in the directory
  1506. self.assertEqual(len(added), 3)
  1507. # Normalize paths to use forward slashes for comparison
  1508. added_normalized = [path.replace(os.sep, "/") for path in added]
  1509. self.assertIn("subdir/file1.txt", added_normalized)
  1510. self.assertIn("subdir/file2.txt", added_normalized)
  1511. self.assertIn("subdir/file3.txt", added_normalized)
  1512. # Verify files are actually staged
  1513. index = self.repo.open_index()
  1514. self.assertIn(b"subdir/file1.txt", index)
  1515. self.assertIn(b"subdir/file2.txt", index)
  1516. self.assertIn(b"subdir/file3.txt", index)
  1517. def test_add_nested_directories(self) -> None:
  1518. """Test adding a directory with nested subdirectories."""
  1519. # Create nested directory structure
  1520. dir1 = os.path.join(self.repo.path, "dir1")
  1521. dir2 = os.path.join(dir1, "dir2")
  1522. dir3 = os.path.join(dir2, "dir3")
  1523. os.makedirs(dir3)
  1524. # Add files at each level
  1525. with open(os.path.join(dir1, "file1.txt"), "w") as f:
  1526. f.write("level1")
  1527. with open(os.path.join(dir2, "file2.txt"), "w") as f:
  1528. f.write("level2")
  1529. with open(os.path.join(dir3, "file3.txt"), "w") as f:
  1530. f.write("level3")
  1531. # Add the top-level directory
  1532. added, ignored = porcelain.add(self.repo.path, paths=["dir1"])
  1533. # Should add all files recursively
  1534. self.assertEqual(len(added), 3)
  1535. # Normalize paths to use forward slashes for comparison
  1536. added_normalized = [path.replace(os.sep, "/") for path in added]
  1537. self.assertIn("dir1/file1.txt", added_normalized)
  1538. self.assertIn("dir1/dir2/file2.txt", added_normalized)
  1539. self.assertIn("dir1/dir2/dir3/file3.txt", added_normalized)
  1540. # Verify files are actually staged
  1541. index = self.repo.open_index()
  1542. self.assertIn(b"dir1/file1.txt", index)
  1543. self.assertIn(b"dir1/dir2/file2.txt", index)
  1544. self.assertIn(b"dir1/dir2/dir3/file3.txt", index)
  1545. def test_add_directory_with_tracked_files(self) -> None:
  1546. """Test adding a directory with some files already tracked."""
  1547. # Create a subdirectory with files
  1548. subdir = os.path.join(self.repo.path, "mixed")
  1549. os.mkdir(subdir)
  1550. # Create and commit one file
  1551. tracked_file = os.path.join(subdir, "tracked.txt")
  1552. with open(tracked_file, "w") as f:
  1553. f.write("already tracked")
  1554. porcelain.add(self.repo.path, paths=[tracked_file])
  1555. porcelain.commit(
  1556. repo=self.repo.path,
  1557. message=b"Add tracked file",
  1558. author=b"test <email>",
  1559. committer=b"test <email>",
  1560. )
  1561. # Add more untracked files
  1562. with open(os.path.join(subdir, "untracked1.txt"), "w") as f:
  1563. f.write("new file 1")
  1564. with open(os.path.join(subdir, "untracked2.txt"), "w") as f:
  1565. f.write("new file 2")
  1566. # Add the directory
  1567. added, ignored = porcelain.add(self.repo.path, paths=["mixed"])
  1568. # Should only add the untracked files
  1569. self.assertEqual(len(added), 2)
  1570. # Normalize paths to use forward slashes for comparison
  1571. added_normalized = [path.replace(os.sep, "/") for path in added]
  1572. self.assertIn("mixed/untracked1.txt", added_normalized)
  1573. self.assertIn("mixed/untracked2.txt", added_normalized)
  1574. self.assertNotIn("mixed/tracked.txt", added)
  1575. # Verify the index contains all files
  1576. index = self.repo.open_index()
  1577. self.assertIn(b"mixed/tracked.txt", index)
  1578. self.assertIn(b"mixed/untracked1.txt", index)
  1579. self.assertIn(b"mixed/untracked2.txt", index)
  1580. def test_add_directory_with_gitignore(self) -> None:
  1581. """Test adding a directory respects .gitignore patterns."""
  1582. # Create .gitignore
  1583. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1584. f.write("*.log\n*.tmp\nbuild/\n")
  1585. # Create directory with mixed files
  1586. testdir = os.path.join(self.repo.path, "testdir")
  1587. os.mkdir(testdir)
  1588. # Create various files
  1589. with open(os.path.join(testdir, "important.txt"), "w") as f:
  1590. f.write("keep this")
  1591. with open(os.path.join(testdir, "debug.log"), "w") as f:
  1592. f.write("ignore this")
  1593. with open(os.path.join(testdir, "temp.tmp"), "w") as f:
  1594. f.write("ignore this too")
  1595. with open(os.path.join(testdir, "readme.md"), "w") as f:
  1596. f.write("keep this too")
  1597. # Create a build directory that should be ignored
  1598. builddir = os.path.join(testdir, "build")
  1599. os.mkdir(builddir)
  1600. with open(os.path.join(builddir, "output.txt"), "w") as f:
  1601. f.write("ignore entire directory")
  1602. # Add the directory
  1603. added, ignored = porcelain.add(self.repo.path, paths=["testdir"])
  1604. # Should only add non-ignored files
  1605. # Normalize paths to use forward slashes for comparison
  1606. added_normalized = {path.replace(os.sep, "/") for path in added}
  1607. self.assertEqual(
  1608. added_normalized, {"testdir/important.txt", "testdir/readme.md"}
  1609. )
  1610. # Check ignored files
  1611. # Normalize paths to use forward slashes for comparison
  1612. ignored_normalized = {path.replace(os.sep, "/") for path in ignored}
  1613. self.assertIn("testdir/debug.log", ignored_normalized)
  1614. self.assertIn("testdir/temp.tmp", ignored_normalized)
  1615. self.assertIn("testdir/build/", ignored_normalized)
  1616. def test_add_multiple_directories(self) -> None:
  1617. """Test adding multiple directories in one call."""
  1618. # Create multiple directories
  1619. for dirname in ["dir1", "dir2", "dir3"]:
  1620. dirpath = os.path.join(self.repo.path, dirname)
  1621. os.mkdir(dirpath)
  1622. # Add files to each directory
  1623. for i in range(2):
  1624. with open(os.path.join(dirpath, f"file{i}.txt"), "w") as f:
  1625. f.write(f"content {dirname} {i}")
  1626. # Add all directories at once
  1627. added, ignored = porcelain.add(self.repo.path, paths=["dir1", "dir2", "dir3"])
  1628. # Should add all files from all directories
  1629. self.assertEqual(len(added), 6)
  1630. # Normalize paths to use forward slashes for comparison
  1631. added_normalized = [path.replace(os.sep, "/") for path in added]
  1632. for dirname in ["dir1", "dir2", "dir3"]:
  1633. for i in range(2):
  1634. self.assertIn(f"{dirname}/file{i}.txt", added_normalized)
  1635. # Verify all files are staged
  1636. index = self.repo.open_index()
  1637. self.assertEqual(len(index), 6)
  1638. def test_add_default_paths_includes_modified_files(self) -> None:
  1639. """Test that add() with no paths includes both untracked and modified files."""
  1640. # Create and commit initial file
  1641. initial_file = os.path.join(self.repo.path, "existing.txt")
  1642. with open(initial_file, "w") as f:
  1643. f.write("initial content\n")
  1644. porcelain.add(repo=self.repo.path, paths=[initial_file])
  1645. porcelain.commit(
  1646. repo=self.repo.path,
  1647. message=b"initial commit",
  1648. author=b"test <email>",
  1649. committer=b"test <email>",
  1650. )
  1651. # Modify the existing file (this creates an unstaged change)
  1652. with open(initial_file, "w") as f:
  1653. f.write("modified content\n")
  1654. # Create a new untracked file
  1655. new_file = os.path.join(self.repo.path, "new.txt")
  1656. with open(new_file, "w") as f:
  1657. f.write("new file content\n")
  1658. # Call add() with no paths - should stage both modified and untracked files
  1659. added_files, ignored_files = porcelain.add(repo=self.repo.path)
  1660. # Verify both files were added
  1661. self.assertIn("existing.txt", added_files)
  1662. self.assertIn("new.txt", added_files)
  1663. self.assertEqual(len(ignored_files), 0)
  1664. # Verify both files are now staged
  1665. index = self.repo.open_index()
  1666. self.assertIn(b"existing.txt", index)
  1667. self.assertIn(b"new.txt", index)
  1668. class RemoveTests(PorcelainTestCase):
  1669. def test_remove_file(self) -> None:
  1670. fullpath = os.path.join(self.repo.path, "foo")
  1671. with open(fullpath, "w") as f:
  1672. f.write("BAR")
  1673. porcelain.add(self.repo.path, paths=[fullpath])
  1674. porcelain.commit(
  1675. repo=self.repo,
  1676. message=b"test",
  1677. author=b"test <email>",
  1678. committer=b"test <email>",
  1679. )
  1680. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "foo")))
  1681. cwd = os.getcwd()
  1682. self.addCleanup(os.chdir, cwd)
  1683. os.chdir(self.repo.path)
  1684. porcelain.remove(self.repo.path, paths=["foo"])
  1685. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1686. def test_remove_file_staged(self) -> None:
  1687. fullpath = os.path.join(self.repo.path, "foo")
  1688. with open(fullpath, "w") as f:
  1689. f.write("BAR")
  1690. cwd = os.getcwd()
  1691. self.addCleanup(os.chdir, cwd)
  1692. os.chdir(self.repo.path)
  1693. porcelain.add(self.repo.path, paths=[fullpath])
  1694. self.assertRaises(Exception, porcelain.rm, self.repo.path, paths=["foo"])
  1695. def test_remove_file_removed_on_disk(self) -> None:
  1696. fullpath = os.path.join(self.repo.path, "foo")
  1697. with open(fullpath, "w") as f:
  1698. f.write("BAR")
  1699. porcelain.add(self.repo.path, paths=[fullpath])
  1700. cwd = os.getcwd()
  1701. self.addCleanup(os.chdir, cwd)
  1702. os.chdir(self.repo.path)
  1703. os.remove(fullpath)
  1704. porcelain.remove(self.repo.path, paths=["foo"])
  1705. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1706. def test_remove_from_different_directory(self) -> None:
  1707. # Create a subdirectory with a file
  1708. subdir = os.path.join(self.repo.path, "mydir")
  1709. os.makedirs(subdir)
  1710. fullpath = os.path.join(subdir, "myfile")
  1711. with open(fullpath, "w") as f:
  1712. f.write("BAR")
  1713. # Add and commit the file
  1714. porcelain.add(self.repo.path, paths=[fullpath])
  1715. porcelain.commit(
  1716. repo=self.repo,
  1717. message=b"test",
  1718. author=b"test <email>",
  1719. committer=b"test <email>",
  1720. )
  1721. # Change to a different directory
  1722. cwd = os.getcwd()
  1723. tempdir = tempfile.mkdtemp()
  1724. def cleanup():
  1725. os.chdir(cwd)
  1726. shutil.rmtree(tempdir)
  1727. self.addCleanup(cleanup)
  1728. os.chdir(tempdir)
  1729. # Remove the file using relative path from repository root
  1730. porcelain.remove(self.repo.path, paths=["mydir/myfile"])
  1731. # Verify file was removed
  1732. self.assertFalse(os.path.exists(fullpath))
  1733. def test_remove_with_absolute_path(self) -> None:
  1734. # Create a file
  1735. fullpath = os.path.join(self.repo.path, "foo")
  1736. with open(fullpath, "w") as f:
  1737. f.write("BAR")
  1738. # Add and commit the file
  1739. porcelain.add(self.repo.path, paths=[fullpath])
  1740. porcelain.commit(
  1741. repo=self.repo,
  1742. message=b"test",
  1743. author=b"test <email>",
  1744. committer=b"test <email>",
  1745. )
  1746. # Change to a different directory
  1747. cwd = os.getcwd()
  1748. tempdir = tempfile.mkdtemp()
  1749. def cleanup():
  1750. os.chdir(cwd)
  1751. shutil.rmtree(tempdir)
  1752. self.addCleanup(cleanup)
  1753. os.chdir(tempdir)
  1754. # Remove the file using absolute path
  1755. porcelain.remove(self.repo.path, paths=[fullpath])
  1756. # Verify file was removed
  1757. self.assertFalse(os.path.exists(fullpath))
  1758. def test_remove_with_filter_normalization(self) -> None:
  1759. # Enable autocrlf to normalize line endings
  1760. config = self.repo.get_config()
  1761. config.set(("core",), "autocrlf", b"true")
  1762. config.write_to_path()
  1763. # Create a file with LF line endings (will be stored with LF in index)
  1764. fullpath = os.path.join(self.repo.path, "foo.txt")
  1765. with open(fullpath, "wb") as f:
  1766. f.write(b"line1\nline2\nline3")
  1767. # Add and commit the file (stored with LF in index)
  1768. porcelain.add(self.repo.path, paths=[fullpath])
  1769. porcelain.commit(
  1770. repo=self.repo,
  1771. message=b"Add file with LF",
  1772. author=b"test <email>",
  1773. committer=b"test <email>",
  1774. )
  1775. # Simulate checkout with CRLF conversion (as would happen on Windows)
  1776. with open(fullpath, "wb") as f:
  1777. f.write(b"line1\r\nline2\r\nline3")
  1778. # Verify file exists
  1779. self.assertTrue(os.path.exists(fullpath))
  1780. # Remove the file - this should not fail even though working tree has CRLF
  1781. # and index has LF (thanks to the normalization in the commit)
  1782. cwd = os.getcwd()
  1783. os.chdir(self.repo.path)
  1784. self.addCleanup(os.chdir, cwd)
  1785. porcelain.remove(self.repo.path, paths=["foo.txt"])
  1786. # Verify file was removed
  1787. self.assertFalse(os.path.exists(fullpath))
  1788. class MvTests(PorcelainTestCase):
  1789. def test_mv_file(self) -> None:
  1790. # Create a file
  1791. fullpath = os.path.join(self.repo.path, "foo")
  1792. with open(fullpath, "w") as f:
  1793. f.write("BAR")
  1794. # Add and commit the file
  1795. porcelain.add(self.repo.path, paths=[fullpath])
  1796. porcelain.commit(
  1797. repo=self.repo,
  1798. message=b"test",
  1799. author=b"test <email>",
  1800. committer=b"test <email>",
  1801. )
  1802. # Move the file
  1803. porcelain.mv(self.repo.path, "foo", "bar")
  1804. # Verify old path doesn't exist and new path does
  1805. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1806. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "bar")))
  1807. # Verify index was updated
  1808. index = self.repo.open_index()
  1809. self.assertNotIn(b"foo", index)
  1810. self.assertIn(b"bar", index)
  1811. def test_mv_file_to_existing_directory(self) -> None:
  1812. # Create a file and a directory
  1813. fullpath = os.path.join(self.repo.path, "foo")
  1814. with open(fullpath, "w") as f:
  1815. f.write("BAR")
  1816. dirpath = os.path.join(self.repo.path, "mydir")
  1817. os.makedirs(dirpath)
  1818. # Add and commit the file
  1819. porcelain.add(self.repo.path, paths=[fullpath])
  1820. porcelain.commit(
  1821. repo=self.repo,
  1822. message=b"test",
  1823. author=b"test <email>",
  1824. committer=b"test <email>",
  1825. )
  1826. # Move the file into the directory
  1827. porcelain.mv(self.repo.path, "foo", "mydir")
  1828. # Verify file moved into directory
  1829. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1830. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "mydir", "foo")))
  1831. # Verify index was updated
  1832. index = self.repo.open_index()
  1833. self.assertNotIn(b"foo", index)
  1834. self.assertIn(b"mydir/foo", index)
  1835. def test_mv_file_force_overwrite(self) -> None:
  1836. # Create two files
  1837. fullpath1 = os.path.join(self.repo.path, "foo")
  1838. with open(fullpath1, "w") as f:
  1839. f.write("FOO")
  1840. fullpath2 = os.path.join(self.repo.path, "bar")
  1841. with open(fullpath2, "w") as f:
  1842. f.write("BAR")
  1843. # Add and commit both files
  1844. porcelain.add(self.repo.path, paths=[fullpath1, fullpath2])
  1845. porcelain.commit(
  1846. repo=self.repo,
  1847. message=b"test",
  1848. author=b"test <email>",
  1849. committer=b"test <email>",
  1850. )
  1851. # Try to move without force (should fail)
  1852. self.assertRaises(porcelain.Error, porcelain.mv, self.repo.path, "foo", "bar")
  1853. # Move with force
  1854. porcelain.mv(self.repo.path, "foo", "bar", force=True)
  1855. # Verify foo doesn't exist and bar has foo's content
  1856. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1857. with open(os.path.join(self.repo.path, "bar")) as f:
  1858. self.assertEqual(f.read(), "FOO")
  1859. def test_mv_file_not_tracked(self) -> None:
  1860. # Create an untracked file
  1861. fullpath = os.path.join(self.repo.path, "untracked")
  1862. with open(fullpath, "w") as f:
  1863. f.write("UNTRACKED")
  1864. # Try to move it (should fail)
  1865. self.assertRaises(
  1866. porcelain.Error, porcelain.mv, self.repo.path, "untracked", "tracked"
  1867. )
  1868. def test_mv_file_not_exists(self) -> None:
  1869. # Try to move a non-existent file
  1870. self.assertRaises(
  1871. porcelain.Error, porcelain.mv, self.repo.path, "nonexistent", "destination"
  1872. )
  1873. def test_mv_absolute_paths(self) -> None:
  1874. # Create a file
  1875. fullpath = os.path.join(self.repo.path, "foo")
  1876. with open(fullpath, "w") as f:
  1877. f.write("BAR")
  1878. # Add and commit the file
  1879. porcelain.add(self.repo.path, paths=[fullpath])
  1880. porcelain.commit(
  1881. repo=self.repo,
  1882. message=b"test",
  1883. author=b"test <email>",
  1884. committer=b"test <email>",
  1885. )
  1886. # Move using absolute paths
  1887. dest_path = os.path.join(self.repo.path, "bar")
  1888. porcelain.mv(self.repo.path, fullpath, dest_path)
  1889. # Verify file moved
  1890. self.assertFalse(os.path.exists(fullpath))
  1891. self.assertTrue(os.path.exists(dest_path))
  1892. def test_mv_from_different_directory(self) -> None:
  1893. # Create a subdirectory with a file
  1894. subdir = os.path.join(self.repo.path, "mydir")
  1895. os.makedirs(subdir)
  1896. fullpath = os.path.join(subdir, "myfile")
  1897. with open(fullpath, "w") as f:
  1898. f.write("BAR")
  1899. # Add and commit the file
  1900. porcelain.add(self.repo.path, paths=[fullpath])
  1901. porcelain.commit(
  1902. repo=self.repo,
  1903. message=b"test",
  1904. author=b"test <email>",
  1905. committer=b"test <email>",
  1906. )
  1907. # Change to a different directory and move the file
  1908. cwd = os.getcwd()
  1909. tempdir = tempfile.mkdtemp()
  1910. def cleanup():
  1911. os.chdir(cwd)
  1912. shutil.rmtree(tempdir)
  1913. self.addCleanup(cleanup)
  1914. os.chdir(tempdir)
  1915. # Move the file using relative path from repository root
  1916. porcelain.mv(self.repo.path, "mydir/myfile", "renamed")
  1917. # Verify file was moved
  1918. self.assertFalse(os.path.exists(fullpath))
  1919. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "renamed")))
  1920. class LogTests(PorcelainTestCase):
  1921. def test_simple(self) -> None:
  1922. c1, c2, c3 = build_commit_graph(
  1923. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1924. )
  1925. self.repo.refs[b"HEAD"] = c3.id
  1926. self.maxDiff = None
  1927. outstream = StringIO()
  1928. porcelain.log(self.repo.path, outstream=outstream)
  1929. self.assertEqual(
  1930. outstream.getvalue(),
  1931. """\
  1932. --------------------------------------------------
  1933. commit: 4a3b887baa9ecb2d054d2469b628aef84e2d74f0
  1934. merge: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  1935. Author: Test Author <test@nodomain.com>
  1936. Committer: Test Committer <test@nodomain.com>
  1937. Date: Fri Jan 01 2010 00:00:00 +0000
  1938. Commit 3
  1939. --------------------------------------------------
  1940. commit: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  1941. Author: Test Author <test@nodomain.com>
  1942. Committer: Test Committer <test@nodomain.com>
  1943. Date: Fri Jan 01 2010 00:00:00 +0000
  1944. Commit 2
  1945. --------------------------------------------------
  1946. commit: 11d3cf672a19366435c1983c7340b008ec6b8bf3
  1947. Author: Test Author <test@nodomain.com>
  1948. Committer: Test Committer <test@nodomain.com>
  1949. Date: Fri Jan 01 2010 00:00:00 +0000
  1950. Commit 1
  1951. """,
  1952. )
  1953. def test_max_entries(self) -> None:
  1954. c1, c2, c3 = build_commit_graph(
  1955. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1956. )
  1957. self.repo.refs[b"HEAD"] = c3.id
  1958. outstream = StringIO()
  1959. porcelain.log(self.repo.path, outstream=outstream, max_entries=1)
  1960. self.assertEqual(1, outstream.getvalue().count("-" * 50))
  1961. def test_no_revisions(self) -> None:
  1962. outstream = StringIO()
  1963. porcelain.log(self.repo.path, outstream=outstream)
  1964. self.assertEqual("", outstream.getvalue())
  1965. def test_empty_message(self) -> None:
  1966. c1 = make_commit(message="")
  1967. self.repo.object_store.add_object(c1)
  1968. self.repo.refs[b"HEAD"] = c1.id
  1969. outstream = StringIO()
  1970. porcelain.log(self.repo.path, outstream=outstream)
  1971. self.assertEqual(
  1972. outstream.getvalue(),
  1973. """\
  1974. --------------------------------------------------
  1975. commit: 4a7ad5552fad70647a81fb9a4a923ccefcca4b76
  1976. Author: Test Author <test@nodomain.com>
  1977. Committer: Test Committer <test@nodomain.com>
  1978. Date: Fri Jan 01 2010 00:00:00 +0000
  1979. """,
  1980. )
  1981. class ShowTests(PorcelainTestCase):
  1982. def test_nolist(self) -> None:
  1983. c1, c2, c3 = build_commit_graph(
  1984. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1985. )
  1986. self.repo.refs[b"HEAD"] = c3.id
  1987. outstream = StringIO()
  1988. porcelain.show(self.repo.path, objects=c3.id, outstream=outstream)
  1989. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  1990. def test_simple(self) -> None:
  1991. c1, c2, c3 = build_commit_graph(
  1992. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1993. )
  1994. self.repo.refs[b"HEAD"] = c3.id
  1995. outstream = StringIO()
  1996. porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream)
  1997. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  1998. def test_blob(self) -> None:
  1999. b = Blob.from_string(b"The Foo\n")
  2000. self.repo.object_store.add_object(b)
  2001. outstream = StringIO()
  2002. porcelain.show(self.repo.path, objects=[b.id], outstream=outstream)
  2003. self.assertEqual(outstream.getvalue(), "The Foo\n")
  2004. def test_commit_no_parent(self) -> None:
  2005. a = Blob.from_string(b"The Foo\n")
  2006. ta = Tree()
  2007. ta.add(b"somename", 0o100644, a.id)
  2008. ca = make_commit(tree=ta.id)
  2009. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2010. outstream = StringIO()
  2011. porcelain.show(self.repo.path, objects=[ca.id], outstream=outstream)
  2012. self.assertMultiLineEqual(
  2013. outstream.getvalue(),
  2014. """\
  2015. --------------------------------------------------
  2016. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2017. Author: Test Author <test@nodomain.com>
  2018. Committer: Test Committer <test@nodomain.com>
  2019. Date: Fri Jan 01 2010 00:00:00 +0000
  2020. Test message.
  2021. diff --git a/somename b/somename
  2022. new file mode 100644
  2023. index 0000000..ea5c7bf
  2024. --- /dev/null
  2025. +++ b/somename
  2026. @@ -0,0 +1 @@
  2027. +The Foo
  2028. """,
  2029. )
  2030. def test_tag(self) -> None:
  2031. a = Blob.from_string(b"The Foo\n")
  2032. ta = Tree()
  2033. ta.add(b"somename", 0o100644, a.id)
  2034. ca = make_commit(tree=ta.id)
  2035. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2036. porcelain.tag_create(
  2037. self.repo.path,
  2038. b"tryme",
  2039. b"foo <foo@bar.com>",
  2040. b"bar",
  2041. annotated=True,
  2042. objectish=ca.id,
  2043. tag_time=1552854211,
  2044. tag_timezone=0,
  2045. )
  2046. outstream = StringIO()
  2047. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2048. self.maxDiff = None
  2049. self.assertMultiLineEqual(
  2050. outstream.getvalue(),
  2051. """\
  2052. Tagger: foo <foo@bar.com>
  2053. Date: Sun Mar 17 2019 20:23:31 +0000
  2054. bar
  2055. --------------------------------------------------
  2056. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2057. Author: Test Author <test@nodomain.com>
  2058. Committer: Test Committer <test@nodomain.com>
  2059. Date: Fri Jan 01 2010 00:00:00 +0000
  2060. Test message.
  2061. diff --git a/somename b/somename
  2062. new file mode 100644
  2063. index 0000000..ea5c7bf
  2064. --- /dev/null
  2065. +++ b/somename
  2066. @@ -0,0 +1 @@
  2067. +The Foo
  2068. """,
  2069. )
  2070. def test_tag_unicode(self) -> None:
  2071. a = Blob.from_string(b"The Foo\n")
  2072. ta = Tree()
  2073. ta.add(b"somename", 0o100644, a.id)
  2074. ca = make_commit(tree=ta.id)
  2075. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  2076. porcelain.tag_create(
  2077. self.repo.path,
  2078. "tryme",
  2079. "foo <foo@bar.com>",
  2080. "bar",
  2081. annotated=True,
  2082. objectish=ca.id,
  2083. tag_time=1552854211,
  2084. tag_timezone=0,
  2085. )
  2086. outstream = StringIO()
  2087. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  2088. self.maxDiff = None
  2089. self.assertMultiLineEqual(
  2090. outstream.getvalue(),
  2091. """\
  2092. Tagger: foo <foo@bar.com>
  2093. Date: Sun Mar 17 2019 20:23:31 +0000
  2094. bar
  2095. --------------------------------------------------
  2096. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  2097. Author: Test Author <test@nodomain.com>
  2098. Committer: Test Committer <test@nodomain.com>
  2099. Date: Fri Jan 01 2010 00:00:00 +0000
  2100. Test message.
  2101. diff --git a/somename b/somename
  2102. new file mode 100644
  2103. index 0000000..ea5c7bf
  2104. --- /dev/null
  2105. +++ b/somename
  2106. @@ -0,0 +1 @@
  2107. +The Foo
  2108. """,
  2109. )
  2110. def test_commit_with_change(self) -> None:
  2111. a = Blob.from_string(b"The Foo\n")
  2112. ta = Tree()
  2113. ta.add(b"somename", 0o100644, a.id)
  2114. ca = make_commit(tree=ta.id)
  2115. b = Blob.from_string(b"The Bar\n")
  2116. tb = Tree()
  2117. tb.add(b"somename", 0o100644, b.id)
  2118. cb = make_commit(tree=tb.id, parents=[ca.id])
  2119. self.repo.object_store.add_objects(
  2120. [
  2121. (a, None),
  2122. (b, None),
  2123. (ta, None),
  2124. (tb, None),
  2125. (ca, None),
  2126. (cb, None),
  2127. ]
  2128. )
  2129. outstream = StringIO()
  2130. porcelain.show(self.repo.path, objects=[cb.id], outstream=outstream)
  2131. self.assertMultiLineEqual(
  2132. outstream.getvalue(),
  2133. """\
  2134. --------------------------------------------------
  2135. commit: 2c6b6c9cb72c130956657e1fdae58e5b103744fa
  2136. Author: Test Author <test@nodomain.com>
  2137. Committer: Test Committer <test@nodomain.com>
  2138. Date: Fri Jan 01 2010 00:00:00 +0000
  2139. Test message.
  2140. diff --git a/somename b/somename
  2141. index ea5c7bf..fd38bcb 100644
  2142. --- a/somename
  2143. +++ b/somename
  2144. @@ -1 +1 @@
  2145. -The Foo
  2146. +The Bar
  2147. """,
  2148. )
  2149. class FormatPatchTests(PorcelainTestCase):
  2150. def test_format_patch_single_commit(self) -> None:
  2151. # Create initial commit
  2152. tree1 = Tree()
  2153. c1 = make_commit(
  2154. tree=tree1,
  2155. message=b"Initial commit",
  2156. )
  2157. self.repo.object_store.add_objects([(tree1, None), (c1, None)])
  2158. # Create second commit
  2159. b = Blob.from_string(b"modified")
  2160. tree = Tree()
  2161. tree.add(b"test.txt", 0o100644, b.id)
  2162. c2 = make_commit(
  2163. tree=tree,
  2164. parents=[c1.id],
  2165. message=b"Add test.txt",
  2166. )
  2167. self.repo.object_store.add_objects([(b, None), (tree, None), (c2, None)])
  2168. self.repo[b"HEAD"] = c2.id
  2169. # Generate patch for single commit
  2170. with tempfile.TemporaryDirectory() as tmpdir:
  2171. patches = porcelain.format_patch(
  2172. self.repo.path,
  2173. committish=c2.id,
  2174. outdir=tmpdir,
  2175. )
  2176. self.assertEqual(len(patches), 1)
  2177. self.assertTrue(patches[0].endswith("-Add-test.txt.patch"))
  2178. # Verify patch content
  2179. with open(patches[0], "rb") as f:
  2180. content = f.read()
  2181. self.assertIn(b"Subject: [PATCH 1/1] Add test.txt", content)
  2182. self.assertIn(b"+modified", content)
  2183. def test_format_patch_multiple_commits(self) -> None:
  2184. # Create commit chain
  2185. commits = []
  2186. for i in range(3):
  2187. blob = Blob.from_string(f"content {i}".encode())
  2188. tree = Tree()
  2189. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  2190. parents = [commits[-1].id] if commits else []
  2191. commit = make_commit(
  2192. tree=tree,
  2193. parents=parents,
  2194. message=f"Commit {i}".encode(),
  2195. )
  2196. self.repo.object_store.add_objects(
  2197. [(blob, None), (tree, None), (commit, None)]
  2198. )
  2199. commits.append(commit)
  2200. self.repo[b"HEAD"] = commits[-1].id
  2201. # Test generating last 2 commits
  2202. with tempfile.TemporaryDirectory() as tmpdir:
  2203. patches = porcelain.format_patch(
  2204. self.repo.path,
  2205. n=2,
  2206. outdir=tmpdir,
  2207. )
  2208. self.assertEqual(len(patches), 2)
  2209. self.assertTrue(patches[0].endswith("-Commit-1.patch"))
  2210. self.assertTrue(patches[1].endswith("-Commit-2.patch"))
  2211. # Check patch numbering
  2212. with open(patches[0], "rb") as f:
  2213. self.assertIn(b"Subject: [PATCH 1/2] Commit 1", f.read())
  2214. with open(patches[1], "rb") as f:
  2215. self.assertIn(b"Subject: [PATCH 2/2] Commit 2", f.read())
  2216. def test_format_patch_range(self) -> None:
  2217. # Create commit chain
  2218. c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 2]])
  2219. self.repo[b"HEAD"] = c3.id
  2220. # Test commit range
  2221. with tempfile.TemporaryDirectory() as tmpdir:
  2222. patches = porcelain.format_patch(
  2223. self.repo.path,
  2224. committish=(c1.id, c3.id),
  2225. outdir=tmpdir,
  2226. )
  2227. # Should include c2 and c3
  2228. self.assertEqual(len(patches), 2)
  2229. def test_format_patch_stdout(self) -> None:
  2230. # Create a commit
  2231. blob = Blob.from_string(b"test content")
  2232. tree = Tree()
  2233. tree.add(b"test.txt", 0o100644, blob.id)
  2234. commit = make_commit(
  2235. tree=tree,
  2236. message=b"Test commit",
  2237. )
  2238. self.repo.object_store.add_objects([(blob, None), (tree, None), (commit, None)])
  2239. self.repo[b"HEAD"] = commit.id
  2240. # Test stdout output
  2241. outstream = BytesIO()
  2242. patches = porcelain.format_patch(
  2243. self.repo.path,
  2244. committish=commit.id,
  2245. stdout=True,
  2246. outstream=outstream,
  2247. )
  2248. # Should return empty list when writing to stdout
  2249. self.assertEqual(patches, [])
  2250. # Check stdout content
  2251. outstream.seek(0)
  2252. content = outstream.read()
  2253. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  2254. self.assertIn(b"diff --git", content)
  2255. def test_format_patch_no_commits(self) -> None:
  2256. # Test with a new repository with no commits
  2257. # Just remove HEAD to simulate empty repo
  2258. patches = porcelain.format_patch(
  2259. self.repo.path,
  2260. n=5,
  2261. )
  2262. self.assertEqual(patches, [])
  2263. class SymbolicRefTests(PorcelainTestCase):
  2264. def test_set_wrong_symbolic_ref(self) -> None:
  2265. c1, c2, c3 = build_commit_graph(
  2266. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2267. )
  2268. self.repo.refs[b"HEAD"] = c3.id
  2269. self.assertRaises(
  2270. porcelain.Error, porcelain.symbolic_ref, self.repo.path, b"foobar"
  2271. )
  2272. def test_set_force_wrong_symbolic_ref(self) -> None:
  2273. c1, c2, c3 = build_commit_graph(
  2274. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2275. )
  2276. self.repo.refs[b"HEAD"] = c3.id
  2277. porcelain.symbolic_ref(self.repo.path, b"force_foobar", force=True)
  2278. # test if we actually changed the file
  2279. with self.repo.get_named_file("HEAD") as f:
  2280. new_ref = f.read()
  2281. self.assertEqual(new_ref, b"ref: refs/heads/force_foobar\n")
  2282. def test_set_symbolic_ref(self) -> None:
  2283. c1, c2, c3 = build_commit_graph(
  2284. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2285. )
  2286. self.repo.refs[b"HEAD"] = c3.id
  2287. porcelain.symbolic_ref(self.repo.path, b"master")
  2288. def test_set_symbolic_ref_other_than_master(self) -> None:
  2289. c1, c2, c3 = build_commit_graph(
  2290. self.repo.object_store,
  2291. [[1], [2, 1], [3, 1, 2]],
  2292. attrs=dict(refs="develop"),
  2293. )
  2294. self.repo.refs[b"HEAD"] = c3.id
  2295. self.repo.refs[b"refs/heads/develop"] = c3.id
  2296. porcelain.symbolic_ref(self.repo.path, b"develop")
  2297. # test if we actually changed the file
  2298. with self.repo.get_named_file("HEAD") as f:
  2299. new_ref = f.read()
  2300. self.assertEqual(new_ref, b"ref: refs/heads/develop\n")
  2301. class DiffTreeTests(PorcelainTestCase):
  2302. def test_empty(self) -> None:
  2303. c1, c2, c3 = build_commit_graph(
  2304. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2305. )
  2306. self.repo.refs[b"HEAD"] = c3.id
  2307. outstream = BytesIO()
  2308. porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream)
  2309. self.assertEqual(outstream.getvalue(), b"")
  2310. class DiffTests(PorcelainTestCase):
  2311. def test_diff_uncommitted_stage(self) -> None:
  2312. # Test diff in repository with no commits yet
  2313. fullpath = os.path.join(self.repo.path, "test.txt")
  2314. with open(fullpath, "w") as f:
  2315. f.write("Hello, world!\n")
  2316. porcelain.add(self.repo.path, paths=["test.txt"])
  2317. outstream = BytesIO()
  2318. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2319. diff_output = outstream.getvalue()
  2320. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2321. self.assertIn(b"new file mode", diff_output)
  2322. self.assertIn(b"+Hello, world!", diff_output)
  2323. def test_diff_uncommitted_working_tree(self) -> None:
  2324. # Test unstaged changes in repository with no commits
  2325. fullpath = os.path.join(self.repo.path, "test.txt")
  2326. with open(fullpath, "w") as f:
  2327. f.write("Hello, world!\n")
  2328. porcelain.add(self.repo.path, paths=["test.txt"])
  2329. # Modify file in working tree
  2330. with open(fullpath, "w") as f:
  2331. f.write("Hello, world!\nNew line\n")
  2332. outstream = BytesIO()
  2333. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2334. diff_output = outstream.getvalue()
  2335. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2336. self.assertIn(b"+New line", diff_output)
  2337. def test_diff_with_commits_staged(self) -> None:
  2338. # Test staged changes with existing commits
  2339. fullpath = os.path.join(self.repo.path, "test.txt")
  2340. with open(fullpath, "w") as f:
  2341. f.write("Initial content\n")
  2342. porcelain.add(self.repo.path, paths=["test.txt"])
  2343. porcelain.commit(self.repo.path, message=b"Initial commit")
  2344. # Modify and stage
  2345. with open(fullpath, "w") as f:
  2346. f.write("Initial content\nModified\n")
  2347. porcelain.add(self.repo.path, paths=["test.txt"])
  2348. outstream = BytesIO()
  2349. porcelain.diff(self.repo.path, staged=True, outstream=outstream)
  2350. diff_output = outstream.getvalue()
  2351. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2352. self.assertIn(b"+Modified", diff_output)
  2353. def test_diff_with_commits_unstaged(self) -> None:
  2354. # Test unstaged changes with existing commits
  2355. fullpath = os.path.join(self.repo.path, "test.txt")
  2356. with open(fullpath, "w") as f:
  2357. f.write("Initial content\n")
  2358. porcelain.add(self.repo.path, paths=["test.txt"])
  2359. porcelain.commit(self.repo.path, message=b"Initial commit")
  2360. # Modify without staging
  2361. with open(fullpath, "w") as f:
  2362. f.write("Initial content\nModified\n")
  2363. outstream = BytesIO()
  2364. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2365. diff_output = outstream.getvalue()
  2366. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2367. self.assertIn(b"+Modified", diff_output)
  2368. def test_diff_file_deletion(self) -> None:
  2369. # Test showing file deletion
  2370. fullpath = os.path.join(self.repo.path, "test.txt")
  2371. with open(fullpath, "w") as f:
  2372. f.write("Content to delete\n")
  2373. porcelain.add(self.repo.path, paths=["test.txt"])
  2374. porcelain.commit(self.repo.path, message=b"Add file")
  2375. # Delete file
  2376. os.unlink(fullpath)
  2377. outstream = BytesIO()
  2378. porcelain.diff(self.repo.path, staged=False, outstream=outstream)
  2379. diff_output = outstream.getvalue()
  2380. self.assertIn(b"diff --git a/test.txt b/test.txt", diff_output)
  2381. self.assertIn(b"deleted file mode", diff_output)
  2382. self.assertIn(b"-Content to delete", diff_output)
  2383. def test_diff_with_paths(self) -> None:
  2384. # Test diff with specific paths
  2385. # Create two files
  2386. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2387. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2388. with open(fullpath1, "w") as f:
  2389. f.write("File 1 content\n")
  2390. with open(fullpath2, "w") as f:
  2391. f.write("File 2 content\n")
  2392. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2393. porcelain.commit(self.repo.path, message=b"Add two files")
  2394. # Modify both files
  2395. with open(fullpath1, "w") as f:
  2396. f.write("File 1 modified\n")
  2397. with open(fullpath2, "w") as f:
  2398. f.write("File 2 modified\n")
  2399. # Test diff with specific path
  2400. outstream = BytesIO()
  2401. porcelain.diff(self.repo.path, paths=["file1.txt"], outstream=outstream)
  2402. diff_output = outstream.getvalue()
  2403. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2404. self.assertIn(b"-File 1 content", diff_output)
  2405. self.assertIn(b"+File 1 modified", diff_output)
  2406. # file2.txt should not appear in diff
  2407. self.assertNotIn(b"file2.txt", diff_output)
  2408. def test_diff_with_paths_multiple(self) -> None:
  2409. # Test diff with multiple paths
  2410. # Create three files
  2411. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2412. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2413. fullpath3 = os.path.join(self.repo.path, "file3.txt")
  2414. with open(fullpath1, "w") as f:
  2415. f.write("File 1 content\n")
  2416. with open(fullpath2, "w") as f:
  2417. f.write("File 2 content\n")
  2418. with open(fullpath3, "w") as f:
  2419. f.write("File 3 content\n")
  2420. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt", "file3.txt"])
  2421. porcelain.commit(self.repo.path, message=b"Add three files")
  2422. # Modify all files
  2423. with open(fullpath1, "w") as f:
  2424. f.write("File 1 modified\n")
  2425. with open(fullpath2, "w") as f:
  2426. f.write("File 2 modified\n")
  2427. with open(fullpath3, "w") as f:
  2428. f.write("File 3 modified\n")
  2429. # Test diff with two specific paths
  2430. outstream = BytesIO()
  2431. porcelain.diff(
  2432. self.repo.path, paths=["file1.txt", "file3.txt"], outstream=outstream
  2433. )
  2434. diff_output = outstream.getvalue()
  2435. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2436. self.assertIn(b"diff --git a/file3.txt b/file3.txt", diff_output)
  2437. # file2.txt should not appear in diff
  2438. self.assertNotIn(b"file2.txt", diff_output)
  2439. def test_diff_with_paths_directory(self) -> None:
  2440. # Test diff with directory paths
  2441. # Create files in subdirectory
  2442. os.mkdir(os.path.join(self.repo.path, "subdir"))
  2443. fullpath1 = os.path.join(self.repo.path, "subdir", "file1.txt")
  2444. fullpath2 = os.path.join(self.repo.path, "subdir", "file2.txt")
  2445. fullpath3 = os.path.join(self.repo.path, "root.txt")
  2446. with open(fullpath1, "w") as f:
  2447. f.write("Subdir file 1\n")
  2448. with open(fullpath2, "w") as f:
  2449. f.write("Subdir file 2\n")
  2450. with open(fullpath3, "w") as f:
  2451. f.write("Root file\n")
  2452. porcelain.add(
  2453. self.repo.path, paths=["subdir/file1.txt", "subdir/file2.txt", "root.txt"]
  2454. )
  2455. porcelain.commit(self.repo.path, message=b"Add files in subdir")
  2456. # Modify all files
  2457. with open(fullpath1, "w") as f:
  2458. f.write("Subdir file 1 modified\n")
  2459. with open(fullpath2, "w") as f:
  2460. f.write("Subdir file 2 modified\n")
  2461. with open(fullpath3, "w") as f:
  2462. f.write("Root file modified\n")
  2463. # Test diff with directory path
  2464. outstream = BytesIO()
  2465. porcelain.diff(self.repo.path, paths=["subdir"], outstream=outstream)
  2466. diff_output = outstream.getvalue()
  2467. self.assertIn(b"subdir/file1.txt", diff_output)
  2468. self.assertIn(b"subdir/file2.txt", diff_output)
  2469. # root.txt should not appear in diff
  2470. self.assertNotIn(b"root.txt", diff_output)
  2471. def test_diff_staged_with_paths(self) -> None:
  2472. # Test staged diff with specific paths
  2473. # Create two files
  2474. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2475. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2476. with open(fullpath1, "w") as f:
  2477. f.write("File 1 content\n")
  2478. with open(fullpath2, "w") as f:
  2479. f.write("File 2 content\n")
  2480. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2481. porcelain.commit(self.repo.path, message=b"Add two files")
  2482. # Modify and stage both files
  2483. with open(fullpath1, "w") as f:
  2484. f.write("File 1 staged\n")
  2485. with open(fullpath2, "w") as f:
  2486. f.write("File 2 staged\n")
  2487. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2488. # Test staged diff with specific path
  2489. outstream = BytesIO()
  2490. porcelain.diff(
  2491. self.repo.path, staged=True, paths=["file1.txt"], outstream=outstream
  2492. )
  2493. diff_output = outstream.getvalue()
  2494. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2495. self.assertIn(b"-File 1 content", diff_output)
  2496. self.assertIn(b"+File 1 staged", diff_output)
  2497. # file2.txt should not appear in diff
  2498. self.assertNotIn(b"file2.txt", diff_output)
  2499. def test_diff_with_commit_and_paths(self) -> None:
  2500. # Test diff against specific commit with paths
  2501. # Create initial file
  2502. fullpath1 = os.path.join(self.repo.path, "file1.txt")
  2503. fullpath2 = os.path.join(self.repo.path, "file2.txt")
  2504. with open(fullpath1, "w") as f:
  2505. f.write("Initial content 1\n")
  2506. with open(fullpath2, "w") as f:
  2507. f.write("Initial content 2\n")
  2508. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2509. first_commit = porcelain.commit(self.repo.path, message=b"Initial commit")
  2510. # Make second commit
  2511. with open(fullpath1, "w") as f:
  2512. f.write("Second content 1\n")
  2513. with open(fullpath2, "w") as f:
  2514. f.write("Second content 2\n")
  2515. porcelain.add(self.repo.path, paths=["file1.txt", "file2.txt"])
  2516. porcelain.commit(self.repo.path, message=b"Second commit")
  2517. # Modify working tree
  2518. with open(fullpath1, "w") as f:
  2519. f.write("Working content 1\n")
  2520. with open(fullpath2, "w") as f:
  2521. f.write("Working content 2\n")
  2522. # Test diff against first commit with specific path
  2523. outstream = BytesIO()
  2524. porcelain.diff(
  2525. self.repo.path,
  2526. commit=first_commit,
  2527. paths=["file1.txt"],
  2528. outstream=outstream,
  2529. )
  2530. diff_output = outstream.getvalue()
  2531. self.assertIn(b"diff --git a/file1.txt b/file1.txt", diff_output)
  2532. self.assertIn(b"-Initial content 1", diff_output)
  2533. self.assertIn(b"+Working content 1", diff_output)
  2534. # file2.txt should not appear in diff
  2535. self.assertNotIn(b"file2.txt", diff_output)
  2536. class CommitTreeTests(PorcelainTestCase):
  2537. def test_simple(self) -> None:
  2538. c1, c2, c3 = build_commit_graph(
  2539. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2540. )
  2541. b = Blob()
  2542. b.data = b"foo the bar"
  2543. t = Tree()
  2544. t.add(b"somename", 0o100644, b.id)
  2545. self.repo.object_store.add_object(t)
  2546. self.repo.object_store.add_object(b)
  2547. sha = porcelain.commit_tree(
  2548. self.repo.path,
  2549. t.id,
  2550. message=b"Withcommit.",
  2551. author=b"Joe <joe@example.com>",
  2552. committer=b"Jane <jane@example.com>",
  2553. )
  2554. self.assertIsInstance(sha, bytes)
  2555. self.assertEqual(len(sha), 40)
  2556. class RevListTests(PorcelainTestCase):
  2557. def test_simple(self) -> None:
  2558. c1, c2, c3 = build_commit_graph(
  2559. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2560. )
  2561. outstream = BytesIO()
  2562. porcelain.rev_list(self.repo.path, [c3.id], outstream=outstream)
  2563. self.assertEqual(
  2564. c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue()
  2565. )
  2566. @skipIf(
  2567. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  2568. "gpgme not easily available or supported on Windows and PyPy",
  2569. )
  2570. class TagCreateSignTests(PorcelainGpgTestCase):
  2571. def test_default_key(self) -> None:
  2572. c1, c2, c3 = build_commit_graph(
  2573. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2574. )
  2575. self.repo.refs[b"HEAD"] = c3.id
  2576. cfg = self.repo.get_config()
  2577. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2578. self.import_default_key()
  2579. porcelain.tag_create(
  2580. self.repo.path,
  2581. b"tryme",
  2582. b"foo <foo@bar.com>",
  2583. b"bar",
  2584. annotated=True,
  2585. sign=True,
  2586. )
  2587. tags = self.repo.refs.as_dict(b"refs/tags")
  2588. self.assertEqual(list(tags.keys()), [b"tryme"])
  2589. tag = self.repo[b"refs/tags/tryme"]
  2590. self.assertIsInstance(tag, Tag)
  2591. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2592. self.assertEqual(b"bar\n", tag.message)
  2593. self.assertRecentTimestamp(tag.tag_time)
  2594. tag = self.repo[b"refs/tags/tryme"]
  2595. assert isinstance(tag, Tag)
  2596. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2597. tag.verify()
  2598. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2599. self.import_non_default_key()
  2600. self.assertRaises(
  2601. gpg.errors.MissingSignatures,
  2602. tag.verify,
  2603. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  2604. )
  2605. assert tag.signature is not None
  2606. tag._chunked_text = [b"bad data", tag.signature]
  2607. self.assertRaises(
  2608. gpg.errors.BadSignatures,
  2609. tag.verify,
  2610. )
  2611. def test_non_default_key(self) -> None:
  2612. c1, c2, c3 = build_commit_graph(
  2613. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2614. )
  2615. self.repo.refs[b"HEAD"] = c3.id
  2616. cfg = self.repo.get_config()
  2617. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2618. self.import_non_default_key()
  2619. porcelain.tag_create(
  2620. self.repo.path,
  2621. b"tryme",
  2622. b"foo <foo@bar.com>",
  2623. b"bar",
  2624. annotated=True,
  2625. sign=True,
  2626. )
  2627. tags = self.repo.refs.as_dict(b"refs/tags")
  2628. self.assertEqual(list(tags.keys()), [b"tryme"])
  2629. tag = self.repo[b"refs/tags/tryme"]
  2630. self.assertIsInstance(tag, Tag)
  2631. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2632. self.assertEqual(b"bar\n", tag.message)
  2633. self.assertRecentTimestamp(tag.tag_time)
  2634. tag = self.repo[b"refs/tags/tryme"]
  2635. assert isinstance(tag, Tag)
  2636. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  2637. tag.verify()
  2638. def test_sign_uses_config_signingkey(self) -> None:
  2639. """Test that sign=True uses user.signingKey from config."""
  2640. c1, c2, c3 = build_commit_graph(
  2641. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2642. )
  2643. self.repo.refs[b"HEAD"] = c3.id
  2644. # Set up user.signingKey in config
  2645. cfg = self.repo.get_config()
  2646. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2647. cfg.write_to_path()
  2648. self.import_default_key()
  2649. # Create tag with sign=True (should use signingKey from config)
  2650. porcelain.tag_create(
  2651. self.repo.path,
  2652. b"signed-tag",
  2653. b"foo <foo@bar.com>",
  2654. b"Tag with configured key",
  2655. annotated=True,
  2656. sign=True, # This should read user.signingKey from config
  2657. )
  2658. tags = self.repo.refs.as_dict(b"refs/tags")
  2659. self.assertEqual(list(tags.keys()), [b"signed-tag"])
  2660. tag = self.repo[b"refs/tags/signed-tag"]
  2661. self.assertIsInstance(tag, Tag)
  2662. # Verify the tag is signed with the configured key
  2663. tag.verify()
  2664. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2665. def test_tag_gpg_sign_config_enabled(self) -> None:
  2666. """Test that tag.gpgSign=true automatically signs tags."""
  2667. c1, c2, c3 = build_commit_graph(
  2668. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2669. )
  2670. self.repo.refs[b"HEAD"] = c3.id
  2671. # Set up user.signingKey and tag.gpgSign in config
  2672. cfg = self.repo.get_config()
  2673. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2674. cfg.set(("tag",), "gpgSign", True)
  2675. cfg.write_to_path()
  2676. self.import_default_key()
  2677. # Create tag without explicit sign parameter (should auto-sign due to config)
  2678. porcelain.tag_create(
  2679. self.repo.path,
  2680. b"auto-signed-tag",
  2681. b"foo <foo@bar.com>",
  2682. b"Auto-signed tag",
  2683. annotated=True,
  2684. # No sign parameter - should use tag.gpgSign config
  2685. )
  2686. tags = self.repo.refs.as_dict(b"refs/tags")
  2687. self.assertEqual(list(tags.keys()), [b"auto-signed-tag"])
  2688. tag = self.repo[b"refs/tags/auto-signed-tag"]
  2689. self.assertIsInstance(tag, Tag)
  2690. # Verify the tag is signed due to config
  2691. tag.verify()
  2692. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2693. def test_tag_gpg_sign_config_disabled(self) -> None:
  2694. """Test that tag.gpgSign=false does not sign tags."""
  2695. c1, c2, c3 = build_commit_graph(
  2696. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2697. )
  2698. self.repo.refs[b"HEAD"] = c3.id
  2699. # Set up user.signingKey and tag.gpgSign=false in config
  2700. cfg = self.repo.get_config()
  2701. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2702. cfg.set(("tag",), "gpgSign", False)
  2703. cfg.write_to_path()
  2704. self.import_default_key()
  2705. # Create tag without explicit sign parameter (should not sign)
  2706. porcelain.tag_create(
  2707. self.repo.path,
  2708. b"unsigned-tag",
  2709. b"foo <foo@bar.com>",
  2710. b"Unsigned tag",
  2711. annotated=True,
  2712. # No sign parameter - should use tag.gpgSign=false config
  2713. )
  2714. tags = self.repo.refs.as_dict(b"refs/tags")
  2715. self.assertEqual(list(tags.keys()), [b"unsigned-tag"])
  2716. tag = self.repo[b"refs/tags/unsigned-tag"]
  2717. self.assertIsInstance(tag, Tag)
  2718. # Verify the tag is not signed
  2719. self.assertIsNone(tag._signature)
  2720. def test_tag_gpg_sign_config_no_signing_key(self) -> None:
  2721. """Test that tag.gpgSign=true works without user.signingKey (uses default)."""
  2722. c1, c2, c3 = build_commit_graph(
  2723. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2724. )
  2725. self.repo.refs[b"HEAD"] = c3.id
  2726. # Set up tag.gpgSign but no user.signingKey
  2727. cfg = self.repo.get_config()
  2728. cfg.set(("tag",), "gpgSign", True)
  2729. cfg.write_to_path()
  2730. self.import_default_key()
  2731. # Create tag without explicit sign parameter (should auto-sign with default key)
  2732. porcelain.tag_create(
  2733. self.repo.path,
  2734. b"default-signed-tag",
  2735. b"foo <foo@bar.com>",
  2736. b"Default signed tag",
  2737. annotated=True,
  2738. # No sign parameter - should use tag.gpgSign config with default key
  2739. )
  2740. tags = self.repo.refs.as_dict(b"refs/tags")
  2741. self.assertEqual(list(tags.keys()), [b"default-signed-tag"])
  2742. tag = self.repo[b"refs/tags/default-signed-tag"]
  2743. self.assertIsInstance(tag, Tag)
  2744. # Verify the tag is signed with default key
  2745. tag.verify()
  2746. def test_explicit_sign_overrides_config(self) -> None:
  2747. """Test that explicit sign parameter overrides tag.gpgSign config."""
  2748. c1, c2, c3 = build_commit_graph(
  2749. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2750. )
  2751. self.repo.refs[b"HEAD"] = c3.id
  2752. # Set up tag.gpgSign=false but explicitly pass sign=True
  2753. cfg = self.repo.get_config()
  2754. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2755. cfg.set(("tag",), "gpgSign", False)
  2756. cfg.write_to_path()
  2757. self.import_default_key()
  2758. # Create tag with explicit sign=True (should override config)
  2759. porcelain.tag_create(
  2760. self.repo.path,
  2761. b"explicit-signed-tag",
  2762. b"foo <foo@bar.com>",
  2763. b"Explicitly signed tag",
  2764. annotated=True,
  2765. sign=True, # This should override tag.gpgSign=false
  2766. )
  2767. tags = self.repo.refs.as_dict(b"refs/tags")
  2768. self.assertEqual(list(tags.keys()), [b"explicit-signed-tag"])
  2769. tag = self.repo[b"refs/tags/explicit-signed-tag"]
  2770. self.assertIsInstance(tag, Tag)
  2771. # Verify the tag is signed despite config=false
  2772. tag.verify()
  2773. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  2774. def test_explicit_false_disables_tag_signing(self) -> None:
  2775. """Test that explicit sign=False disables signing even with config=true."""
  2776. c1, c2, c3 = build_commit_graph(
  2777. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2778. )
  2779. self.repo.refs[b"HEAD"] = c3.id
  2780. # Set up tag.gpgSign=true but explicitly pass sign=False
  2781. cfg = self.repo.get_config()
  2782. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  2783. cfg.set(("tag",), "gpgSign", True)
  2784. cfg.write_to_path()
  2785. self.import_default_key()
  2786. # Create tag with explicit sign=False (should disable signing)
  2787. porcelain.tag_create(
  2788. self.repo.path,
  2789. b"explicit-unsigned-tag",
  2790. b"foo <foo@bar.com>",
  2791. b"Explicitly unsigned tag",
  2792. annotated=True,
  2793. sign=False, # This should override tag.gpgSign=true
  2794. )
  2795. tags = self.repo.refs.as_dict(b"refs/tags")
  2796. self.assertEqual(list(tags.keys()), [b"explicit-unsigned-tag"])
  2797. tag = self.repo[b"refs/tags/explicit-unsigned-tag"]
  2798. self.assertIsInstance(tag, Tag)
  2799. # Verify the tag is NOT signed despite config=true
  2800. self.assertIsNone(tag._signature)
  2801. class TagCreateTests(PorcelainTestCase):
  2802. def test_annotated(self) -> None:
  2803. c1, c2, c3 = build_commit_graph(
  2804. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2805. )
  2806. self.repo.refs[b"HEAD"] = c3.id
  2807. porcelain.tag_create(
  2808. self.repo.path,
  2809. b"tryme",
  2810. b"foo <foo@bar.com>",
  2811. b"bar",
  2812. annotated=True,
  2813. )
  2814. tags = self.repo.refs.as_dict(b"refs/tags")
  2815. self.assertEqual(list(tags.keys()), [b"tryme"])
  2816. tag = self.repo[b"refs/tags/tryme"]
  2817. self.assertIsInstance(tag, Tag)
  2818. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  2819. self.assertEqual(b"bar\n", tag.message)
  2820. self.assertRecentTimestamp(tag.tag_time)
  2821. def test_unannotated(self) -> None:
  2822. c1, c2, c3 = build_commit_graph(
  2823. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2824. )
  2825. self.repo.refs[b"HEAD"] = c3.id
  2826. porcelain.tag_create(self.repo.path, b"tryme", annotated=False)
  2827. tags = self.repo.refs.as_dict(b"refs/tags")
  2828. self.assertEqual(list(tags.keys()), [b"tryme"])
  2829. self.repo[b"refs/tags/tryme"]
  2830. self.assertEqual(list(tags.values()), [self.repo.head()])
  2831. def test_unannotated_unicode(self) -> None:
  2832. c1, c2, c3 = build_commit_graph(
  2833. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  2834. )
  2835. self.repo.refs[b"HEAD"] = c3.id
  2836. porcelain.tag_create(self.repo.path, "tryme", annotated=False)
  2837. tags = self.repo.refs.as_dict(b"refs/tags")
  2838. self.assertEqual(list(tags.keys()), [b"tryme"])
  2839. self.repo[b"refs/tags/tryme"]
  2840. self.assertEqual(list(tags.values()), [self.repo.head()])
  2841. class TagListTests(PorcelainTestCase):
  2842. def test_empty(self) -> None:
  2843. tags = porcelain.tag_list(self.repo.path)
  2844. self.assertEqual([], tags)
  2845. def test_simple(self) -> None:
  2846. self.repo.refs[b"refs/tags/foo"] = b"aa" * 20
  2847. self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20
  2848. tags = porcelain.tag_list(self.repo.path)
  2849. self.assertEqual([b"bar/bla", b"foo"], tags)
  2850. class TagDeleteTests(PorcelainTestCase):
  2851. def test_simple(self) -> None:
  2852. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  2853. self.repo[b"HEAD"] = c1.id
  2854. porcelain.tag_create(self.repo, b"foo")
  2855. self.assertIn(b"foo", porcelain.tag_list(self.repo))
  2856. porcelain.tag_delete(self.repo, b"foo")
  2857. self.assertNotIn(b"foo", porcelain.tag_list(self.repo))
  2858. class ResetTests(PorcelainTestCase):
  2859. def test_hard_head(self) -> None:
  2860. fullpath = os.path.join(self.repo.path, "foo")
  2861. with open(fullpath, "w") as f:
  2862. f.write("BAR")
  2863. porcelain.add(self.repo.path, paths=[fullpath])
  2864. porcelain.commit(
  2865. self.repo.path,
  2866. message=b"Some message",
  2867. committer=b"Jane <jane@example.com>",
  2868. author=b"John <john@example.com>",
  2869. )
  2870. with open(os.path.join(self.repo.path, "foo"), "wb") as f:
  2871. f.write(b"OOH")
  2872. porcelain.reset(self.repo, "hard", b"HEAD")
  2873. index = self.repo.open_index()
  2874. changes = list(
  2875. tree_changes(
  2876. self.repo.object_store,
  2877. index.commit(self.repo.object_store),
  2878. self.repo[b"HEAD"].tree,
  2879. )
  2880. )
  2881. self.assertEqual([], changes)
  2882. def test_hard_commit(self) -> None:
  2883. fullpath = os.path.join(self.repo.path, "foo")
  2884. with open(fullpath, "w") as f:
  2885. f.write("BAR")
  2886. porcelain.add(self.repo.path, paths=[fullpath])
  2887. sha = porcelain.commit(
  2888. self.repo.path,
  2889. message=b"Some message",
  2890. committer=b"Jane <jane@example.com>",
  2891. author=b"John <john@example.com>",
  2892. )
  2893. with open(fullpath, "wb") as f:
  2894. f.write(b"BAZ")
  2895. porcelain.add(self.repo.path, paths=[fullpath])
  2896. porcelain.commit(
  2897. self.repo.path,
  2898. message=b"Some other message",
  2899. committer=b"Jane <jane@example.com>",
  2900. author=b"John <john@example.com>",
  2901. )
  2902. porcelain.reset(self.repo, "hard", sha)
  2903. index = self.repo.open_index()
  2904. changes = list(
  2905. tree_changes(
  2906. self.repo.object_store,
  2907. index.commit(self.repo.object_store),
  2908. self.repo[sha].tree,
  2909. )
  2910. )
  2911. self.assertEqual([], changes)
  2912. def test_hard_commit_short_hash(self) -> None:
  2913. fullpath = os.path.join(self.repo.path, "foo")
  2914. with open(fullpath, "w") as f:
  2915. f.write("BAR")
  2916. porcelain.add(self.repo.path, paths=[fullpath])
  2917. sha = porcelain.commit(
  2918. self.repo.path,
  2919. message=b"Some message",
  2920. committer=b"Jane <jane@example.com>",
  2921. author=b"John <john@example.com>",
  2922. )
  2923. with open(fullpath, "wb") as f:
  2924. f.write(b"BAZ")
  2925. porcelain.add(self.repo.path, paths=[fullpath])
  2926. porcelain.commit(
  2927. self.repo.path,
  2928. message=b"Some other message",
  2929. committer=b"Jane <jane@example.com>",
  2930. author=b"John <john@example.com>",
  2931. )
  2932. # Test with short hash (7 characters)
  2933. short_sha = sha[:7].decode("ascii")
  2934. porcelain.reset(self.repo, "hard", short_sha)
  2935. index = self.repo.open_index()
  2936. changes = list(
  2937. tree_changes(
  2938. self.repo.object_store,
  2939. index.commit(self.repo.object_store),
  2940. self.repo[sha].tree,
  2941. )
  2942. )
  2943. self.assertEqual([], changes)
  2944. def test_hard_deletes_untracked_files(self) -> None:
  2945. """Test that reset --hard deletes files that don't exist in target tree."""
  2946. # Create and commit a file
  2947. fullpath = os.path.join(self.repo.path, "foo")
  2948. with open(fullpath, "w") as f:
  2949. f.write("BAR")
  2950. porcelain.add(self.repo.path, paths=[fullpath])
  2951. sha1 = porcelain.commit(
  2952. self.repo.path,
  2953. message=b"First commit",
  2954. committer=b"Jane <jane@example.com>",
  2955. author=b"John <john@example.com>",
  2956. )
  2957. # Create another file and commit
  2958. fullpath2 = os.path.join(self.repo.path, "bar")
  2959. with open(fullpath2, "w") as f:
  2960. f.write("BAZ")
  2961. porcelain.add(self.repo.path, paths=[fullpath2])
  2962. porcelain.commit(
  2963. self.repo.path,
  2964. message=b"Second commit",
  2965. committer=b"Jane <jane@example.com>",
  2966. author=b"John <john@example.com>",
  2967. )
  2968. # Reset hard to first commit - this should delete 'bar'
  2969. porcelain.reset(self.repo, "hard", sha1)
  2970. # Check that 'foo' still exists and 'bar' is deleted
  2971. self.assertTrue(os.path.exists(fullpath))
  2972. self.assertFalse(os.path.exists(fullpath2))
  2973. # Check index matches first commit
  2974. index = self.repo.open_index()
  2975. self.assertIn(b"foo", index)
  2976. self.assertNotIn(b"bar", index)
  2977. def test_hard_deletes_files_in_subdirs(self) -> None:
  2978. """Test that reset --hard deletes files in subdirectories."""
  2979. # Create and commit files in subdirectory
  2980. subdir = os.path.join(self.repo.path, "subdir")
  2981. os.makedirs(subdir)
  2982. file1 = os.path.join(subdir, "file1")
  2983. file2 = os.path.join(subdir, "file2")
  2984. with open(file1, "w") as f:
  2985. f.write("content1")
  2986. with open(file2, "w") as f:
  2987. f.write("content2")
  2988. porcelain.add(self.repo.path, paths=[file1, file2])
  2989. porcelain.commit(
  2990. self.repo.path,
  2991. message=b"First commit",
  2992. committer=b"Jane <jane@example.com>",
  2993. author=b"John <john@example.com>",
  2994. )
  2995. # Remove one file from subdirectory and commit
  2996. porcelain.rm(self.repo.path, paths=[file2])
  2997. sha2 = porcelain.commit(
  2998. self.repo.path,
  2999. message=b"Remove file2",
  3000. committer=b"Jane <jane@example.com>",
  3001. author=b"John <john@example.com>",
  3002. )
  3003. # Create file2 again (untracked)
  3004. with open(file2, "w") as f:
  3005. f.write("new content")
  3006. # Reset to commit that has file2 removed - should delete untracked file2
  3007. porcelain.reset(self.repo, "hard", sha2)
  3008. self.assertTrue(os.path.exists(file1))
  3009. self.assertFalse(os.path.exists(file2))
  3010. def test_hard_reset_to_remote_branch(self) -> None:
  3011. """Test reset --hard to remote branch deletes local files not in remote."""
  3012. # Create a file and commit
  3013. file1 = os.path.join(self.repo.path, "file1")
  3014. with open(file1, "w") as f:
  3015. f.write("content1")
  3016. porcelain.add(self.repo.path, paths=[file1])
  3017. sha1 = porcelain.commit(
  3018. self.repo.path,
  3019. message=b"Initial commit",
  3020. committer=b"Jane <jane@example.com>",
  3021. author=b"John <john@example.com>",
  3022. )
  3023. # Create a "remote" ref that doesn't have additional files
  3024. self.repo.refs[b"refs/remotes/origin/master"] = sha1
  3025. # Add another file locally and commit
  3026. file2 = os.path.join(self.repo.path, "file2")
  3027. with open(file2, "w") as f:
  3028. f.write("content2")
  3029. porcelain.add(self.repo.path, paths=[file2])
  3030. porcelain.commit(
  3031. self.repo.path,
  3032. message=b"Add file2",
  3033. committer=b"Jane <jane@example.com>",
  3034. author=b"John <john@example.com>",
  3035. )
  3036. # Both files should exist
  3037. self.assertTrue(os.path.exists(file1))
  3038. self.assertTrue(os.path.exists(file2))
  3039. # Reset to remote branch - should delete file2
  3040. porcelain.reset(self.repo, "hard", b"refs/remotes/origin/master")
  3041. # file1 should exist, file2 should be deleted
  3042. self.assertTrue(os.path.exists(file1))
  3043. self.assertFalse(os.path.exists(file2))
  3044. def test_mixed_reset(self) -> None:
  3045. # Create initial commit
  3046. fullpath = os.path.join(self.repo.path, "foo")
  3047. with open(fullpath, "w") as f:
  3048. f.write("BAR")
  3049. porcelain.add(self.repo.path, paths=[fullpath])
  3050. first_sha = porcelain.commit(
  3051. self.repo.path,
  3052. message=b"First commit",
  3053. committer=b"Jane <jane@example.com>",
  3054. author=b"John <john@example.com>",
  3055. )
  3056. # Make second commit with modified content
  3057. with open(fullpath, "w") as f:
  3058. f.write("BAZ")
  3059. porcelain.add(self.repo.path, paths=[fullpath])
  3060. porcelain.commit(
  3061. self.repo.path,
  3062. message=b"Second commit",
  3063. committer=b"Jane <jane@example.com>",
  3064. author=b"John <john@example.com>",
  3065. )
  3066. # Modify working tree without staging
  3067. with open(fullpath, "w") as f:
  3068. f.write("MODIFIED")
  3069. # Mixed reset to first commit
  3070. porcelain.reset(self.repo, "mixed", first_sha)
  3071. # Check that HEAD points to first commit
  3072. self.assertEqual(self.repo.head(), first_sha)
  3073. # Check that index matches first commit
  3074. index = self.repo.open_index()
  3075. changes = list(
  3076. tree_changes(
  3077. self.repo.object_store,
  3078. index.commit(self.repo.object_store),
  3079. self.repo[first_sha].tree,
  3080. )
  3081. )
  3082. self.assertEqual([], changes)
  3083. # Check that working tree is unchanged (still has "MODIFIED")
  3084. with open(fullpath) as f:
  3085. self.assertEqual(f.read(), "MODIFIED")
  3086. def test_soft_reset(self) -> None:
  3087. # Create initial commit
  3088. fullpath = os.path.join(self.repo.path, "foo")
  3089. with open(fullpath, "w") as f:
  3090. f.write("BAR")
  3091. porcelain.add(self.repo.path, paths=[fullpath])
  3092. first_sha = porcelain.commit(
  3093. self.repo.path,
  3094. message=b"First commit",
  3095. committer=b"Jane <jane@example.com>",
  3096. author=b"John <john@example.com>",
  3097. )
  3098. # Make second commit with modified content
  3099. with open(fullpath, "w") as f:
  3100. f.write("BAZ")
  3101. porcelain.add(self.repo.path, paths=[fullpath])
  3102. porcelain.commit(
  3103. self.repo.path,
  3104. message=b"Second commit",
  3105. committer=b"Jane <jane@example.com>",
  3106. author=b"John <john@example.com>",
  3107. )
  3108. # Stage a new change
  3109. with open(fullpath, "w") as f:
  3110. f.write("STAGED")
  3111. porcelain.add(self.repo.path, paths=[fullpath])
  3112. # Soft reset to first commit
  3113. porcelain.reset(self.repo, "soft", first_sha)
  3114. # Check that HEAD points to first commit
  3115. self.assertEqual(self.repo.head(), first_sha)
  3116. # Check that index still has the staged change (not reset)
  3117. index = self.repo.open_index()
  3118. # The index should still contain the staged content, not the first commit's content
  3119. self.assertIn(b"foo", index)
  3120. # Check that working tree is unchanged
  3121. with open(fullpath) as f:
  3122. self.assertEqual(f.read(), "STAGED")
  3123. class ResetFileTests(PorcelainTestCase):
  3124. def test_reset_modify_file_to_commit(self) -> None:
  3125. file = "foo"
  3126. full_path = os.path.join(self.repo.path, file)
  3127. with open(full_path, "w") as f:
  3128. f.write("hello")
  3129. porcelain.add(self.repo, paths=[full_path])
  3130. sha = porcelain.commit(
  3131. self.repo,
  3132. message=b"unitest",
  3133. committer=b"Jane <jane@example.com>",
  3134. author=b"John <john@example.com>",
  3135. )
  3136. with open(full_path, "a") as f:
  3137. f.write("something new")
  3138. porcelain.reset_file(self.repo, file, target=sha)
  3139. with open(full_path) as f:
  3140. self.assertEqual("hello", f.read())
  3141. def test_reset_remove_file_to_commit(self) -> None:
  3142. file = "foo"
  3143. full_path = os.path.join(self.repo.path, file)
  3144. with open(full_path, "w") as f:
  3145. f.write("hello")
  3146. porcelain.add(self.repo, paths=[full_path])
  3147. sha = porcelain.commit(
  3148. self.repo,
  3149. message=b"unitest",
  3150. committer=b"Jane <jane@example.com>",
  3151. author=b"John <john@example.com>",
  3152. )
  3153. os.remove(full_path)
  3154. porcelain.reset_file(self.repo, file, target=sha)
  3155. with open(full_path) as f:
  3156. self.assertEqual("hello", f.read())
  3157. def test_resetfile_with_dir(self) -> None:
  3158. os.mkdir(os.path.join(self.repo.path, "new_dir"))
  3159. full_path = os.path.join(self.repo.path, "new_dir", "foo")
  3160. with open(full_path, "w") as f:
  3161. f.write("hello")
  3162. porcelain.add(self.repo, paths=[full_path])
  3163. sha = porcelain.commit(
  3164. self.repo,
  3165. message=b"unitest",
  3166. committer=b"Jane <jane@example.com>",
  3167. author=b"John <john@example.com>",
  3168. )
  3169. with open(full_path, "a") as f:
  3170. f.write("something new")
  3171. porcelain.commit(
  3172. self.repo,
  3173. message=b"unitest 2",
  3174. committer=b"Jane <jane@example.com>",
  3175. author=b"John <john@example.com>",
  3176. )
  3177. porcelain.reset_file(self.repo, os.path.join("new_dir", "foo"), target=sha)
  3178. with open(full_path) as f:
  3179. self.assertEqual("hello", f.read())
  3180. def _commit_file_with_content(repo, filename, content):
  3181. file_path = os.path.join(repo.path, filename)
  3182. with open(file_path, "w") as f:
  3183. f.write(content)
  3184. porcelain.add(repo, paths=[file_path])
  3185. sha = porcelain.commit(
  3186. repo,
  3187. message=b"add " + filename.encode(),
  3188. committer=b"Jane <jane@example.com>",
  3189. author=b"John <john@example.com>",
  3190. )
  3191. return sha, file_path
  3192. class RevertTests(PorcelainTestCase):
  3193. def test_revert_simple(self) -> None:
  3194. # Create initial commit
  3195. fullpath = os.path.join(self.repo.path, "foo")
  3196. with open(fullpath, "w") as f:
  3197. f.write("initial content\n")
  3198. porcelain.add(self.repo.path, paths=[fullpath])
  3199. porcelain.commit(
  3200. self.repo.path,
  3201. message=b"Initial commit",
  3202. committer=b"Jane <jane@example.com>",
  3203. author=b"John <john@example.com>",
  3204. )
  3205. # Make a change
  3206. with open(fullpath, "w") as f:
  3207. f.write("modified content\n")
  3208. porcelain.add(self.repo.path, paths=[fullpath])
  3209. change_sha = porcelain.commit(
  3210. self.repo.path,
  3211. message=b"Change content",
  3212. committer=b"Jane <jane@example.com>",
  3213. author=b"John <john@example.com>",
  3214. )
  3215. # Revert the change
  3216. revert_sha = porcelain.revert(self.repo.path, commits=[change_sha])
  3217. # Check the file content is back to initial
  3218. with open(fullpath) as f:
  3219. self.assertEqual("initial content\n", f.read())
  3220. # Check the revert commit message
  3221. revert_commit = self.repo[revert_sha]
  3222. self.assertIn(b'Revert "Change content"', revert_commit.message)
  3223. self.assertIn(change_sha[:7], revert_commit.message)
  3224. def test_revert_multiple(self) -> None:
  3225. # Create initial commit
  3226. fullpath = os.path.join(self.repo.path, "foo")
  3227. with open(fullpath, "w") as f:
  3228. f.write("line1\n")
  3229. porcelain.add(self.repo.path, paths=[fullpath])
  3230. porcelain.commit(
  3231. self.repo.path,
  3232. message=b"Initial commit",
  3233. committer=b"Jane <jane@example.com>",
  3234. author=b"John <john@example.com>",
  3235. )
  3236. # Add line2
  3237. with open(fullpath, "a") as f:
  3238. f.write("line2\n")
  3239. porcelain.add(self.repo.path, paths=[fullpath])
  3240. commit1 = porcelain.commit(
  3241. self.repo.path,
  3242. message=b"Add line2",
  3243. committer=b"Jane <jane@example.com>",
  3244. author=b"John <john@example.com>",
  3245. )
  3246. # Add line3
  3247. with open(fullpath, "a") as f:
  3248. f.write("line3\n")
  3249. porcelain.add(self.repo.path, paths=[fullpath])
  3250. commit2 = porcelain.commit(
  3251. self.repo.path,
  3252. message=b"Add line3",
  3253. committer=b"Jane <jane@example.com>",
  3254. author=b"John <john@example.com>",
  3255. )
  3256. # Revert both commits (in reverse order)
  3257. porcelain.revert(self.repo.path, commits=[commit2, commit1])
  3258. # Check file is back to initial state
  3259. with open(fullpath) as f:
  3260. self.assertEqual("line1\n", f.read())
  3261. def test_revert_no_commit(self) -> None:
  3262. # Create initial commit
  3263. fullpath = os.path.join(self.repo.path, "foo")
  3264. with open(fullpath, "w") as f:
  3265. f.write("initial\n")
  3266. porcelain.add(self.repo.path, paths=[fullpath])
  3267. porcelain.commit(
  3268. self.repo.path,
  3269. message=b"Initial",
  3270. committer=b"Jane <jane@example.com>",
  3271. author=b"John <john@example.com>",
  3272. )
  3273. # Make a change
  3274. with open(fullpath, "w") as f:
  3275. f.write("changed\n")
  3276. porcelain.add(self.repo.path, paths=[fullpath])
  3277. change_sha = porcelain.commit(
  3278. self.repo.path,
  3279. message=b"Change",
  3280. committer=b"Jane <jane@example.com>",
  3281. author=b"John <john@example.com>",
  3282. )
  3283. # Revert with no_commit
  3284. result = porcelain.revert(self.repo.path, commits=[change_sha], no_commit=True)
  3285. # Should return None
  3286. self.assertIsNone(result)
  3287. # File should be reverted
  3288. with open(fullpath) as f:
  3289. self.assertEqual("initial\n", f.read())
  3290. # HEAD should still point to the change commit
  3291. self.assertEqual(self.repo.refs[b"HEAD"], change_sha)
  3292. def test_revert_custom_message(self) -> None:
  3293. # Create commits
  3294. fullpath = os.path.join(self.repo.path, "foo")
  3295. with open(fullpath, "w") as f:
  3296. f.write("initial\n")
  3297. porcelain.add(self.repo.path, paths=[fullpath])
  3298. porcelain.commit(
  3299. self.repo.path,
  3300. message=b"Initial",
  3301. committer=b"Jane <jane@example.com>",
  3302. author=b"John <john@example.com>",
  3303. )
  3304. with open(fullpath, "w") as f:
  3305. f.write("changed\n")
  3306. porcelain.add(self.repo.path, paths=[fullpath])
  3307. change_sha = porcelain.commit(
  3308. self.repo.path,
  3309. message=b"Change",
  3310. committer=b"Jane <jane@example.com>",
  3311. author=b"John <john@example.com>",
  3312. )
  3313. # Revert with custom message
  3314. custom_msg = "Custom revert message"
  3315. revert_sha = porcelain.revert(
  3316. self.repo.path, commits=[change_sha], message=custom_msg
  3317. )
  3318. # Check the message
  3319. revert_commit = self.repo[revert_sha]
  3320. self.assertEqual(custom_msg.encode("utf-8"), revert_commit.message)
  3321. def test_revert_no_parent(self) -> None:
  3322. # Try to revert the initial commit (no parent)
  3323. fullpath = os.path.join(self.repo.path, "foo")
  3324. with open(fullpath, "w") as f:
  3325. f.write("content\n")
  3326. porcelain.add(self.repo.path, paths=[fullpath])
  3327. initial_sha = porcelain.commit(
  3328. self.repo.path,
  3329. message=b"Initial",
  3330. committer=b"Jane <jane@example.com>",
  3331. author=b"John <john@example.com>",
  3332. )
  3333. # Should raise an error
  3334. with self.assertRaises(porcelain.Error) as cm:
  3335. porcelain.revert(self.repo.path, commits=[initial_sha])
  3336. self.assertIn("no parents", str(cm.exception))
  3337. class CheckoutTests(PorcelainTestCase):
  3338. def setUp(self) -> None:
  3339. super().setUp()
  3340. self._sha, self._foo_path = _commit_file_with_content(
  3341. self.repo, "foo", "hello\n"
  3342. )
  3343. porcelain.branch_create(self.repo, "uni")
  3344. def test_checkout_to_existing_branch(self) -> None:
  3345. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3346. porcelain.checkout(self.repo, b"uni")
  3347. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3348. def test_checkout_to_non_existing_branch(self) -> None:
  3349. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3350. with self.assertRaises(KeyError):
  3351. porcelain.checkout(self.repo, b"bob")
  3352. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3353. def test_checkout_to_branch_with_modified_files(self) -> None:
  3354. with open(self._foo_path, "a") as f:
  3355. f.write("new message\n")
  3356. porcelain.add(self.repo, paths=[self._foo_path])
  3357. status = list(porcelain.status(self.repo))
  3358. self.assertEqual(
  3359. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  3360. )
  3361. # The new checkout behavior prevents switching with staged changes
  3362. with self.assertRaises(porcelain.CheckoutError):
  3363. porcelain.checkout(self.repo, b"uni")
  3364. # Should still be on master
  3365. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3366. # Force checkout should work
  3367. porcelain.checkout(self.repo, b"uni", force=True)
  3368. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3369. def test_checkout_with_deleted_files(self) -> None:
  3370. porcelain.remove(self.repo.path, [os.path.join(self.repo.path, "foo")])
  3371. status = list(porcelain.status(self.repo))
  3372. self.assertEqual(
  3373. [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status
  3374. )
  3375. # The new checkout behavior prevents switching with staged deletions
  3376. with self.assertRaises(porcelain.CheckoutError):
  3377. porcelain.checkout(self.repo, b"uni")
  3378. # Should still be on master
  3379. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3380. # Force checkout should work
  3381. porcelain.checkout(self.repo, b"uni", force=True)
  3382. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3383. def test_checkout_to_branch_with_added_files(self) -> None:
  3384. file_path = os.path.join(self.repo.path, "bar")
  3385. with open(file_path, "w") as f:
  3386. f.write("bar content\n")
  3387. porcelain.add(self.repo, paths=[file_path])
  3388. status = list(porcelain.status(self.repo))
  3389. self.assertEqual(
  3390. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3391. )
  3392. # Both branches have file 'foo' checkout should be fine.
  3393. porcelain.checkout(self.repo, b"uni")
  3394. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3395. status = list(porcelain.status(self.repo))
  3396. self.assertEqual(
  3397. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  3398. )
  3399. def test_checkout_to_branch_with_modified_file_not_present(self) -> None:
  3400. # Commit a new file that the other branch doesn't have.
  3401. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3402. # Modify the file the other branch doesn't have.
  3403. with open(nee_path, "a") as f:
  3404. f.write("bar content\n")
  3405. porcelain.add(self.repo, paths=[nee_path])
  3406. status = list(porcelain.status(self.repo))
  3407. self.assertEqual(
  3408. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3409. )
  3410. # The new checkout behavior allows switching if the file doesn't exist in target branch
  3411. # (changes can be preserved)
  3412. porcelain.checkout(self.repo, b"uni")
  3413. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3414. # The staged changes are lost and the file is removed from working tree
  3415. # because it doesn't exist in the target branch
  3416. status = list(porcelain.status(self.repo))
  3417. # File 'nee' is gone completely
  3418. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3419. self.assertFalse(os.path.exists(nee_path))
  3420. def test_checkout_to_branch_with_modified_file_not_present_forced(self) -> None:
  3421. # Commit a new file that the other branch doesn't have.
  3422. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  3423. # Modify the file the other branch doesn't have.
  3424. with open(nee_path, "a") as f:
  3425. f.write("bar content\n")
  3426. porcelain.add(self.repo, paths=[nee_path])
  3427. status = list(porcelain.status(self.repo))
  3428. self.assertEqual(
  3429. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  3430. )
  3431. # 'uni' branch doesn't have 'nee' and it has been modified, but we force to reset the entire index.
  3432. porcelain.checkout(self.repo, b"uni", force=True)
  3433. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3434. status = list(porcelain.status(self.repo))
  3435. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3436. def test_checkout_to_branch_with_unstaged_files(self) -> None:
  3437. # Edit `foo`.
  3438. with open(self._foo_path, "a") as f:
  3439. f.write("new message")
  3440. status = list(porcelain.status(self.repo))
  3441. self.assertEqual(
  3442. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  3443. )
  3444. # The new checkout behavior prevents switching with unstaged changes
  3445. with self.assertRaises(porcelain.CheckoutError):
  3446. porcelain.checkout(self.repo, b"uni")
  3447. # Should still be on master
  3448. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3449. # Force checkout should work
  3450. porcelain.checkout(self.repo, b"uni", force=True)
  3451. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3452. def test_checkout_to_branch_with_untracked_files(self) -> None:
  3453. with open(os.path.join(self.repo.path, "neu"), "a") as f:
  3454. f.write("new message\n")
  3455. status = list(porcelain.status(self.repo))
  3456. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3457. porcelain.checkout(self.repo, b"uni")
  3458. status = list(porcelain.status(self.repo))
  3459. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  3460. def test_checkout_to_branch_with_new_files(self) -> None:
  3461. porcelain.checkout(self.repo, b"uni")
  3462. sub_directory = os.path.join(self.repo.path, "sub1")
  3463. os.mkdir(sub_directory)
  3464. for index in range(5):
  3465. _commit_file_with_content(
  3466. self.repo, "new_file_" + str(index + 1), "Some content\n"
  3467. )
  3468. _commit_file_with_content(
  3469. self.repo,
  3470. os.path.join("sub1", "new_file_" + str(index + 10)),
  3471. "Good content\n",
  3472. )
  3473. status = list(porcelain.status(self.repo))
  3474. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3475. porcelain.checkout(self.repo, b"master")
  3476. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3477. status = list(porcelain.status(self.repo))
  3478. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3479. porcelain.checkout(self.repo, b"uni")
  3480. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  3481. status = list(porcelain.status(self.repo))
  3482. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3483. def test_checkout_to_branch_with_file_in_sub_directory(self) -> None:
  3484. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3485. os.makedirs(sub_directory)
  3486. sub_directory_file = os.path.join(sub_directory, "neu")
  3487. with open(sub_directory_file, "w") as f:
  3488. f.write("new message\n")
  3489. porcelain.add(self.repo, paths=[sub_directory_file])
  3490. porcelain.commit(
  3491. self.repo,
  3492. message=b"add " + sub_directory_file.encode(),
  3493. committer=b"Jane <jane@example.com>",
  3494. author=b"John <john@example.com>",
  3495. )
  3496. status = list(porcelain.status(self.repo))
  3497. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3498. self.assertTrue(os.path.isdir(sub_directory))
  3499. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3500. porcelain.checkout(self.repo, b"uni")
  3501. status = list(porcelain.status(self.repo))
  3502. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3503. self.assertFalse(os.path.isdir(sub_directory))
  3504. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3505. porcelain.checkout(self.repo, b"master")
  3506. self.assertTrue(os.path.isdir(sub_directory))
  3507. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3508. def test_checkout_to_branch_with_multiple_files_in_sub_directory(self) -> None:
  3509. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  3510. os.makedirs(sub_directory)
  3511. sub_directory_file_1 = os.path.join(sub_directory, "neu")
  3512. with open(sub_directory_file_1, "w") as f:
  3513. f.write("new message\n")
  3514. sub_directory_file_2 = os.path.join(sub_directory, "gus")
  3515. with open(sub_directory_file_2, "w") as f:
  3516. f.write("alternative message\n")
  3517. porcelain.add(self.repo, paths=[sub_directory_file_1, sub_directory_file_2])
  3518. porcelain.commit(
  3519. self.repo,
  3520. message=b"add files neu and gus.",
  3521. committer=b"Jane <jane@example.com>",
  3522. author=b"John <john@example.com>",
  3523. )
  3524. status = list(porcelain.status(self.repo))
  3525. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3526. self.assertTrue(os.path.isdir(sub_directory))
  3527. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  3528. porcelain.checkout(self.repo, b"uni")
  3529. status = list(porcelain.status(self.repo))
  3530. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  3531. self.assertFalse(os.path.isdir(sub_directory))
  3532. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  3533. def _commit_something_wrong(self):
  3534. with open(self._foo_path, "a") as f:
  3535. f.write("something wrong")
  3536. porcelain.add(self.repo, paths=[self._foo_path])
  3537. return porcelain.commit(
  3538. self.repo,
  3539. message=b"I may added something wrong",
  3540. committer=b"Jane <jane@example.com>",
  3541. author=b"John <john@example.com>",
  3542. )
  3543. def test_checkout_to_commit_sha(self) -> None:
  3544. self._commit_something_wrong()
  3545. porcelain.checkout(self.repo, self._sha)
  3546. self.assertEqual(self._sha, self.repo.head())
  3547. def test_checkout_to_head(self) -> None:
  3548. new_sha = self._commit_something_wrong()
  3549. porcelain.checkout(self.repo, b"HEAD")
  3550. self.assertEqual(new_sha, self.repo.head())
  3551. def _checkout_remote_branch(self):
  3552. errstream = BytesIO()
  3553. outstream = BytesIO()
  3554. porcelain.commit(
  3555. repo=self.repo.path,
  3556. message=b"init",
  3557. author=b"author <email>",
  3558. committer=b"committer <email>",
  3559. )
  3560. # Setup target repo cloned from temp test repo
  3561. clone_path = tempfile.mkdtemp()
  3562. self.addCleanup(shutil.rmtree, clone_path)
  3563. target_repo = porcelain.clone(
  3564. self.repo.path, target=clone_path, errstream=errstream
  3565. )
  3566. self.addCleanup(target_repo.close)
  3567. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  3568. # create a second file to be pushed back to origin
  3569. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3570. os.close(handle)
  3571. porcelain.add(repo=clone_path, paths=[fullpath])
  3572. porcelain.commit(
  3573. repo=clone_path,
  3574. message=b"push",
  3575. author=b"author <email>",
  3576. committer=b"committer <email>",
  3577. )
  3578. # Setup a non-checked out branch in the remote
  3579. refs_path = b"refs/heads/foo"
  3580. new_id = self.repo[b"HEAD"].id
  3581. self.assertNotEqual(new_id, ZERO_SHA)
  3582. self.repo.refs[refs_path] = new_id
  3583. # Push to the remote
  3584. porcelain.push(
  3585. clone_path,
  3586. "origin",
  3587. b"HEAD:" + refs_path,
  3588. outstream=outstream,
  3589. errstream=errstream,
  3590. )
  3591. self.assertEqual(
  3592. target_repo.refs[b"refs/remotes/origin/foo"],
  3593. target_repo.refs[b"HEAD"],
  3594. )
  3595. # The new checkout behavior treats origin/foo as a ref and creates detached HEAD
  3596. porcelain.checkout(target_repo, b"origin/foo")
  3597. original_id = target_repo[b"HEAD"].id
  3598. uni_id = target_repo[b"refs/remotes/origin/uni"].id
  3599. # Should be in detached HEAD state
  3600. with self.assertRaises((ValueError, IndexError)):
  3601. porcelain.active_branch(target_repo)
  3602. expected_refs = {
  3603. b"HEAD": original_id,
  3604. b"refs/heads/master": original_id,
  3605. # No local foo branch is created anymore
  3606. b"refs/remotes/origin/foo": original_id,
  3607. b"refs/remotes/origin/uni": uni_id,
  3608. b"refs/remotes/origin/HEAD": new_id,
  3609. b"refs/remotes/origin/master": new_id,
  3610. }
  3611. self.assertEqual(expected_refs, target_repo.get_refs())
  3612. return target_repo
  3613. def test_checkout_remote_branch(self) -> None:
  3614. repo = self._checkout_remote_branch()
  3615. repo.close()
  3616. def test_checkout_remote_branch_then_master_then_remote_branch_again(self) -> None:
  3617. target_repo = self._checkout_remote_branch()
  3618. # Should be in detached HEAD state
  3619. with self.assertRaises((ValueError, IndexError)):
  3620. porcelain.active_branch(target_repo)
  3621. # Save the commit SHA before adding bar
  3622. detached_commit_sha, _ = _commit_file_with_content(
  3623. target_repo, "bar", "something\n"
  3624. )
  3625. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3626. porcelain.checkout(target_repo, b"master")
  3627. self.assertEqual(b"master", porcelain.active_branch(target_repo))
  3628. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3629. # Going back to origin/foo won't have bar because the commit was made in detached state
  3630. porcelain.checkout(target_repo, b"origin/foo")
  3631. # Should be in detached HEAD state again
  3632. with self.assertRaises((ValueError, IndexError)):
  3633. porcelain.active_branch(target_repo)
  3634. # bar is NOT there because we're back at the original origin/foo commit
  3635. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3636. # But we can checkout the specific commit to get bar back
  3637. porcelain.checkout(target_repo, detached_commit_sha.decode())
  3638. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  3639. target_repo.close()
  3640. def test_checkout_new_branch_from_remote_sets_tracking(self) -> None:
  3641. # Create a "remote" repository
  3642. remote_path = tempfile.mkdtemp()
  3643. self.addCleanup(shutil.rmtree, remote_path)
  3644. remote_repo = porcelain.init(remote_path)
  3645. # Add a commit to the remote
  3646. remote_sha, _ = _commit_file_with_content(
  3647. remote_repo, "bar", "remote content\n"
  3648. )
  3649. # Clone the remote repository
  3650. target_path = tempfile.mkdtemp()
  3651. self.addCleanup(shutil.rmtree, target_path)
  3652. target_repo = porcelain.clone(remote_path, target_path)
  3653. self.addCleanup(target_repo.close)
  3654. # Create a remote tracking branch reference
  3655. remote_branch_ref = b"refs/remotes/origin/feature"
  3656. target_repo.refs[remote_branch_ref] = remote_sha
  3657. # Checkout a new branch from the remote branch
  3658. porcelain.checkout(target_repo, remote_branch_ref, new_branch=b"local-feature")
  3659. # Verify the branch was created and is active
  3660. self.assertEqual(b"local-feature", porcelain.active_branch(target_repo))
  3661. # Verify tracking configuration was set
  3662. config = target_repo.get_config()
  3663. self.assertEqual(
  3664. b"origin", config.get((b"branch", b"local-feature"), b"remote")
  3665. )
  3666. self.assertEqual(
  3667. b"refs/heads/feature", config.get((b"branch", b"local-feature"), b"merge")
  3668. )
  3669. target_repo.close()
  3670. remote_repo.close()
  3671. class GeneralCheckoutTests(PorcelainTestCase):
  3672. """Tests for the general checkout function that handles branches, tags, and commits."""
  3673. def setUp(self) -> None:
  3674. super().setUp()
  3675. # Create initial commit
  3676. self._sha1, self._foo_path = _commit_file_with_content(
  3677. self.repo, "foo", "initial content\n"
  3678. )
  3679. # Create a branch
  3680. porcelain.branch_create(self.repo, "feature")
  3681. # Create another commit on master
  3682. self._sha2, self._bar_path = _commit_file_with_content(
  3683. self.repo, "bar", "bar content\n"
  3684. )
  3685. # Create a tag
  3686. porcelain.tag_create(self.repo, "v1.0", objectish=self._sha1)
  3687. def test_checkout_branch(self) -> None:
  3688. """Test checking out a branch."""
  3689. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3690. # Checkout feature branch
  3691. porcelain.checkout(self.repo, "feature")
  3692. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3693. # File 'bar' should not exist in feature branch
  3694. self.assertFalse(os.path.exists(self._bar_path))
  3695. # Go back to master
  3696. porcelain.checkout(self.repo, "master")
  3697. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3698. # File 'bar' should exist again
  3699. self.assertTrue(os.path.exists(self._bar_path))
  3700. def test_checkout_commit(self) -> None:
  3701. """Test checking out a specific commit (detached HEAD)."""
  3702. # Checkout first commit by SHA
  3703. porcelain.checkout(self.repo, self._sha1.decode("ascii"))
  3704. # Should be in detached HEAD state - active_branch raises IndexError
  3705. with self.assertRaises((ValueError, IndexError)):
  3706. porcelain.active_branch(self.repo)
  3707. # File 'bar' should not exist
  3708. self.assertFalse(os.path.exists(self._bar_path))
  3709. # HEAD should point to the commit
  3710. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3711. def test_checkout_tag(self) -> None:
  3712. """Test checking out a tag (detached HEAD)."""
  3713. # Checkout tag
  3714. porcelain.checkout(self.repo, "v1.0")
  3715. # Should be in detached HEAD state - active_branch raises IndexError
  3716. with self.assertRaises((ValueError, IndexError)):
  3717. porcelain.active_branch(self.repo)
  3718. # File 'bar' should not exist (tag points to first commit)
  3719. self.assertFalse(os.path.exists(self._bar_path))
  3720. # HEAD should point to the tagged commit
  3721. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3722. def test_checkout_new_branch(self) -> None:
  3723. """Test creating a new branch during checkout (like git checkout -b)."""
  3724. # Create and checkout new branch from current HEAD
  3725. porcelain.checkout(self.repo, "master", new_branch="new-feature")
  3726. self.assertEqual(b"new-feature", porcelain.active_branch(self.repo))
  3727. self.assertTrue(os.path.exists(self._bar_path))
  3728. # Create and checkout new branch from specific commit
  3729. porcelain.checkout(self.repo, self._sha1.decode("ascii"), new_branch="from-old")
  3730. self.assertEqual(b"from-old", porcelain.active_branch(self.repo))
  3731. self.assertFalse(os.path.exists(self._bar_path))
  3732. def test_checkout_with_uncommitted_changes(self) -> None:
  3733. """Test checkout behavior with uncommitted changes."""
  3734. # Modify a file
  3735. with open(self._foo_path, "w") as f:
  3736. f.write("modified content\n")
  3737. # Should raise error when trying to checkout
  3738. with self.assertRaises(porcelain.CheckoutError) as cm:
  3739. porcelain.checkout(self.repo, "feature")
  3740. self.assertIn("local changes", str(cm.exception))
  3741. self.assertIn("foo", str(cm.exception))
  3742. # Should still be on master
  3743. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3744. def test_checkout_force(self) -> None:
  3745. """Test forced checkout discards local changes."""
  3746. # Modify a file
  3747. with open(self._foo_path, "w") as f:
  3748. f.write("modified content\n")
  3749. # Force checkout should succeed
  3750. porcelain.checkout(self.repo, "feature", force=True)
  3751. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3752. # Local changes should be discarded
  3753. with open(self._foo_path) as f:
  3754. content = f.read()
  3755. self.assertEqual("initial content\n", content)
  3756. def test_checkout_nonexistent_ref(self) -> None:
  3757. """Test checkout of non-existent branch/commit."""
  3758. with self.assertRaises(KeyError):
  3759. porcelain.checkout(self.repo, "nonexistent")
  3760. def test_checkout_partial_sha(self) -> None:
  3761. """Test checkout with partial SHA."""
  3762. # Git typically allows checkout with partial SHA
  3763. partial_sha = self._sha1.decode("ascii")[:7]
  3764. porcelain.checkout(self.repo, partial_sha)
  3765. # Should be in detached HEAD state at the right commit
  3766. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3767. def test_checkout_preserves_untracked_files(self) -> None:
  3768. """Test that checkout preserves untracked files."""
  3769. # Create an untracked file
  3770. untracked_path = os.path.join(self.repo.path, "untracked.txt")
  3771. with open(untracked_path, "w") as f:
  3772. f.write("untracked content\n")
  3773. # Checkout another branch
  3774. porcelain.checkout(self.repo, "feature")
  3775. # Untracked file should still exist
  3776. self.assertTrue(os.path.exists(untracked_path))
  3777. with open(untracked_path) as f:
  3778. content = f.read()
  3779. self.assertEqual("untracked content\n", content)
  3780. def test_checkout_full_ref_paths(self) -> None:
  3781. """Test checkout with full ref paths."""
  3782. # Test checkout with full branch ref path
  3783. porcelain.checkout(self.repo, "refs/heads/feature")
  3784. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3785. # Test checkout with full tag ref path
  3786. porcelain.checkout(self.repo, "refs/tags/v1.0")
  3787. # Should be in detached HEAD state
  3788. with self.assertRaises((ValueError, IndexError)):
  3789. porcelain.active_branch(self.repo)
  3790. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  3791. def test_checkout_bytes_vs_string_target(self) -> None:
  3792. """Test that checkout works with both bytes and string targets."""
  3793. # Test with string target
  3794. porcelain.checkout(self.repo, "feature")
  3795. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3796. # Test with bytes target
  3797. porcelain.checkout(self.repo, b"master")
  3798. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3799. def test_checkout_new_branch_from_commit(self) -> None:
  3800. """Test creating a new branch from a specific commit."""
  3801. # Create new branch from first commit
  3802. porcelain.checkout(self.repo, self._sha1.decode(), new_branch="from-commit")
  3803. self.assertEqual(b"from-commit", porcelain.active_branch(self.repo))
  3804. # Should be at the first commit (no bar file)
  3805. self.assertFalse(os.path.exists(self._bar_path))
  3806. def test_checkout_with_staged_addition(self) -> None:
  3807. """Test checkout behavior with staged file additions."""
  3808. # Create and stage a new file that doesn't exist in target branch
  3809. new_file_path = os.path.join(self.repo.path, "new.txt")
  3810. with open(new_file_path, "w") as f:
  3811. f.write("new file content\n")
  3812. porcelain.add(self.repo, [new_file_path])
  3813. # This should succeed because the file doesn't exist in target branch
  3814. porcelain.checkout(self.repo, "feature")
  3815. # Should be on feature branch
  3816. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  3817. # The new file should still exist and be staged
  3818. self.assertTrue(os.path.exists(new_file_path))
  3819. status = porcelain.status(self.repo)
  3820. self.assertIn(b"new.txt", status.staged["add"])
  3821. def test_checkout_with_staged_modification_conflict(self) -> None:
  3822. """Test checkout behavior with staged modifications that would conflict."""
  3823. # Stage changes to a file that exists in both branches
  3824. with open(self._foo_path, "w") as f:
  3825. f.write("modified content\n")
  3826. porcelain.add(self.repo, [self._foo_path])
  3827. # Should prevent checkout due to staged changes to existing file
  3828. with self.assertRaises(porcelain.CheckoutError) as cm:
  3829. porcelain.checkout(self.repo, "feature")
  3830. self.assertIn("local changes", str(cm.exception))
  3831. self.assertIn("foo", str(cm.exception))
  3832. def test_checkout_head_reference(self) -> None:
  3833. """Test checkout of HEAD reference."""
  3834. # Move to feature branch first
  3835. porcelain.checkout(self.repo, "feature")
  3836. # Checkout HEAD creates detached HEAD state
  3837. porcelain.checkout(self.repo, "HEAD")
  3838. # Should be in detached HEAD state
  3839. with self.assertRaises((ValueError, IndexError)):
  3840. porcelain.active_branch(self.repo)
  3841. def test_checkout_error_messages(self) -> None:
  3842. """Test that checkout error messages are helpful."""
  3843. # Create uncommitted changes
  3844. with open(self._foo_path, "w") as f:
  3845. f.write("uncommitted changes\n")
  3846. # Try to checkout
  3847. with self.assertRaises(porcelain.CheckoutError) as cm:
  3848. porcelain.checkout(self.repo, "feature")
  3849. error_msg = str(cm.exception)
  3850. self.assertIn("local changes", error_msg)
  3851. self.assertIn("foo", error_msg)
  3852. self.assertIn("overwritten", error_msg)
  3853. self.assertIn("commit or stash", error_msg)
  3854. class SubmoduleTests(PorcelainTestCase):
  3855. def test_empty(self) -> None:
  3856. porcelain.commit(
  3857. repo=self.repo.path,
  3858. message=b"init",
  3859. author=b"author <email>",
  3860. committer=b"committer <email>",
  3861. )
  3862. self.assertEqual([], list(porcelain.submodule_list(self.repo)))
  3863. def test_add(self) -> None:
  3864. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  3865. with open(f"{self.repo.path}/.gitmodules") as f:
  3866. self.assertEqual(
  3867. """\
  3868. [submodule "bar"]
  3869. \turl = ../bar.git
  3870. \tpath = bar
  3871. """,
  3872. f.read(),
  3873. )
  3874. def test_init(self) -> None:
  3875. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  3876. porcelain.submodule_init(self.repo)
  3877. def test_update(self) -> None:
  3878. # Create a submodule repository
  3879. sub_repo_path = tempfile.mkdtemp()
  3880. self.addCleanup(shutil.rmtree, sub_repo_path)
  3881. sub_repo = Repo.init(sub_repo_path)
  3882. self.addCleanup(sub_repo.close)
  3883. # Add a file to the submodule repo
  3884. sub_file = os.path.join(sub_repo_path, "test.txt")
  3885. with open(sub_file, "w") as f:
  3886. f.write("submodule content")
  3887. porcelain.add(sub_repo, paths=[sub_file])
  3888. sub_commit = porcelain.commit(
  3889. sub_repo,
  3890. message=b"Initial submodule commit",
  3891. author=b"Test Author <test@example.com>",
  3892. committer=b"Test Committer <test@example.com>",
  3893. )
  3894. # Add the submodule to the main repository
  3895. porcelain.submodule_add(self.repo, sub_repo_path, "test_submodule")
  3896. # Manually add the submodule to the index
  3897. from dulwich.index import IndexEntry
  3898. from dulwich.objects import S_IFGITLINK
  3899. index = self.repo.open_index()
  3900. index[b"test_submodule"] = IndexEntry(
  3901. ctime=0,
  3902. mtime=0,
  3903. dev=0,
  3904. ino=0,
  3905. mode=S_IFGITLINK,
  3906. uid=0,
  3907. gid=0,
  3908. size=0,
  3909. sha=sub_commit,
  3910. flags=0,
  3911. )
  3912. index.write()
  3913. porcelain.add(self.repo, paths=[".gitmodules"])
  3914. porcelain.commit(
  3915. self.repo,
  3916. message=b"Add submodule",
  3917. author=b"Test Author <test@example.com>",
  3918. committer=b"Test Committer <test@example.com>",
  3919. )
  3920. # Initialize and update the submodule
  3921. porcelain.submodule_init(self.repo)
  3922. porcelain.submodule_update(self.repo)
  3923. # Check that the submodule directory exists
  3924. submodule_path = os.path.join(self.repo.path, "test_submodule")
  3925. self.assertTrue(os.path.exists(submodule_path))
  3926. # Check that the submodule file exists
  3927. submodule_file = os.path.join(submodule_path, "test.txt")
  3928. self.assertTrue(os.path.exists(submodule_file))
  3929. with open(submodule_file) as f:
  3930. self.assertEqual(f.read(), "submodule content")
  3931. class PushTests(PorcelainTestCase):
  3932. def test_simple(self) -> None:
  3933. """Basic test of porcelain push where self.repo is the remote. First
  3934. clone the remote, commit a file to the clone, then push the changes
  3935. back to the remote.
  3936. """
  3937. outstream = BytesIO()
  3938. errstream = BytesIO()
  3939. porcelain.commit(
  3940. repo=self.repo.path,
  3941. message=b"init",
  3942. author=b"author <email>",
  3943. committer=b"committer <email>",
  3944. )
  3945. # Setup target repo cloned from temp test repo
  3946. clone_path = tempfile.mkdtemp()
  3947. self.addCleanup(shutil.rmtree, clone_path)
  3948. target_repo = porcelain.clone(
  3949. self.repo.path, target=clone_path, errstream=errstream
  3950. )
  3951. self.addCleanup(target_repo.close)
  3952. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  3953. # create a second file to be pushed back to origin
  3954. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  3955. os.close(handle)
  3956. porcelain.add(repo=clone_path, paths=[fullpath])
  3957. porcelain.commit(
  3958. repo=clone_path,
  3959. message=b"push",
  3960. author=b"author <email>",
  3961. committer=b"committer <email>",
  3962. )
  3963. # Setup a non-checked out branch in the remote
  3964. refs_path = b"refs/heads/foo"
  3965. new_id = self.repo[b"HEAD"].id
  3966. self.assertNotEqual(new_id, ZERO_SHA)
  3967. self.repo.refs[refs_path] = new_id
  3968. # Push to the remote
  3969. porcelain.push(
  3970. clone_path,
  3971. "origin",
  3972. b"HEAD:" + refs_path,
  3973. outstream=outstream,
  3974. errstream=errstream,
  3975. )
  3976. self.assertEqual(
  3977. target_repo.refs[b"refs/remotes/origin/foo"],
  3978. target_repo.refs[b"HEAD"],
  3979. )
  3980. # Check that the target and source
  3981. with Repo(clone_path) as r_clone:
  3982. self.assertEqual(
  3983. {
  3984. b"HEAD": new_id,
  3985. b"refs/heads/foo": r_clone[b"HEAD"].id,
  3986. b"refs/heads/master": new_id,
  3987. },
  3988. self.repo.get_refs(),
  3989. )
  3990. self.assertEqual(r_clone[b"HEAD"].id, self.repo[refs_path].id)
  3991. # Get the change in the target repo corresponding to the add
  3992. # this will be in the foo branch.
  3993. change = next(
  3994. iter(
  3995. tree_changes(
  3996. self.repo.object_store,
  3997. self.repo[b"HEAD"].tree,
  3998. self.repo[b"refs/heads/foo"].tree,
  3999. )
  4000. )
  4001. )
  4002. self.assertEqual(
  4003. os.path.basename(fullpath), change.new.path.decode("ascii")
  4004. )
  4005. def test_local_missing(self) -> None:
  4006. """Pushing a new branch."""
  4007. outstream = BytesIO()
  4008. errstream = BytesIO()
  4009. # Setup target repo cloned from temp test repo
  4010. clone_path = tempfile.mkdtemp()
  4011. self.addCleanup(shutil.rmtree, clone_path)
  4012. target_repo = porcelain.init(clone_path)
  4013. target_repo.close()
  4014. self.assertRaises(
  4015. porcelain.Error,
  4016. porcelain.push,
  4017. self.repo,
  4018. clone_path,
  4019. b"HEAD:refs/heads/master",
  4020. outstream=outstream,
  4021. errstream=errstream,
  4022. )
  4023. def test_new(self) -> None:
  4024. """Pushing a new branch."""
  4025. outstream = BytesIO()
  4026. errstream = BytesIO()
  4027. # Setup target repo cloned from temp test repo
  4028. clone_path = tempfile.mkdtemp()
  4029. self.addCleanup(shutil.rmtree, clone_path)
  4030. target_repo = porcelain.init(clone_path)
  4031. target_repo.close()
  4032. # create a second file to be pushed back to origin
  4033. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4034. os.close(handle)
  4035. porcelain.add(repo=clone_path, paths=[fullpath])
  4036. new_id = porcelain.commit(
  4037. repo=self.repo,
  4038. message=b"push",
  4039. author=b"author <email>",
  4040. committer=b"committer <email>",
  4041. )
  4042. # Push to the remote
  4043. porcelain.push(
  4044. self.repo,
  4045. clone_path,
  4046. b"HEAD:refs/heads/master",
  4047. outstream=outstream,
  4048. errstream=errstream,
  4049. )
  4050. with Repo(clone_path) as r_clone:
  4051. self.assertEqual(
  4052. {
  4053. b"HEAD": new_id,
  4054. b"refs/heads/master": new_id,
  4055. },
  4056. r_clone.get_refs(),
  4057. )
  4058. def test_delete(self) -> None:
  4059. """Basic test of porcelain push, removing a branch."""
  4060. outstream = BytesIO()
  4061. errstream = BytesIO()
  4062. porcelain.commit(
  4063. repo=self.repo.path,
  4064. message=b"init",
  4065. author=b"author <email>",
  4066. committer=b"committer <email>",
  4067. )
  4068. # Setup target repo cloned from temp test repo
  4069. clone_path = tempfile.mkdtemp()
  4070. self.addCleanup(shutil.rmtree, clone_path)
  4071. target_repo = porcelain.clone(
  4072. self.repo.path, target=clone_path, errstream=errstream
  4073. )
  4074. target_repo.close()
  4075. # Setup a non-checked out branch in the remote
  4076. refs_path = b"refs/heads/foo"
  4077. new_id = self.repo[b"HEAD"].id
  4078. self.assertNotEqual(new_id, ZERO_SHA)
  4079. self.repo.refs[refs_path] = new_id
  4080. # Push to the remote
  4081. porcelain.push(
  4082. clone_path,
  4083. self.repo.path,
  4084. b":" + refs_path,
  4085. outstream=outstream,
  4086. errstream=errstream,
  4087. )
  4088. self.assertEqual(
  4089. {
  4090. b"HEAD": new_id,
  4091. b"refs/heads/master": new_id,
  4092. },
  4093. self.repo.get_refs(),
  4094. )
  4095. def test_diverged(self) -> None:
  4096. outstream = BytesIO()
  4097. errstream = BytesIO()
  4098. porcelain.commit(
  4099. repo=self.repo.path,
  4100. message=b"init",
  4101. author=b"author <email>",
  4102. committer=b"committer <email>",
  4103. )
  4104. # Setup target repo cloned from temp test repo
  4105. clone_path = tempfile.mkdtemp()
  4106. self.addCleanup(shutil.rmtree, clone_path)
  4107. target_repo = porcelain.clone(
  4108. self.repo.path, target=clone_path, errstream=errstream
  4109. )
  4110. target_repo.close()
  4111. remote_id = porcelain.commit(
  4112. repo=self.repo.path,
  4113. message=b"remote change",
  4114. author=b"author <email>",
  4115. committer=b"committer <email>",
  4116. )
  4117. local_id = porcelain.commit(
  4118. repo=clone_path,
  4119. message=b"local change",
  4120. author=b"author <email>",
  4121. committer=b"committer <email>",
  4122. )
  4123. outstream = BytesIO()
  4124. errstream = BytesIO()
  4125. # Push to the remote
  4126. self.assertRaises(
  4127. porcelain.DivergedBranches,
  4128. porcelain.push,
  4129. clone_path,
  4130. self.repo.path,
  4131. b"refs/heads/master",
  4132. outstream=outstream,
  4133. errstream=errstream,
  4134. )
  4135. self.assertEqual(
  4136. {
  4137. b"HEAD": remote_id,
  4138. b"refs/heads/master": remote_id,
  4139. },
  4140. self.repo.get_refs(),
  4141. )
  4142. self.assertEqual(b"", outstream.getvalue())
  4143. self.assertEqual(b"", errstream.getvalue())
  4144. outstream = BytesIO()
  4145. errstream = BytesIO()
  4146. # Push to the remote with --force
  4147. porcelain.push(
  4148. clone_path,
  4149. self.repo.path,
  4150. b"refs/heads/master",
  4151. outstream=outstream,
  4152. errstream=errstream,
  4153. force=True,
  4154. )
  4155. self.assertEqual(
  4156. {
  4157. b"HEAD": local_id,
  4158. b"refs/heads/master": local_id,
  4159. },
  4160. self.repo.get_refs(),
  4161. )
  4162. self.assertEqual(b"", outstream.getvalue())
  4163. self.assertTrue(re.match(b"Push to .* successful.\n", errstream.getvalue()))
  4164. def test_push_returns_sendpackresult(self) -> None:
  4165. """Test that push returns a SendPackResult with per-ref information."""
  4166. outstream = BytesIO()
  4167. errstream = BytesIO()
  4168. # Create initial commit
  4169. porcelain.commit(
  4170. repo=self.repo.path,
  4171. message=b"init",
  4172. author=b"author <email>",
  4173. committer=b"committer <email>",
  4174. )
  4175. # Setup target repo cloned from temp test repo
  4176. clone_path = tempfile.mkdtemp()
  4177. self.addCleanup(shutil.rmtree, clone_path)
  4178. target_repo = porcelain.clone(
  4179. self.repo.path, target=clone_path, errstream=errstream
  4180. )
  4181. target_repo.close()
  4182. # Create a commit in the clone
  4183. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  4184. os.close(handle)
  4185. porcelain.add(repo=clone_path, paths=[fullpath])
  4186. porcelain.commit(
  4187. repo=clone_path,
  4188. message=b"push",
  4189. author=b"author <email>",
  4190. committer=b"committer <email>",
  4191. )
  4192. # Push and check the return value
  4193. result = porcelain.push(
  4194. clone_path,
  4195. "origin",
  4196. b"HEAD:refs/heads/new-branch",
  4197. outstream=outstream,
  4198. errstream=errstream,
  4199. )
  4200. # Verify that we get a SendPackResult
  4201. self.assertIsInstance(result, SendPackResult)
  4202. # Verify that it contains refs
  4203. self.assertIsNotNone(result.refs)
  4204. self.assertIn(b"refs/heads/new-branch", result.refs)
  4205. # Verify ref_status - should be None for successful updates
  4206. if result.ref_status:
  4207. self.assertIsNone(result.ref_status.get(b"refs/heads/new-branch"))
  4208. def test_mirror_mode(self) -> None:
  4209. """Test push with remote.<name>.mirror configuration."""
  4210. outstream = BytesIO()
  4211. errstream = BytesIO()
  4212. # Create initial commit
  4213. porcelain.commit(
  4214. repo=self.repo.path,
  4215. message=b"init",
  4216. author=b"author <email>",
  4217. committer=b"committer <email>",
  4218. )
  4219. # Setup target repo cloned from temp test repo
  4220. clone_path = tempfile.mkdtemp()
  4221. self.addCleanup(shutil.rmtree, clone_path)
  4222. target_repo = porcelain.clone(
  4223. self.repo.path, target=clone_path, errstream=errstream
  4224. )
  4225. target_repo.close()
  4226. # Create multiple refs in the clone
  4227. with Repo(clone_path) as r_clone:
  4228. # Create a new branch
  4229. r_clone.refs[b"refs/heads/feature"] = r_clone[b"HEAD"].id
  4230. # Create a tag
  4231. r_clone.refs[b"refs/tags/v1.0"] = r_clone[b"HEAD"].id
  4232. # Create a remote tracking branch
  4233. r_clone.refs[b"refs/remotes/upstream/main"] = r_clone[b"HEAD"].id
  4234. # Create a branch in the remote that doesn't exist in clone
  4235. self.repo.refs[b"refs/heads/to-be-deleted"] = self.repo[b"HEAD"].id
  4236. # Configure mirror mode
  4237. with Repo(clone_path) as r_clone:
  4238. config = r_clone.get_config()
  4239. config.set((b"remote", b"origin"), b"mirror", True)
  4240. config.write_to_path()
  4241. # Push with mirror mode
  4242. porcelain.push(
  4243. clone_path,
  4244. "origin",
  4245. outstream=outstream,
  4246. errstream=errstream,
  4247. )
  4248. # Verify refs were properly mirrored
  4249. with Repo(clone_path) as r_clone:
  4250. # All local branches should be pushed
  4251. self.assertEqual(
  4252. r_clone.refs[b"refs/heads/feature"],
  4253. self.repo.refs[b"refs/heads/feature"],
  4254. )
  4255. # All tags should be pushed
  4256. self.assertEqual(
  4257. r_clone.refs[b"refs/tags/v1.0"], self.repo.refs[b"refs/tags/v1.0"]
  4258. )
  4259. # Remote tracking branches should be pushed
  4260. self.assertEqual(
  4261. r_clone.refs[b"refs/remotes/upstream/main"],
  4262. self.repo.refs[b"refs/remotes/upstream/main"],
  4263. )
  4264. # Verify the extra branch was deleted
  4265. self.assertNotIn(b"refs/heads/to-be-deleted", self.repo.refs)
  4266. def test_mirror_mode_disabled(self) -> None:
  4267. """Test that mirror mode is properly disabled when set to false."""
  4268. outstream = BytesIO()
  4269. errstream = BytesIO()
  4270. # Create initial commit
  4271. porcelain.commit(
  4272. repo=self.repo.path,
  4273. message=b"init",
  4274. author=b"author <email>",
  4275. committer=b"committer <email>",
  4276. )
  4277. # Setup target repo cloned from temp test repo
  4278. clone_path = tempfile.mkdtemp()
  4279. self.addCleanup(shutil.rmtree, clone_path)
  4280. target_repo = porcelain.clone(
  4281. self.repo.path, target=clone_path, errstream=errstream
  4282. )
  4283. target_repo.close()
  4284. # Create a branch in the remote that doesn't exist in clone
  4285. self.repo.refs[b"refs/heads/should-not-be-deleted"] = self.repo[b"HEAD"].id
  4286. # Explicitly set mirror mode to false
  4287. with Repo(clone_path) as r_clone:
  4288. config = r_clone.get_config()
  4289. config.set((b"remote", b"origin"), b"mirror", False)
  4290. config.write_to_path()
  4291. # Push normally (not mirror mode)
  4292. porcelain.push(
  4293. clone_path,
  4294. "origin",
  4295. outstream=outstream,
  4296. errstream=errstream,
  4297. )
  4298. # Verify the extra branch was NOT deleted
  4299. self.assertIn(b"refs/heads/should-not-be-deleted", self.repo.refs)
  4300. class PullTests(PorcelainTestCase):
  4301. def setUp(self) -> None:
  4302. super().setUp()
  4303. # create a file for initial commit
  4304. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4305. os.close(handle)
  4306. porcelain.add(repo=self.repo.path, paths=fullpath)
  4307. porcelain.commit(
  4308. repo=self.repo.path,
  4309. message=b"test",
  4310. author=b"test <email>",
  4311. committer=b"test <email>",
  4312. )
  4313. # Setup target repo
  4314. self.target_path = tempfile.mkdtemp()
  4315. self.addCleanup(shutil.rmtree, self.target_path)
  4316. target_repo = porcelain.clone(
  4317. self.repo.path, target=self.target_path, errstream=BytesIO()
  4318. )
  4319. target_repo.close()
  4320. # create a second file to be pushed
  4321. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  4322. os.close(handle)
  4323. porcelain.add(repo=self.repo.path, paths=fullpath)
  4324. porcelain.commit(
  4325. repo=self.repo.path,
  4326. message=b"test2",
  4327. author=b"test2 <email>",
  4328. committer=b"test2 <email>",
  4329. )
  4330. self.assertIn(b"refs/heads/master", self.repo.refs)
  4331. self.assertIn(b"refs/heads/master", target_repo.refs)
  4332. def test_simple(self) -> None:
  4333. outstream = BytesIO()
  4334. errstream = BytesIO()
  4335. # Pull changes into the cloned repo
  4336. porcelain.pull(
  4337. self.target_path,
  4338. self.repo.path,
  4339. b"refs/heads/master",
  4340. outstream=outstream,
  4341. errstream=errstream,
  4342. )
  4343. # Check the target repo for pushed changes
  4344. with Repo(self.target_path) as r:
  4345. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4346. def test_diverged(self) -> None:
  4347. outstream = BytesIO()
  4348. errstream = BytesIO()
  4349. c3a = porcelain.commit(
  4350. repo=self.target_path,
  4351. message=b"test3a",
  4352. author=b"test2 <email>",
  4353. committer=b"test2 <email>",
  4354. )
  4355. porcelain.commit(
  4356. repo=self.repo.path,
  4357. message=b"test3b",
  4358. author=b"test2 <email>",
  4359. committer=b"test2 <email>",
  4360. )
  4361. # Pull changes into the cloned repo
  4362. self.assertRaises(
  4363. porcelain.DivergedBranches,
  4364. porcelain.pull,
  4365. self.target_path,
  4366. self.repo.path,
  4367. b"refs/heads/master",
  4368. outstream=outstream,
  4369. errstream=errstream,
  4370. )
  4371. # Check the target repo for pushed changes
  4372. with Repo(self.target_path) as r:
  4373. self.assertEqual(r[b"refs/heads/master"].id, c3a)
  4374. # Pull with merge should now work
  4375. porcelain.pull(
  4376. self.target_path,
  4377. self.repo.path,
  4378. b"refs/heads/master",
  4379. outstream=outstream,
  4380. errstream=errstream,
  4381. fast_forward=False,
  4382. )
  4383. # Check the target repo for merged changes
  4384. with Repo(self.target_path) as r:
  4385. # HEAD should now be a merge commit
  4386. head = r[b"HEAD"]
  4387. # It should have two parents
  4388. self.assertEqual(len(head.parents), 2)
  4389. # One parent should be the previous HEAD (c3a)
  4390. self.assertIn(c3a, head.parents)
  4391. # The other parent should be from the source repo
  4392. self.assertIn(self.repo[b"HEAD"].id, head.parents)
  4393. def test_no_refspec(self) -> None:
  4394. outstream = BytesIO()
  4395. errstream = BytesIO()
  4396. # Pull changes into the cloned repo
  4397. porcelain.pull(
  4398. self.target_path,
  4399. self.repo.path,
  4400. outstream=outstream,
  4401. errstream=errstream,
  4402. )
  4403. # Check the target repo for pushed changes
  4404. with Repo(self.target_path) as r:
  4405. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4406. def test_no_remote_location(self) -> None:
  4407. outstream = BytesIO()
  4408. errstream = BytesIO()
  4409. # Pull changes into the cloned repo
  4410. porcelain.pull(
  4411. self.target_path,
  4412. refspecs=b"refs/heads/master",
  4413. outstream=outstream,
  4414. errstream=errstream,
  4415. )
  4416. # Check the target repo for pushed changes
  4417. with Repo(self.target_path) as r:
  4418. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4419. def test_pull_updates_working_tree(self) -> None:
  4420. """Test that pull updates the working tree with new files."""
  4421. outstream = BytesIO()
  4422. errstream = BytesIO()
  4423. # Create a new file with content in the source repo
  4424. new_file = os.path.join(self.repo.path, "newfile.txt")
  4425. with open(new_file, "w") as f:
  4426. f.write("This is new content")
  4427. porcelain.add(repo=self.repo.path, paths=[new_file])
  4428. porcelain.commit(
  4429. repo=self.repo.path,
  4430. message=b"Add new file",
  4431. author=b"test <email>",
  4432. committer=b"test <email>",
  4433. )
  4434. # Before pull, the file should not exist in target
  4435. target_file = os.path.join(self.target_path, "newfile.txt")
  4436. self.assertFalse(os.path.exists(target_file))
  4437. # Pull changes into the cloned repo
  4438. porcelain.pull(
  4439. self.target_path,
  4440. self.repo.path,
  4441. b"refs/heads/master",
  4442. outstream=outstream,
  4443. errstream=errstream,
  4444. )
  4445. # After pull, the file should exist with correct content
  4446. self.assertTrue(os.path.exists(target_file))
  4447. with open(target_file) as f:
  4448. self.assertEqual(f.read(), "This is new content")
  4449. # Check the HEAD is updated too
  4450. with Repo(self.target_path) as r:
  4451. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  4452. class StatusTests(PorcelainTestCase):
  4453. def test_empty(self) -> None:
  4454. results = porcelain.status(self.repo)
  4455. self.assertEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4456. self.assertEqual([], results.unstaged)
  4457. def test_status_base(self) -> None:
  4458. """Integration test for `status` functionality."""
  4459. # Commit a dummy file then modify it
  4460. fullpath = os.path.join(self.repo.path, "foo")
  4461. with open(fullpath, "w") as f:
  4462. f.write("origstuff")
  4463. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4464. porcelain.commit(
  4465. repo=self.repo.path,
  4466. message=b"test status",
  4467. author=b"author <email>",
  4468. committer=b"committer <email>",
  4469. )
  4470. # modify access and modify time of path
  4471. os.utime(fullpath, (0, 0))
  4472. with open(fullpath, "wb") as f:
  4473. f.write(b"stuff")
  4474. # Make a dummy file and stage it
  4475. filename_add = "bar"
  4476. fullpath = os.path.join(self.repo.path, filename_add)
  4477. with open(fullpath, "w") as f:
  4478. f.write("stuff")
  4479. porcelain.add(repo=self.repo.path, paths=fullpath)
  4480. results = porcelain.status(self.repo)
  4481. self.assertEqual(results.staged["add"][0], filename_add.encode("ascii"))
  4482. self.assertEqual(results.unstaged, [b"foo"])
  4483. def test_status_all(self) -> None:
  4484. del_path = os.path.join(self.repo.path, "foo")
  4485. mod_path = os.path.join(self.repo.path, "bar")
  4486. add_path = os.path.join(self.repo.path, "baz")
  4487. us_path = os.path.join(self.repo.path, "blye")
  4488. ut_path = os.path.join(self.repo.path, "blyat")
  4489. with open(del_path, "w") as f:
  4490. f.write("origstuff")
  4491. with open(mod_path, "w") as f:
  4492. f.write("origstuff")
  4493. with open(us_path, "w") as f:
  4494. f.write("origstuff")
  4495. porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path])
  4496. porcelain.commit(
  4497. repo=self.repo.path,
  4498. message=b"test status",
  4499. author=b"author <email>",
  4500. committer=b"committer <email>",
  4501. )
  4502. porcelain.remove(self.repo.path, [del_path])
  4503. with open(add_path, "w") as f:
  4504. f.write("origstuff")
  4505. with open(mod_path, "w") as f:
  4506. f.write("more_origstuff")
  4507. with open(us_path, "w") as f:
  4508. f.write("more_origstuff")
  4509. porcelain.add(repo=self.repo.path, paths=[add_path, mod_path])
  4510. with open(us_path, "w") as f:
  4511. f.write("\norigstuff")
  4512. with open(ut_path, "w") as f:
  4513. f.write("origstuff")
  4514. results = porcelain.status(self.repo.path)
  4515. self.assertDictEqual(
  4516. {"add": [b"baz"], "delete": [b"foo"], "modify": [b"bar"]},
  4517. results.staged,
  4518. )
  4519. self.assertListEqual(results.unstaged, [b"blye"])
  4520. results_no_untracked = porcelain.status(self.repo.path, untracked_files="no")
  4521. self.assertListEqual(results_no_untracked.untracked, [])
  4522. def test_status_wrong_untracked_files_value(self) -> None:
  4523. with self.assertRaises(ValueError):
  4524. porcelain.status(self.repo.path, untracked_files="antani")
  4525. def test_status_untracked_path(self) -> None:
  4526. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  4527. os.mkdir(untracked_dir)
  4528. untracked_file = os.path.join(untracked_dir, "untracked_file")
  4529. with open(untracked_file, "w") as fh:
  4530. fh.write("untracked")
  4531. _, _, untracked = porcelain.status(self.repo.path, untracked_files="all")
  4532. self.assertEqual(untracked, ["untracked_dir/untracked_file"])
  4533. def test_status_untracked_path_normal(self) -> None:
  4534. # Create an untracked directory with multiple files
  4535. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  4536. os.mkdir(untracked_dir)
  4537. untracked_file1 = os.path.join(untracked_dir, "file1")
  4538. untracked_file2 = os.path.join(untracked_dir, "file2")
  4539. with open(untracked_file1, "w") as fh:
  4540. fh.write("untracked1")
  4541. with open(untracked_file2, "w") as fh:
  4542. fh.write("untracked2")
  4543. # Create a nested untracked directory
  4544. nested_dir = os.path.join(untracked_dir, "nested")
  4545. os.mkdir(nested_dir)
  4546. nested_file = os.path.join(nested_dir, "file3")
  4547. with open(nested_file, "w") as fh:
  4548. fh.write("untracked3")
  4549. # Test "normal" mode - should only show the directory, not individual files
  4550. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  4551. self.assertEqual(untracked, ["untracked_dir/"])
  4552. # Test "all" mode - should show all files
  4553. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  4554. self.assertEqual(
  4555. sorted(untracked_all),
  4556. [
  4557. "untracked_dir/file1",
  4558. "untracked_dir/file2",
  4559. "untracked_dir/nested/file3",
  4560. ],
  4561. )
  4562. def test_status_mixed_tracked_untracked(self) -> None:
  4563. # Create a directory with both tracked and untracked files
  4564. mixed_dir = os.path.join(self.repo_path, "mixed_dir")
  4565. os.mkdir(mixed_dir)
  4566. # Add a tracked file
  4567. tracked_file = os.path.join(mixed_dir, "tracked.txt")
  4568. with open(tracked_file, "w") as fh:
  4569. fh.write("tracked content")
  4570. porcelain.add(self.repo.path, paths=[tracked_file])
  4571. porcelain.commit(
  4572. repo=self.repo.path,
  4573. message=b"add tracked file",
  4574. author=b"author <email>",
  4575. committer=b"committer <email>",
  4576. )
  4577. # Add untracked files to the same directory
  4578. untracked_file = os.path.join(mixed_dir, "untracked.txt")
  4579. with open(untracked_file, "w") as fh:
  4580. fh.write("untracked content")
  4581. # In "normal" mode, should show individual untracked files in mixed dirs
  4582. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  4583. self.assertEqual(untracked, ["mixed_dir/untracked.txt"])
  4584. # In "all" mode, should be the same for mixed directories
  4585. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  4586. self.assertEqual(untracked_all, ["mixed_dir/untracked.txt"])
  4587. def test_status_crlf_mismatch(self) -> None:
  4588. # First make a commit as if the file has been added on a Linux system
  4589. # or with core.autocrlf=True
  4590. file_path = os.path.join(self.repo.path, "crlf")
  4591. with open(file_path, "wb") as f:
  4592. f.write(b"line1\nline2")
  4593. porcelain.add(repo=self.repo.path, paths=[file_path])
  4594. porcelain.commit(
  4595. repo=self.repo.path,
  4596. message=b"test status",
  4597. author=b"author <email>",
  4598. committer=b"committer <email>",
  4599. )
  4600. # Then update the file as if it was created by CGit on a Windows
  4601. # system with core.autocrlf=true
  4602. with open(file_path, "wb") as f:
  4603. f.write(b"line1\r\nline2")
  4604. results = porcelain.status(self.repo)
  4605. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4606. self.assertListEqual(results.unstaged, [b"crlf"])
  4607. self.assertListEqual(results.untracked, [])
  4608. def test_status_autocrlf_true(self) -> None:
  4609. # First make a commit as if the file has been added on a Linux system
  4610. # or with core.autocrlf=True
  4611. file_path = os.path.join(self.repo.path, "crlf")
  4612. with open(file_path, "wb") as f:
  4613. f.write(b"line1\nline2")
  4614. porcelain.add(repo=self.repo.path, paths=[file_path])
  4615. porcelain.commit(
  4616. repo=self.repo.path,
  4617. message=b"test status",
  4618. author=b"author <email>",
  4619. committer=b"committer <email>",
  4620. )
  4621. # Then update the file as if it was created by CGit on a Windows
  4622. # system with core.autocrlf=true
  4623. with open(file_path, "wb") as f:
  4624. f.write(b"line1\r\nline2")
  4625. # TODO: It should be set automatically by looking at the configuration
  4626. c = self.repo.get_config()
  4627. c.set("core", "autocrlf", True)
  4628. c.write_to_path()
  4629. results = porcelain.status(self.repo)
  4630. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  4631. self.assertListEqual(results.unstaged, [])
  4632. self.assertListEqual(results.untracked, [])
  4633. def test_status_autocrlf_input(self) -> None:
  4634. # Commit existing file with CRLF
  4635. file_path = os.path.join(self.repo.path, "crlf-exists")
  4636. with open(file_path, "wb") as f:
  4637. f.write(b"line1\r\nline2")
  4638. porcelain.add(repo=self.repo.path, paths=[file_path])
  4639. porcelain.commit(
  4640. repo=self.repo.path,
  4641. message=b"test status",
  4642. author=b"author <email>",
  4643. committer=b"committer <email>",
  4644. )
  4645. c = self.repo.get_config()
  4646. c.set("core", "autocrlf", "input")
  4647. c.write_to_path()
  4648. # Add new (untracked) file
  4649. file_path = os.path.join(self.repo.path, "crlf-new")
  4650. with open(file_path, "wb") as f:
  4651. f.write(b"line1\r\nline2")
  4652. porcelain.add(repo=self.repo.path, paths=[file_path])
  4653. results = porcelain.status(self.repo)
  4654. self.assertDictEqual(
  4655. {"add": [b"crlf-new"], "delete": [], "modify": []}, results.staged
  4656. )
  4657. self.assertListEqual(results.unstaged, [b"crlf-exists"])
  4658. self.assertListEqual(results.untracked, [])
  4659. def test_get_tree_changes_add(self) -> None:
  4660. """Unit test for get_tree_changes add."""
  4661. # Make a dummy file, stage
  4662. filename = "bar"
  4663. fullpath = os.path.join(self.repo.path, filename)
  4664. with open(fullpath, "w") as f:
  4665. f.write("stuff")
  4666. porcelain.add(repo=self.repo.path, paths=fullpath)
  4667. porcelain.commit(
  4668. repo=self.repo.path,
  4669. message=b"test status",
  4670. author=b"author <email>",
  4671. committer=b"committer <email>",
  4672. )
  4673. filename = "foo"
  4674. fullpath = os.path.join(self.repo.path, filename)
  4675. with open(fullpath, "w") as f:
  4676. f.write("stuff")
  4677. porcelain.add(repo=self.repo.path, paths=fullpath)
  4678. changes = porcelain.get_tree_changes(self.repo.path)
  4679. self.assertEqual(changes["add"][0], filename.encode("ascii"))
  4680. self.assertEqual(len(changes["add"]), 1)
  4681. self.assertEqual(len(changes["modify"]), 0)
  4682. self.assertEqual(len(changes["delete"]), 0)
  4683. def test_get_tree_changes_modify(self) -> None:
  4684. """Unit test for get_tree_changes modify."""
  4685. # Make a dummy file, stage, commit, modify
  4686. filename = "foo"
  4687. fullpath = os.path.join(self.repo.path, filename)
  4688. with open(fullpath, "w") as f:
  4689. f.write("stuff")
  4690. porcelain.add(repo=self.repo.path, paths=fullpath)
  4691. porcelain.commit(
  4692. repo=self.repo.path,
  4693. message=b"test status",
  4694. author=b"author <email>",
  4695. committer=b"committer <email>",
  4696. )
  4697. with open(fullpath, "w") as f:
  4698. f.write("otherstuff")
  4699. porcelain.add(repo=self.repo.path, paths=fullpath)
  4700. changes = porcelain.get_tree_changes(self.repo.path)
  4701. self.assertEqual(changes["modify"][0], filename.encode("ascii"))
  4702. self.assertEqual(len(changes["add"]), 0)
  4703. self.assertEqual(len(changes["modify"]), 1)
  4704. self.assertEqual(len(changes["delete"]), 0)
  4705. def test_get_tree_changes_delete(self) -> None:
  4706. """Unit test for get_tree_changes delete."""
  4707. # Make a dummy file, stage, commit, remove
  4708. filename = "foo"
  4709. fullpath = os.path.join(self.repo.path, filename)
  4710. with open(fullpath, "w") as f:
  4711. f.write("stuff")
  4712. porcelain.add(repo=self.repo.path, paths=fullpath)
  4713. porcelain.commit(
  4714. repo=self.repo.path,
  4715. message=b"test status",
  4716. author=b"author <email>",
  4717. committer=b"committer <email>",
  4718. )
  4719. cwd = os.getcwd()
  4720. self.addCleanup(os.chdir, cwd)
  4721. os.chdir(self.repo.path)
  4722. porcelain.remove(repo=self.repo.path, paths=[filename])
  4723. changes = porcelain.get_tree_changes(self.repo.path)
  4724. self.assertEqual(changes["delete"][0], filename.encode("ascii"))
  4725. self.assertEqual(len(changes["add"]), 0)
  4726. self.assertEqual(len(changes["modify"]), 0)
  4727. self.assertEqual(len(changes["delete"]), 1)
  4728. def test_get_untracked_paths(self) -> None:
  4729. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  4730. f.write("ignored\n")
  4731. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  4732. f.write("blah\n")
  4733. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  4734. f.write("blah\n")
  4735. os.symlink(
  4736. os.path.join(self.repo.path, os.pardir, "external_target"),
  4737. os.path.join(self.repo.path, "link"),
  4738. )
  4739. self.assertEqual(
  4740. {"ignored", "notignored", ".gitignore", "link"},
  4741. set(
  4742. porcelain.get_untracked_paths(
  4743. self.repo.path, self.repo.path, self.repo.open_index()
  4744. )
  4745. ),
  4746. )
  4747. self.assertEqual(
  4748. {".gitignore", "notignored", "link"},
  4749. set(porcelain.status(self.repo).untracked),
  4750. )
  4751. self.assertEqual(
  4752. {".gitignore", "notignored", "ignored", "link"},
  4753. set(porcelain.status(self.repo, ignored=True).untracked),
  4754. )
  4755. def test_get_untracked_paths_subrepo(self) -> None:
  4756. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  4757. f.write("nested/\n")
  4758. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  4759. f.write("blah\n")
  4760. subrepo = Repo.init(os.path.join(self.repo.path, "nested"), mkdir=True)
  4761. with open(os.path.join(subrepo.path, "ignored"), "w") as f:
  4762. f.write("bleep\n")
  4763. with open(os.path.join(subrepo.path, "with"), "w") as f:
  4764. f.write("bloop\n")
  4765. with open(os.path.join(subrepo.path, "manager"), "w") as f:
  4766. f.write("blop\n")
  4767. self.assertEqual(
  4768. {".gitignore", "notignored", os.path.join("nested", "")},
  4769. set(
  4770. porcelain.get_untracked_paths(
  4771. self.repo.path, self.repo.path, self.repo.open_index()
  4772. )
  4773. ),
  4774. )
  4775. self.assertEqual(
  4776. {".gitignore", "notignored"},
  4777. set(
  4778. porcelain.get_untracked_paths(
  4779. self.repo.path,
  4780. self.repo.path,
  4781. self.repo.open_index(),
  4782. exclude_ignored=True,
  4783. )
  4784. ),
  4785. )
  4786. self.assertEqual(
  4787. {"ignored", "with", "manager"},
  4788. set(
  4789. porcelain.get_untracked_paths(
  4790. subrepo.path, subrepo.path, subrepo.open_index()
  4791. )
  4792. ),
  4793. )
  4794. self.assertEqual(
  4795. set(),
  4796. set(
  4797. porcelain.get_untracked_paths(
  4798. subrepo.path,
  4799. self.repo.path,
  4800. self.repo.open_index(),
  4801. )
  4802. ),
  4803. )
  4804. self.assertEqual(
  4805. {
  4806. os.path.join("nested", "ignored"),
  4807. os.path.join("nested", "with"),
  4808. os.path.join("nested", "manager"),
  4809. },
  4810. set(
  4811. porcelain.get_untracked_paths(
  4812. self.repo.path,
  4813. subrepo.path,
  4814. self.repo.open_index(),
  4815. )
  4816. ),
  4817. )
  4818. def test_get_untracked_paths_nested_gitignore(self) -> None:
  4819. """Test directories with nested .gitignore files that ignore all contents."""
  4820. # Create cache directories with .gitignore files that contain "*"
  4821. cache_dirs = [".ruff_cache", ".pytest_cache", "__pycache__"]
  4822. for cache_dir in cache_dirs:
  4823. cache_path = os.path.join(self.repo.path, cache_dir)
  4824. os.mkdir(cache_path)
  4825. # Create .gitignore with * pattern (ignores everything)
  4826. with open(os.path.join(cache_path, ".gitignore"), "w") as f:
  4827. f.write("*\n")
  4828. # Create some files in the cache directory
  4829. with open(os.path.join(cache_path, "somefile.txt"), "w") as f:
  4830. f.write("cached data\n")
  4831. with open(os.path.join(cache_path, "data.json"), "w") as f:
  4832. f.write("{}\n")
  4833. # Create a normal untracked file
  4834. with open(os.path.join(self.repo.path, "untracked.txt"), "w") as f:
  4835. f.write("untracked content\n")
  4836. # Test with exclude_ignored=True (default for status)
  4837. untracked = set(
  4838. porcelain.get_untracked_paths(
  4839. self.repo.path,
  4840. self.repo.path,
  4841. self.repo.open_index(),
  4842. exclude_ignored=True,
  4843. untracked_files="normal",
  4844. )
  4845. )
  4846. # Cache directories should NOT be in untracked since all their contents are ignored
  4847. self.assertEqual({"untracked.txt"}, untracked)
  4848. # Test with exclude_ignored=False
  4849. untracked_with_ignored = set(
  4850. porcelain.get_untracked_paths(
  4851. self.repo.path,
  4852. self.repo.path,
  4853. self.repo.open_index(),
  4854. exclude_ignored=False,
  4855. untracked_files="normal",
  4856. )
  4857. )
  4858. # Cache directories should be included when not excluding ignored
  4859. expected = {"untracked.txt"}
  4860. for cache_dir in cache_dirs:
  4861. expected.add(cache_dir + os.sep)
  4862. self.assertEqual(expected, untracked_with_ignored)
  4863. # Test status() which uses exclude_ignored=True by default
  4864. status = porcelain.status(self.repo)
  4865. self.assertEqual(["untracked.txt"], status.untracked)
  4866. # Test status() with ignored=True which uses exclude_ignored=False
  4867. status_with_ignored = porcelain.status(self.repo, ignored=True)
  4868. # Should include cache directories
  4869. self.assertIn("untracked.txt", status_with_ignored.untracked)
  4870. for cache_dir in cache_dirs:
  4871. self.assertIn(cache_dir + "/", status_with_ignored.untracked)
  4872. def test_get_untracked_paths_mixed_directory(self) -> None:
  4873. """Test directory with both ignored and non-ignored files."""
  4874. # Create a directory with mixed content
  4875. mixed_dir = os.path.join(self.repo.path, "mixed")
  4876. os.mkdir(mixed_dir)
  4877. # Create .gitignore that ignores .log files
  4878. with open(os.path.join(mixed_dir, ".gitignore"), "w") as f:
  4879. f.write("*.log\n")
  4880. # Create ignored and non-ignored files
  4881. with open(os.path.join(mixed_dir, "debug.log"), "w") as f:
  4882. f.write("debug info\n")
  4883. with open(os.path.join(mixed_dir, "readme.txt"), "w") as f:
  4884. f.write("important\n")
  4885. # Test with exclude_ignored=True and normal mode
  4886. untracked = set(
  4887. porcelain.get_untracked_paths(
  4888. self.repo.path,
  4889. self.repo.path,
  4890. self.repo.open_index(),
  4891. exclude_ignored=True,
  4892. untracked_files="normal",
  4893. )
  4894. )
  4895. # In normal mode, should show the directory (matching git behavior)
  4896. self.assertEqual({os.path.join("mixed", "")}, untracked)
  4897. # Test with untracked_files="all"
  4898. untracked_all = set(
  4899. porcelain.get_untracked_paths(
  4900. self.repo.path,
  4901. self.repo.path,
  4902. self.repo.open_index(),
  4903. exclude_ignored=True,
  4904. untracked_files="all",
  4905. )
  4906. )
  4907. # Should list the non-ignored files
  4908. expected = {
  4909. os.path.join("mixed", ".gitignore"),
  4910. os.path.join("mixed", "readme.txt"),
  4911. }
  4912. self.assertEqual(expected, untracked_all)
  4913. def test_get_untracked_paths_specific_ignore_pattern(self) -> None:
  4914. """Test directory with .gitignore that ignores specific files, not all."""
  4915. # Create a directory
  4916. test_dir = os.path.join(self.repo.path, "testdir")
  4917. os.mkdir(test_dir)
  4918. # Create .gitignore that ignores only files named "test"
  4919. with open(os.path.join(test_dir, ".gitignore"), "w") as f:
  4920. f.write("test\n")
  4921. # Create files
  4922. with open(os.path.join(test_dir, "test"), "w") as f:
  4923. f.write("ignored\n")
  4924. with open(os.path.join(test_dir, "other.txt"), "w") as f:
  4925. f.write("not ignored\n")
  4926. # Test with exclude_ignored=True and normal mode
  4927. untracked = set(
  4928. porcelain.get_untracked_paths(
  4929. self.repo.path,
  4930. self.repo.path,
  4931. self.repo.open_index(),
  4932. exclude_ignored=True,
  4933. untracked_files="normal",
  4934. )
  4935. )
  4936. # Directory should be shown because it has non-ignored files
  4937. self.assertEqual({os.path.join("testdir", "")}, untracked)
  4938. def test_get_untracked_paths_nested_subdirs_all_ignored(self) -> None:
  4939. """Test directory containing only subdirectories where all files are ignored."""
  4940. # Create parent directory with .gitignore that ignores everything
  4941. parent_dir = os.path.join(self.repo.path, "parent")
  4942. os.mkdir(parent_dir)
  4943. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  4944. f.write("*\n")
  4945. # Create subdirectories with files (all should be ignored by parent's .gitignore)
  4946. sub1 = os.path.join(parent_dir, "sub1")
  4947. sub2 = os.path.join(parent_dir, "sub2")
  4948. os.mkdir(sub1)
  4949. os.mkdir(sub2)
  4950. # Create files in subdirectories
  4951. with open(os.path.join(sub1, "file1.txt"), "w") as f:
  4952. f.write("content1\n")
  4953. with open(os.path.join(sub2, "file2.txt"), "w") as f:
  4954. f.write("content2\n")
  4955. # Create another normal untracked file
  4956. with open(os.path.join(self.repo.path, "normal.txt"), "w") as f:
  4957. f.write("normal\n")
  4958. # Test with exclude_ignored=True
  4959. untracked = set(
  4960. porcelain.get_untracked_paths(
  4961. self.repo.path,
  4962. self.repo.path,
  4963. self.repo.open_index(),
  4964. exclude_ignored=True,
  4965. untracked_files="normal",
  4966. )
  4967. )
  4968. # Parent directory should NOT be shown since all nested files are ignored
  4969. self.assertEqual({"normal.txt"}, untracked)
  4970. def test_get_untracked_paths_nested_subdirs_mixed(self) -> None:
  4971. """Test directory containing only subdirectories where some files are ignored, some aren't."""
  4972. # Create parent directory with .gitignore that ignores .log files
  4973. parent_dir = os.path.join(self.repo.path, "parent")
  4974. os.mkdir(parent_dir)
  4975. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  4976. f.write("*.log\n")
  4977. # Create subdirectories
  4978. sub1 = os.path.join(parent_dir, "sub1")
  4979. sub2 = os.path.join(parent_dir, "sub2")
  4980. os.mkdir(sub1)
  4981. os.mkdir(sub2)
  4982. # sub1: only ignored files
  4983. with open(os.path.join(sub1, "debug.log"), "w") as f:
  4984. f.write("log content\n")
  4985. with open(os.path.join(sub1, "error.log"), "w") as f:
  4986. f.write("error log\n")
  4987. # sub2: mix of ignored and non-ignored files
  4988. with open(os.path.join(sub2, "access.log"), "w") as f:
  4989. f.write("access log\n")
  4990. with open(os.path.join(sub2, "readme.txt"), "w") as f:
  4991. f.write("important info\n")
  4992. # Test with exclude_ignored=True
  4993. untracked = set(
  4994. porcelain.get_untracked_paths(
  4995. self.repo.path,
  4996. self.repo.path,
  4997. self.repo.open_index(),
  4998. exclude_ignored=True,
  4999. untracked_files="normal",
  5000. )
  5001. )
  5002. # Parent directory SHOULD be shown since sub2 has non-ignored files
  5003. self.assertEqual({os.path.join("parent", "")}, untracked)
  5004. def test_get_untracked_paths_deeply_nested_all_ignored(self) -> None:
  5005. """Test deeply nested directories where all files are eventually ignored."""
  5006. # Create nested structure: parent/sub/subsub/
  5007. parent_dir = os.path.join(self.repo.path, "parent")
  5008. sub_dir = os.path.join(parent_dir, "sub")
  5009. subsub_dir = os.path.join(sub_dir, "subsub")
  5010. os.makedirs(subsub_dir)
  5011. # Parent has .gitignore that ignores everything
  5012. with open(os.path.join(parent_dir, ".gitignore"), "w") as f:
  5013. f.write("*\n")
  5014. # Create files at different levels
  5015. with open(os.path.join(subsub_dir, "deep_file.txt"), "w") as f:
  5016. f.write("deep content\n")
  5017. with open(os.path.join(sub_dir, "mid_file.txt"), "w") as f:
  5018. f.write("mid content\n")
  5019. # Test with exclude_ignored=True
  5020. untracked = set(
  5021. porcelain.get_untracked_paths(
  5022. self.repo.path,
  5023. self.repo.path,
  5024. self.repo.open_index(),
  5025. exclude_ignored=True,
  5026. untracked_files="normal",
  5027. )
  5028. )
  5029. # Parent directory should NOT be shown since all nested files are ignored
  5030. self.assertEqual(set(), untracked)
  5031. def test_get_untracked_paths_subdir(self) -> None:
  5032. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5033. f.write("subdir/\nignored")
  5034. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  5035. f.write("blah\n")
  5036. os.mkdir(os.path.join(self.repo.path, "subdir"))
  5037. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  5038. f.write("foo")
  5039. with open(os.path.join(self.repo.path, "subdir", "ignored"), "w") as f:
  5040. f.write("foo")
  5041. self.assertEqual(
  5042. {
  5043. ".gitignore",
  5044. "notignored",
  5045. "ignored",
  5046. os.path.join("subdir", ""),
  5047. },
  5048. set(
  5049. porcelain.get_untracked_paths(
  5050. self.repo.path,
  5051. self.repo.path,
  5052. self.repo.open_index(),
  5053. )
  5054. ),
  5055. )
  5056. self.assertEqual(
  5057. {".gitignore", "notignored"},
  5058. set(
  5059. porcelain.get_untracked_paths(
  5060. self.repo.path,
  5061. self.repo.path,
  5062. self.repo.open_index(),
  5063. exclude_ignored=True,
  5064. )
  5065. ),
  5066. )
  5067. def test_get_untracked_paths_invalid_untracked_files(self) -> None:
  5068. with self.assertRaises(ValueError):
  5069. list(
  5070. porcelain.get_untracked_paths(
  5071. self.repo.path,
  5072. self.repo.path,
  5073. self.repo.open_index(),
  5074. untracked_files="invalid_value",
  5075. )
  5076. )
  5077. def test_get_untracked_paths_normal(self) -> None:
  5078. # Create an untracked directory with files
  5079. untracked_dir = os.path.join(self.repo.path, "untracked_dir")
  5080. os.mkdir(untracked_dir)
  5081. with open(os.path.join(untracked_dir, "file1.txt"), "w") as f:
  5082. f.write("untracked content")
  5083. with open(os.path.join(untracked_dir, "file2.txt"), "w") as f:
  5084. f.write("more untracked content")
  5085. # Test that "normal" mode works and returns only the directory
  5086. _, _, untracked = porcelain.status(
  5087. repo=self.repo.path, untracked_files="normal"
  5088. )
  5089. self.assertEqual(untracked, ["untracked_dir/"])
  5090. def test_get_untracked_paths_top_level_issue_1247(self) -> None:
  5091. """Test for issue #1247: ensure top-level untracked files are detected."""
  5092. # Create a single top-level untracked file
  5093. with open(os.path.join(self.repo.path, "sample.txt"), "w") as f:
  5094. f.write("test content")
  5095. # Test get_untracked_paths directly
  5096. untracked = list(
  5097. porcelain.get_untracked_paths(
  5098. self.repo.path, self.repo.path, self.repo.open_index()
  5099. )
  5100. )
  5101. self.assertIn(
  5102. "sample.txt",
  5103. untracked,
  5104. "Top-level file 'sample.txt' should be in untracked list",
  5105. )
  5106. # Test via status
  5107. status = porcelain.status(self.repo)
  5108. self.assertIn(
  5109. "sample.txt",
  5110. status.untracked,
  5111. "Top-level file 'sample.txt' should be in status.untracked",
  5112. )
  5113. # TODO(jelmer): Add test for dulwich.porcelain.daemon
  5114. class UploadPackTests(PorcelainTestCase):
  5115. """Tests for upload_pack."""
  5116. def test_upload_pack(self) -> None:
  5117. outf = BytesIO()
  5118. exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf)
  5119. outlines = outf.getvalue().splitlines()
  5120. self.assertEqual([b"0000"], outlines)
  5121. self.assertEqual(0, exitcode)
  5122. class ReceivePackTests(PorcelainTestCase):
  5123. """Tests for receive_pack."""
  5124. def test_receive_pack(self) -> None:
  5125. filename = "foo"
  5126. fullpath = os.path.join(self.repo.path, filename)
  5127. with open(fullpath, "w") as f:
  5128. f.write("stuff")
  5129. porcelain.add(repo=self.repo.path, paths=fullpath)
  5130. self.repo.do_commit(
  5131. message=b"test status",
  5132. author=b"author <email>",
  5133. committer=b"committer <email>",
  5134. author_timestamp=1402354300,
  5135. commit_timestamp=1402354300,
  5136. author_timezone=0,
  5137. commit_timezone=0,
  5138. )
  5139. outf = BytesIO()
  5140. exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf)
  5141. outlines = outf.getvalue().splitlines()
  5142. self.assertEqual(
  5143. [
  5144. b"0091319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status "
  5145. b"delete-refs quiet ofs-delta side-band-64k "
  5146. b"no-done symref=HEAD:refs/heads/master",
  5147. b"003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master",
  5148. b"0000",
  5149. ],
  5150. outlines,
  5151. )
  5152. self.assertEqual(0, exitcode)
  5153. class BranchListTests(PorcelainTestCase):
  5154. def test_standard(self) -> None:
  5155. self.assertEqual(set(), set(porcelain.branch_list(self.repo)))
  5156. def test_new_branch(self) -> None:
  5157. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5158. self.repo[b"HEAD"] = c1.id
  5159. porcelain.branch_create(self.repo, b"foo")
  5160. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  5161. def test_sort_by_refname(self) -> None:
  5162. """Test branch.sort=refname (default alphabetical)."""
  5163. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5164. self.repo[b"HEAD"] = c1.id
  5165. # Create branches in non-alphabetical order
  5166. porcelain.branch_create(self.repo, b"zebra")
  5167. porcelain.branch_create(self.repo, b"alpha")
  5168. porcelain.branch_create(self.repo, b"beta")
  5169. # Set branch.sort to refname (though it's the default)
  5170. config = self.repo.get_config()
  5171. config.set((b"branch",), b"sort", b"refname")
  5172. config.write_to_path()
  5173. # Should be sorted alphabetically
  5174. branches = porcelain.branch_list(self.repo)
  5175. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5176. def test_sort_by_refname_reverse(self) -> None:
  5177. """Test branch.sort=-refname (reverse alphabetical)."""
  5178. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5179. self.repo[b"HEAD"] = c1.id
  5180. # Create branches
  5181. porcelain.branch_create(self.repo, b"zebra")
  5182. porcelain.branch_create(self.repo, b"alpha")
  5183. porcelain.branch_create(self.repo, b"beta")
  5184. # Set branch.sort to -refname
  5185. config = self.repo.get_config()
  5186. config.set((b"branch",), b"sort", b"-refname")
  5187. config.write_to_path()
  5188. # Should be sorted reverse alphabetically
  5189. branches = porcelain.branch_list(self.repo)
  5190. self.assertEqual([b"zebra", b"master", b"beta", b"alpha"], branches)
  5191. def test_sort_by_committerdate(self) -> None:
  5192. """Test branch.sort=committerdate."""
  5193. # Use build_commit_graph to create proper commits with specific times
  5194. c1, c2, c3 = build_commit_graph(
  5195. self.repo.object_store,
  5196. [[1], [2], [3]],
  5197. attrs={
  5198. 1: {"commit_time": 1000}, # oldest
  5199. 2: {"commit_time": 2000}, # newest
  5200. 3: {"commit_time": 1500}, # middle
  5201. },
  5202. )
  5203. self.repo[b"HEAD"] = c1.id
  5204. # Create branches pointing to different commits
  5205. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  5206. self.repo.refs[b"refs/heads/oldest"] = c1.id
  5207. self.repo.refs[b"refs/heads/newest"] = c2.id
  5208. self.repo.refs[b"refs/heads/middle"] = c3.id
  5209. # Set branch.sort to committerdate
  5210. config = self.repo.get_config()
  5211. config.set((b"branch",), b"sort", b"committerdate")
  5212. config.write_to_path()
  5213. # Should be sorted by commit time (oldest first)
  5214. branches = porcelain.branch_list(self.repo)
  5215. self.assertEqual([b"master", b"oldest", b"middle", b"newest"], branches)
  5216. def test_sort_by_committerdate_reverse(self) -> None:
  5217. """Test branch.sort=-committerdate."""
  5218. # Use build_commit_graph to create proper commits with specific times
  5219. c1, c2, c3 = build_commit_graph(
  5220. self.repo.object_store,
  5221. [[1], [2], [3]],
  5222. attrs={
  5223. 1: {"commit_time": 1000}, # oldest
  5224. 2: {"commit_time": 2000}, # newest
  5225. 3: {"commit_time": 1500}, # middle
  5226. },
  5227. )
  5228. self.repo[b"HEAD"] = c1.id
  5229. # Create branches pointing to different commits
  5230. self.repo.refs[b"refs/heads/master"] = c1.id # master points to oldest
  5231. self.repo.refs[b"refs/heads/oldest"] = c1.id
  5232. self.repo.refs[b"refs/heads/newest"] = c2.id
  5233. self.repo.refs[b"refs/heads/middle"] = c3.id
  5234. # Set branch.sort to -committerdate
  5235. config = self.repo.get_config()
  5236. config.set((b"branch",), b"sort", b"-committerdate")
  5237. config.write_to_path()
  5238. # Should be sorted by commit time (newest first)
  5239. branches = porcelain.branch_list(self.repo)
  5240. self.assertEqual([b"newest", b"middle", b"master", b"oldest"], branches)
  5241. def test_sort_default(self) -> None:
  5242. """Test default sorting (no config)."""
  5243. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5244. self.repo[b"HEAD"] = c1.id
  5245. # Create branches in non-alphabetical order
  5246. porcelain.branch_create(self.repo, b"zebra")
  5247. porcelain.branch_create(self.repo, b"alpha")
  5248. porcelain.branch_create(self.repo, b"beta")
  5249. # No config set - should default to alphabetical
  5250. branches = porcelain.branch_list(self.repo)
  5251. self.assertEqual([b"alpha", b"beta", b"master", b"zebra"], branches)
  5252. class BranchCreateTests(PorcelainTestCase):
  5253. def test_branch_exists(self) -> None:
  5254. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5255. self.repo[b"HEAD"] = c1.id
  5256. porcelain.branch_create(self.repo, b"foo")
  5257. self.assertRaises(porcelain.Error, porcelain.branch_create, self.repo, b"foo")
  5258. porcelain.branch_create(self.repo, b"foo", force=True)
  5259. def test_new_branch(self) -> None:
  5260. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5261. self.repo[b"HEAD"] = c1.id
  5262. porcelain.branch_create(self.repo, b"foo")
  5263. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  5264. def test_auto_setup_merge_true_from_remote_tracking(self) -> None:
  5265. """Test branch.autoSetupMerge=true sets up tracking from remote-tracking branch."""
  5266. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5267. self.repo[b"HEAD"] = c1.id
  5268. # Create a remote-tracking branch
  5269. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  5270. # Set branch.autoSetupMerge to true (default)
  5271. config = self.repo.get_config()
  5272. config.set((b"branch",), b"autoSetupMerge", b"true")
  5273. config.write_to_path()
  5274. # Create branch from remote-tracking branch
  5275. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  5276. # Verify tracking was set up
  5277. config = self.repo.get_config()
  5278. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  5279. self.assertEqual(
  5280. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  5281. )
  5282. def test_auto_setup_merge_false(self) -> None:
  5283. """Test branch.autoSetupMerge=false disables tracking setup."""
  5284. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5285. self.repo[b"HEAD"] = c1.id
  5286. # Create a remote-tracking branch
  5287. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  5288. # Set branch.autoSetupMerge to false
  5289. config = self.repo.get_config()
  5290. config.set((b"branch",), b"autoSetupMerge", b"false")
  5291. config.write_to_path()
  5292. # Create branch from remote-tracking branch
  5293. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  5294. # Verify tracking was NOT set up
  5295. config = self.repo.get_config()
  5296. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"remote")
  5297. self.assertRaises(KeyError, config.get, (b"branch", b"myfeature"), b"merge")
  5298. def test_auto_setup_merge_always(self) -> None:
  5299. """Test branch.autoSetupMerge=always sets up tracking even from local branches."""
  5300. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5301. self.repo[b"HEAD"] = c1.id
  5302. self.repo.refs[b"refs/heads/main"] = c1.id
  5303. # Set branch.autoSetupMerge to always
  5304. config = self.repo.get_config()
  5305. config.set((b"branch",), b"autoSetupMerge", b"always")
  5306. config.write_to_path()
  5307. # Create branch from local branch - normally wouldn't set up tracking
  5308. porcelain.branch_create(self.repo, "feature", "main")
  5309. # With always, tracking should NOT be set up from local branches
  5310. # (Git only sets up tracking from remote-tracking branches even with always)
  5311. config = self.repo.get_config()
  5312. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"remote")
  5313. self.assertRaises(KeyError, config.get, (b"branch", b"feature"), b"merge")
  5314. def test_auto_setup_merge_always_from_remote(self) -> None:
  5315. """Test branch.autoSetupMerge=always still sets up tracking from remote branches."""
  5316. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5317. self.repo[b"HEAD"] = c1.id
  5318. # Create a remote-tracking branch
  5319. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  5320. # Set branch.autoSetupMerge to always
  5321. config = self.repo.get_config()
  5322. config.set((b"branch",), b"autoSetupMerge", b"always")
  5323. config.write_to_path()
  5324. # Create branch from remote-tracking branch
  5325. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  5326. # Verify tracking was set up
  5327. config = self.repo.get_config()
  5328. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  5329. self.assertEqual(
  5330. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  5331. )
  5332. def test_auto_setup_merge_default(self) -> None:
  5333. """Test default behavior (no config) is same as true."""
  5334. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5335. self.repo[b"HEAD"] = c1.id
  5336. # Create a remote-tracking branch
  5337. self.repo.refs[b"refs/remotes/origin/feature"] = c1.id
  5338. # Don't set any config - should default to true
  5339. # Create branch from remote-tracking branch
  5340. porcelain.branch_create(self.repo, "myfeature", "origin/feature")
  5341. # Verify tracking was set up
  5342. config = self.repo.get_config()
  5343. self.assertEqual(config.get((b"branch", b"myfeature"), b"remote"), b"origin")
  5344. self.assertEqual(
  5345. config.get((b"branch", b"myfeature"), b"merge"), b"refs/heads/feature"
  5346. )
  5347. class BranchDeleteTests(PorcelainTestCase):
  5348. def test_simple(self) -> None:
  5349. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5350. self.repo[b"HEAD"] = c1.id
  5351. porcelain.branch_create(self.repo, b"foo")
  5352. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  5353. porcelain.branch_delete(self.repo, b"foo")
  5354. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  5355. def test_simple_unicode(self) -> None:
  5356. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5357. self.repo[b"HEAD"] = c1.id
  5358. porcelain.branch_create(self.repo, "foo")
  5359. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  5360. porcelain.branch_delete(self.repo, "foo")
  5361. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  5362. class FetchTests(PorcelainTestCase):
  5363. def test_simple(self) -> None:
  5364. outstream = BytesIO()
  5365. errstream = BytesIO()
  5366. # create a file for initial commit
  5367. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5368. os.close(handle)
  5369. porcelain.add(repo=self.repo.path, paths=fullpath)
  5370. porcelain.commit(
  5371. repo=self.repo.path,
  5372. message=b"test",
  5373. author=b"test <email>",
  5374. committer=b"test <email>",
  5375. )
  5376. # Setup target repo
  5377. target_path = tempfile.mkdtemp()
  5378. self.addCleanup(shutil.rmtree, target_path)
  5379. target_repo = porcelain.clone(
  5380. self.repo.path, target=target_path, errstream=errstream
  5381. )
  5382. # create a second file to be pushed
  5383. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5384. os.close(handle)
  5385. porcelain.add(repo=self.repo.path, paths=fullpath)
  5386. porcelain.commit(
  5387. repo=self.repo.path,
  5388. message=b"test2",
  5389. author=b"test2 <email>",
  5390. committer=b"test2 <email>",
  5391. )
  5392. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  5393. target_repo.close()
  5394. # Fetch changes into the cloned repo
  5395. porcelain.fetch(target_path, "origin", outstream=outstream, errstream=errstream)
  5396. # Assert that fetch updated the local image of the remote
  5397. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  5398. # Check the target repo for pushed changes
  5399. with Repo(target_path) as r:
  5400. self.assertIn(self.repo[b"HEAD"].id, r)
  5401. def test_with_remote_name(self) -> None:
  5402. remote_name = "origin"
  5403. outstream = BytesIO()
  5404. errstream = BytesIO()
  5405. # create a file for initial commit
  5406. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5407. os.close(handle)
  5408. porcelain.add(repo=self.repo.path, paths=fullpath)
  5409. porcelain.commit(
  5410. repo=self.repo.path,
  5411. message=b"test",
  5412. author=b"test <email>",
  5413. committer=b"test <email>",
  5414. )
  5415. # Setup target repo
  5416. target_path = tempfile.mkdtemp()
  5417. self.addCleanup(shutil.rmtree, target_path)
  5418. target_repo = porcelain.clone(
  5419. self.repo.path, target=target_path, errstream=errstream
  5420. )
  5421. # Capture current refs
  5422. target_refs = target_repo.get_refs()
  5423. # create a second file to be pushed
  5424. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5425. os.close(handle)
  5426. porcelain.add(repo=self.repo.path, paths=fullpath)
  5427. porcelain.commit(
  5428. repo=self.repo.path,
  5429. message=b"test2",
  5430. author=b"test2 <email>",
  5431. committer=b"test2 <email>",
  5432. )
  5433. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  5434. target_config = target_repo.get_config()
  5435. target_config.set(
  5436. (b"remote", remote_name.encode()), b"url", self.repo.path.encode()
  5437. )
  5438. target_repo.close()
  5439. # Fetch changes into the cloned repo
  5440. porcelain.fetch(
  5441. target_path, remote_name, outstream=outstream, errstream=errstream
  5442. )
  5443. # Assert that fetch updated the local image of the remote
  5444. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  5445. # Check the target repo for pushed changes, as well as updates
  5446. # for the refs
  5447. with Repo(target_path) as r:
  5448. self.assertIn(self.repo[b"HEAD"].id, r)
  5449. self.assertNotEqual(self.repo.get_refs(), target_refs)
  5450. def assert_correct_remote_refs(
  5451. self, local_refs, remote_refs, remote_name=b"origin"
  5452. ) -> None:
  5453. """Assert that known remote refs corresponds to actual remote refs."""
  5454. local_ref_prefix = b"refs/heads"
  5455. remote_ref_prefix = b"refs/remotes/" + remote_name
  5456. locally_known_remote_refs = {
  5457. k[len(remote_ref_prefix) + 1 :]: v
  5458. for k, v in local_refs.items()
  5459. if k.startswith(remote_ref_prefix)
  5460. }
  5461. normalized_remote_refs = {
  5462. k[len(local_ref_prefix) + 1 :]: v
  5463. for k, v in remote_refs.items()
  5464. if k.startswith(local_ref_prefix)
  5465. }
  5466. if b"HEAD" in locally_known_remote_refs and b"HEAD" in remote_refs:
  5467. normalized_remote_refs[b"HEAD"] = remote_refs[b"HEAD"]
  5468. self.assertEqual(locally_known_remote_refs, normalized_remote_refs)
  5469. class RepackTests(PorcelainTestCase):
  5470. def test_empty(self) -> None:
  5471. porcelain.repack(self.repo)
  5472. def test_simple(self) -> None:
  5473. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  5474. os.close(handle)
  5475. porcelain.add(repo=self.repo.path, paths=fullpath)
  5476. porcelain.repack(self.repo)
  5477. class LsTreeTests(PorcelainTestCase):
  5478. def test_empty(self) -> None:
  5479. porcelain.commit(
  5480. repo=self.repo.path,
  5481. message=b"test status",
  5482. author=b"author <email>",
  5483. committer=b"committer <email>",
  5484. )
  5485. f = StringIO()
  5486. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  5487. self.assertEqual(f.getvalue(), "")
  5488. def test_simple(self) -> None:
  5489. # Commit a dummy file then modify it
  5490. fullpath = os.path.join(self.repo.path, "foo")
  5491. with open(fullpath, "w") as f:
  5492. f.write("origstuff")
  5493. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5494. porcelain.commit(
  5495. repo=self.repo.path,
  5496. message=b"test status",
  5497. author=b"author <email>",
  5498. committer=b"committer <email>",
  5499. )
  5500. output = StringIO()
  5501. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  5502. self.assertEqual(
  5503. output.getvalue(),
  5504. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n",
  5505. )
  5506. def test_recursive(self) -> None:
  5507. # Create a directory then write a dummy file in it
  5508. dirpath = os.path.join(self.repo.path, "adir")
  5509. filepath = os.path.join(dirpath, "afile")
  5510. os.mkdir(dirpath)
  5511. with open(filepath, "w") as f:
  5512. f.write("origstuff")
  5513. porcelain.add(repo=self.repo.path, paths=[filepath])
  5514. porcelain.commit(
  5515. repo=self.repo.path,
  5516. message=b"test status",
  5517. author=b"author <email>",
  5518. committer=b"committer <email>",
  5519. )
  5520. output = StringIO()
  5521. porcelain.ls_tree(self.repo, b"HEAD", outstream=output)
  5522. self.assertEqual(
  5523. output.getvalue(),
  5524. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n",
  5525. )
  5526. output2 = StringIO()
  5527. porcelain.ls_tree(self.repo, b"HEAD", outstream=output2, recursive=True)
  5528. self.assertEqual(
  5529. output2.getvalue(),
  5530. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n"
  5531. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir"
  5532. "/afile\n",
  5533. )
  5534. class LsRemoteTests(PorcelainTestCase):
  5535. def test_empty(self) -> None:
  5536. result = porcelain.ls_remote(self.repo.path)
  5537. self.assertEqual({}, result.refs)
  5538. self.assertEqual({}, result.symrefs)
  5539. def test_some(self) -> None:
  5540. cid = porcelain.commit(
  5541. repo=self.repo.path,
  5542. message=b"test status",
  5543. author=b"author <email>",
  5544. committer=b"committer <email>",
  5545. )
  5546. result = porcelain.ls_remote(self.repo.path)
  5547. self.assertEqual(
  5548. {b"refs/heads/master": cid, b"HEAD": cid},
  5549. result.refs,
  5550. )
  5551. # HEAD should be a symref to refs/heads/master
  5552. self.assertEqual({b"HEAD": b"refs/heads/master"}, result.symrefs)
  5553. class LsFilesTests(PorcelainTestCase):
  5554. def test_empty(self) -> None:
  5555. self.assertEqual([], list(porcelain.ls_files(self.repo)))
  5556. def test_simple(self) -> None:
  5557. # Commit a dummy file then modify it
  5558. fullpath = os.path.join(self.repo.path, "foo")
  5559. with open(fullpath, "w") as f:
  5560. f.write("origstuff")
  5561. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5562. self.assertEqual([b"foo"], list(porcelain.ls_files(self.repo)))
  5563. class RemoteAddTests(PorcelainTestCase):
  5564. def test_new(self) -> None:
  5565. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  5566. c = self.repo.get_config()
  5567. self.assertEqual(
  5568. c.get((b"remote", b"jelmer"), b"url"),
  5569. b"git://jelmer.uk/code/dulwich",
  5570. )
  5571. def test_exists(self) -> None:
  5572. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  5573. self.assertRaises(
  5574. porcelain.RemoteExists,
  5575. porcelain.remote_add,
  5576. self.repo,
  5577. "jelmer",
  5578. "git://jelmer.uk/code/dulwich",
  5579. )
  5580. class RemoteRemoveTests(PorcelainTestCase):
  5581. def test_remove(self) -> None:
  5582. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  5583. c = self.repo.get_config()
  5584. self.assertEqual(
  5585. c.get((b"remote", b"jelmer"), b"url"),
  5586. b"git://jelmer.uk/code/dulwich",
  5587. )
  5588. porcelain.remote_remove(self.repo, "jelmer")
  5589. self.assertRaises(KeyError, porcelain.remote_remove, self.repo, "jelmer")
  5590. c = self.repo.get_config()
  5591. self.assertRaises(KeyError, c.get, (b"remote", b"jelmer"), b"url")
  5592. class CheckIgnoreTests(PorcelainTestCase):
  5593. def test_check_ignored(self) -> None:
  5594. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5595. f.write("foo")
  5596. foo_path = os.path.join(self.repo.path, "foo")
  5597. with open(foo_path, "w") as f:
  5598. f.write("BAR")
  5599. bar_path = os.path.join(self.repo.path, "bar")
  5600. with open(bar_path, "w") as f:
  5601. f.write("BAR")
  5602. self.assertEqual(["foo"], list(porcelain.check_ignore(self.repo, [foo_path])))
  5603. self.assertEqual([], list(porcelain.check_ignore(self.repo, [bar_path])))
  5604. def test_check_added_abs(self) -> None:
  5605. path = os.path.join(self.repo.path, "foo")
  5606. with open(path, "w") as f:
  5607. f.write("BAR")
  5608. self.repo.stage(["foo"])
  5609. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5610. f.write("foo\n")
  5611. self.assertEqual([], list(porcelain.check_ignore(self.repo, [path])))
  5612. self.assertEqual(
  5613. ["foo"],
  5614. list(porcelain.check_ignore(self.repo, [path], no_index=True)),
  5615. )
  5616. def test_check_added_rel(self) -> None:
  5617. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  5618. f.write("BAR")
  5619. self.repo.stage(["foo"])
  5620. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  5621. f.write("foo\n")
  5622. cwd = os.getcwd()
  5623. self.addCleanup(os.chdir, cwd)
  5624. os.mkdir(os.path.join(self.repo.path, "bar"))
  5625. os.chdir(os.path.join(self.repo.path, "bar"))
  5626. self.assertEqual(list(porcelain.check_ignore(self.repo, ["../foo"])), [])
  5627. self.assertEqual(
  5628. ["../foo"],
  5629. list(porcelain.check_ignore(self.repo, ["../foo"], no_index=True)),
  5630. )
  5631. class UpdateHeadTests(PorcelainTestCase):
  5632. def test_set_to_branch(self) -> None:
  5633. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5634. self.repo.refs[b"refs/heads/blah"] = c1.id
  5635. porcelain.update_head(self.repo, "blah")
  5636. self.assertEqual(c1.id, self.repo.head())
  5637. self.assertEqual(b"ref: refs/heads/blah", self.repo.refs.read_ref(b"HEAD"))
  5638. def test_set_to_branch_detached(self) -> None:
  5639. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5640. self.repo.refs[b"refs/heads/blah"] = c1.id
  5641. porcelain.update_head(self.repo, "blah", detached=True)
  5642. self.assertEqual(c1.id, self.repo.head())
  5643. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  5644. def test_set_to_commit_detached(self) -> None:
  5645. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5646. self.repo.refs[b"refs/heads/blah"] = c1.id
  5647. porcelain.update_head(self.repo, c1.id, detached=True)
  5648. self.assertEqual(c1.id, self.repo.head())
  5649. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  5650. def test_set_new_branch(self) -> None:
  5651. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  5652. self.repo.refs[b"refs/heads/blah"] = c1.id
  5653. porcelain.update_head(self.repo, "blah", new_branch="bar")
  5654. self.assertEqual(c1.id, self.repo.head())
  5655. self.assertEqual(b"ref: refs/heads/bar", self.repo.refs.read_ref(b"HEAD"))
  5656. class MailmapTests(PorcelainTestCase):
  5657. def test_no_mailmap(self) -> None:
  5658. self.assertEqual(
  5659. b"Jelmer Vernooij <jelmer@samba.org>",
  5660. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  5661. )
  5662. def test_mailmap_lookup(self) -> None:
  5663. with open(os.path.join(self.repo.path, ".mailmap"), "wb") as f:
  5664. f.write(
  5665. b"""\
  5666. Jelmer Vernooij <jelmer@debian.org>
  5667. """
  5668. )
  5669. self.assertEqual(
  5670. b"Jelmer Vernooij <jelmer@debian.org>",
  5671. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  5672. )
  5673. class FsckTests(PorcelainTestCase):
  5674. def test_none(self) -> None:
  5675. self.assertEqual([], list(porcelain.fsck(self.repo)))
  5676. def test_git_dir(self) -> None:
  5677. obj = Tree()
  5678. a = Blob()
  5679. a.data = b"foo"
  5680. obj.add(b".git", 0o100644, a.id)
  5681. self.repo.object_store.add_objects([(a, None), (obj, None)])
  5682. self.assertEqual(
  5683. [(obj.id, "invalid name .git")],
  5684. [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)],
  5685. )
  5686. class DescribeTests(PorcelainTestCase):
  5687. def test_no_commits(self) -> None:
  5688. self.assertRaises(KeyError, porcelain.describe, self.repo.path)
  5689. def test_single_commit(self) -> None:
  5690. fullpath = os.path.join(self.repo.path, "foo")
  5691. with open(fullpath, "w") as f:
  5692. f.write("BAR")
  5693. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5694. sha = porcelain.commit(
  5695. self.repo.path,
  5696. message=b"Some message",
  5697. author=b"Joe <joe@example.com>",
  5698. committer=b"Bob <bob@example.com>",
  5699. )
  5700. self.assertEqual(
  5701. "g{}".format(sha[:7].decode("ascii")),
  5702. porcelain.describe(self.repo.path),
  5703. )
  5704. def test_tag(self) -> None:
  5705. fullpath = os.path.join(self.repo.path, "foo")
  5706. with open(fullpath, "w") as f:
  5707. f.write("BAR")
  5708. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5709. porcelain.commit(
  5710. self.repo.path,
  5711. message=b"Some message",
  5712. author=b"Joe <joe@example.com>",
  5713. committer=b"Bob <bob@example.com>",
  5714. )
  5715. porcelain.tag_create(
  5716. self.repo.path,
  5717. b"tryme",
  5718. b"foo <foo@bar.com>",
  5719. b"bar",
  5720. annotated=True,
  5721. )
  5722. self.assertEqual("tryme", porcelain.describe(self.repo.path))
  5723. def test_tag_and_commit(self) -> None:
  5724. fullpath = os.path.join(self.repo.path, "foo")
  5725. with open(fullpath, "w") as f:
  5726. f.write("BAR")
  5727. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5728. porcelain.commit(
  5729. self.repo.path,
  5730. message=b"Some message",
  5731. author=b"Joe <joe@example.com>",
  5732. committer=b"Bob <bob@example.com>",
  5733. )
  5734. porcelain.tag_create(
  5735. self.repo.path,
  5736. b"tryme",
  5737. b"foo <foo@bar.com>",
  5738. b"bar",
  5739. annotated=True,
  5740. )
  5741. with open(fullpath, "w") as f:
  5742. f.write("BAR2")
  5743. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5744. sha = porcelain.commit(
  5745. self.repo.path,
  5746. message=b"Some message",
  5747. author=b"Joe <joe@example.com>",
  5748. committer=b"Bob <bob@example.com>",
  5749. )
  5750. self.assertEqual(
  5751. "tryme-1-g{}".format(sha[:7].decode("ascii")),
  5752. porcelain.describe(self.repo.path),
  5753. )
  5754. def test_tag_and_commit_full(self) -> None:
  5755. fullpath = os.path.join(self.repo.path, "foo")
  5756. with open(fullpath, "w") as f:
  5757. f.write("BAR")
  5758. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5759. porcelain.commit(
  5760. self.repo.path,
  5761. message=b"Some message",
  5762. author=b"Joe <joe@example.com>",
  5763. committer=b"Bob <bob@example.com>",
  5764. )
  5765. porcelain.tag_create(
  5766. self.repo.path,
  5767. b"tryme",
  5768. b"foo <foo@bar.com>",
  5769. b"bar",
  5770. annotated=True,
  5771. )
  5772. with open(fullpath, "w") as f:
  5773. f.write("BAR2")
  5774. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5775. sha = porcelain.commit(
  5776. self.repo.path,
  5777. message=b"Some message",
  5778. author=b"Joe <joe@example.com>",
  5779. committer=b"Bob <bob@example.com>",
  5780. )
  5781. self.assertEqual(
  5782. "tryme-1-g{}".format(sha.decode("ascii")),
  5783. porcelain.describe(self.repo.path, abbrev=40),
  5784. )
  5785. def test_untagged_commit_abbreviation(self) -> None:
  5786. _, _, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]])
  5787. self.repo.refs[b"HEAD"] = c3.id
  5788. brief_description, complete_description = (
  5789. porcelain.describe(self.repo),
  5790. porcelain.describe(self.repo, abbrev=40),
  5791. )
  5792. self.assertTrue(complete_description.startswith(brief_description))
  5793. self.assertEqual(
  5794. "g{}".format(c3.id.decode("ascii")),
  5795. complete_description,
  5796. )
  5797. def test_hash_length_dynamic(self) -> None:
  5798. """Test that hash length adjusts based on uniqueness."""
  5799. fullpath = os.path.join(self.repo.path, "foo")
  5800. with open(fullpath, "w") as f:
  5801. f.write("content")
  5802. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5803. sha = porcelain.commit(
  5804. self.repo.path,
  5805. message=b"commit",
  5806. author=b"Joe <joe@example.com>",
  5807. committer=b"Bob <bob@example.com>",
  5808. )
  5809. # When abbrev is None, it should use find_unique_abbrev
  5810. result = porcelain.describe(self.repo.path)
  5811. # Should start with 'g' and have at least 7 characters
  5812. self.assertTrue(result.startswith("g"))
  5813. self.assertGreaterEqual(len(result[1:]), 7)
  5814. # Should be a prefix of the full SHA
  5815. self.assertTrue(sha.decode("ascii").startswith(result[1:]))
  5816. class PathToTreeTests(PorcelainTestCase):
  5817. def setUp(self) -> None:
  5818. super().setUp()
  5819. self.fp = os.path.join(self.test_dir, "bar")
  5820. with open(self.fp, "w") as f:
  5821. f.write("something")
  5822. oldcwd = os.getcwd()
  5823. self.addCleanup(os.chdir, oldcwd)
  5824. os.chdir(self.test_dir)
  5825. def test_path_to_tree_path_base(self) -> None:
  5826. self.assertEqual(b"bar", porcelain.path_to_tree_path(self.test_dir, self.fp))
  5827. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  5828. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "bar"))
  5829. cwd = os.getcwd()
  5830. self.assertEqual(
  5831. b"bar", porcelain.path_to_tree_path(".", os.path.join(cwd, "bar"))
  5832. )
  5833. self.assertEqual(b"bar", porcelain.path_to_tree_path(cwd, "bar"))
  5834. def test_path_to_tree_path_syntax(self) -> None:
  5835. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  5836. def test_path_to_tree_path_error(self) -> None:
  5837. with self.assertRaises(ValueError):
  5838. with tempfile.TemporaryDirectory() as od:
  5839. porcelain.path_to_tree_path(od, self.fp)
  5840. def test_path_to_tree_path_rel(self) -> None:
  5841. cwd = os.getcwd()
  5842. self.addCleanup(os.chdir, cwd)
  5843. os.mkdir(os.path.join(self.repo.path, "foo"))
  5844. os.mkdir(os.path.join(self.repo.path, "foo/bar"))
  5845. os.chdir(os.path.join(self.repo.path, "foo/bar"))
  5846. with open("baz", "w") as f:
  5847. f.write("contents")
  5848. self.assertEqual(b"bar/baz", porcelain.path_to_tree_path("..", "baz"))
  5849. self.assertEqual(
  5850. b"bar/baz",
  5851. porcelain.path_to_tree_path(
  5852. os.path.join(os.getcwd(), ".."),
  5853. os.path.join(os.getcwd(), "baz"),
  5854. ),
  5855. )
  5856. self.assertEqual(
  5857. b"bar/baz",
  5858. porcelain.path_to_tree_path("..", os.path.join(os.getcwd(), "baz")),
  5859. )
  5860. self.assertEqual(
  5861. b"bar/baz",
  5862. porcelain.path_to_tree_path(os.path.join(os.getcwd(), ".."), "baz"),
  5863. )
  5864. class GetObjectByPathTests(PorcelainTestCase):
  5865. def test_simple(self) -> None:
  5866. fullpath = os.path.join(self.repo.path, "foo")
  5867. with open(fullpath, "w") as f:
  5868. f.write("BAR")
  5869. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5870. porcelain.commit(
  5871. self.repo.path,
  5872. message=b"Some message",
  5873. author=b"Joe <joe@example.com>",
  5874. committer=b"Bob <bob@example.com>",
  5875. )
  5876. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  5877. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  5878. def test_encoding(self) -> None:
  5879. fullpath = os.path.join(self.repo.path, "foo")
  5880. with open(fullpath, "w") as f:
  5881. f.write("BAR")
  5882. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5883. porcelain.commit(
  5884. self.repo.path,
  5885. message=b"Some message",
  5886. author=b"Joe <joe@example.com>",
  5887. committer=b"Bob <bob@example.com>",
  5888. encoding=b"utf-8",
  5889. )
  5890. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  5891. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  5892. def test_missing(self) -> None:
  5893. self.assertRaises(KeyError, porcelain.get_object_by_path, self.repo, "foo")
  5894. class WriteTreeTests(PorcelainTestCase):
  5895. def test_simple(self) -> None:
  5896. fullpath = os.path.join(self.repo.path, "foo")
  5897. with open(fullpath, "w") as f:
  5898. f.write("BAR")
  5899. porcelain.add(repo=self.repo.path, paths=[fullpath])
  5900. self.assertEqual(
  5901. b"d2092c8a9f311f0311083bf8d177f2ca0ab5b241",
  5902. porcelain.write_tree(self.repo),
  5903. )
  5904. class ActiveBranchTests(PorcelainTestCase):
  5905. def test_simple(self) -> None:
  5906. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  5907. class BranchTrackingTests(PorcelainTestCase):
  5908. def test_get_branch_merge(self) -> None:
  5909. # Set up branch tracking configuration
  5910. config = self.repo.get_config()
  5911. config.set((b"branch", b"master"), b"remote", b"origin")
  5912. config.set((b"branch", b"master"), b"merge", b"refs/heads/main")
  5913. config.write_to_path()
  5914. # Test getting merge ref for current branch
  5915. merge_ref = porcelain.get_branch_merge(self.repo)
  5916. self.assertEqual(b"refs/heads/main", merge_ref)
  5917. # Test getting merge ref for specific branch
  5918. merge_ref = porcelain.get_branch_merge(self.repo, b"master")
  5919. self.assertEqual(b"refs/heads/main", merge_ref)
  5920. # Test branch without merge config
  5921. with self.assertRaises(KeyError):
  5922. porcelain.get_branch_merge(self.repo, b"nonexistent")
  5923. def test_set_branch_tracking(self) -> None:
  5924. # Create a new branch
  5925. sha, _ = _commit_file_with_content(self.repo, "foo", "content\n")
  5926. porcelain.branch_create(self.repo, "feature")
  5927. # Set up tracking
  5928. porcelain.set_branch_tracking(
  5929. self.repo, b"feature", b"upstream", b"refs/heads/main"
  5930. )
  5931. # Verify configuration was written
  5932. config = self.repo.get_config()
  5933. self.assertEqual(b"upstream", config.get((b"branch", b"feature"), b"remote"))
  5934. self.assertEqual(
  5935. b"refs/heads/main", config.get((b"branch", b"feature"), b"merge")
  5936. )
  5937. class FindUniqueAbbrevTests(PorcelainTestCase):
  5938. def test_simple(self) -> None:
  5939. c1, c2, c3 = build_commit_graph(
  5940. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  5941. )
  5942. self.repo.refs[b"HEAD"] = c3.id
  5943. self.assertEqual(
  5944. c1.id.decode("ascii")[:7],
  5945. porcelain.find_unique_abbrev(self.repo.object_store, c1.id),
  5946. )
  5947. class PackRefsTests(PorcelainTestCase):
  5948. def test_all(self) -> None:
  5949. c1, c2, c3 = build_commit_graph(
  5950. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  5951. )
  5952. self.repo.refs[b"HEAD"] = c3.id
  5953. self.repo.refs[b"refs/heads/master"] = c2.id
  5954. self.repo.refs[b"refs/tags/foo"] = c1.id
  5955. porcelain.pack_refs(self.repo, all=True)
  5956. self.assertEqual(
  5957. self.repo.refs.get_packed_refs(),
  5958. {
  5959. b"refs/heads/master": c2.id,
  5960. b"refs/tags/foo": c1.id,
  5961. },
  5962. )
  5963. def test_not_all(self) -> None:
  5964. c1, c2, c3 = build_commit_graph(
  5965. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  5966. )
  5967. self.repo.refs[b"HEAD"] = c3.id
  5968. self.repo.refs[b"refs/heads/master"] = c2.id
  5969. self.repo.refs[b"refs/tags/foo"] = c1.id
  5970. porcelain.pack_refs(self.repo)
  5971. self.assertEqual(
  5972. self.repo.refs.get_packed_refs(),
  5973. {
  5974. b"refs/tags/foo": c1.id,
  5975. },
  5976. )
  5977. class ServerTests(PorcelainTestCase):
  5978. @contextlib.contextmanager
  5979. def _serving(self):
  5980. with make_server("localhost", 0, self.app) as server:
  5981. thread = threading.Thread(target=server.serve_forever, daemon=True)
  5982. thread.start()
  5983. try:
  5984. yield f"http://localhost:{server.server_port}"
  5985. finally:
  5986. server.shutdown()
  5987. thread.join(10)
  5988. def setUp(self) -> None:
  5989. super().setUp()
  5990. self.served_repo_path = os.path.join(self.test_dir, "served_repo.git")
  5991. self.served_repo = Repo.init_bare(self.served_repo_path, mkdir=True)
  5992. self.addCleanup(self.served_repo.close)
  5993. backend = DictBackend({"/": self.served_repo})
  5994. self.app = make_wsgi_chain(backend)
  5995. def test_pull(self) -> None:
  5996. (c1,) = build_commit_graph(self.served_repo.object_store, [[1]])
  5997. self.served_repo.refs[b"refs/heads/master"] = c1.id
  5998. with self._serving() as url:
  5999. porcelain.pull(self.repo, url, "master")
  6000. def test_push(self) -> None:
  6001. (c1,) = build_commit_graph(self.repo.object_store, [[1]])
  6002. self.repo.refs[b"refs/heads/master"] = c1.id
  6003. with self._serving() as url:
  6004. porcelain.push(self.repo, url, "master")
  6005. class ForEachTests(PorcelainTestCase):
  6006. def setUp(self) -> None:
  6007. super().setUp()
  6008. c1, c2, c3, c4 = build_commit_graph(
  6009. self.repo.object_store, [[1], [2, 1], [3, 1, 2], [4]]
  6010. )
  6011. porcelain.tag_create(
  6012. self.repo.path,
  6013. b"v0.1",
  6014. objectish=c1.id,
  6015. annotated=True,
  6016. message=b"0.1",
  6017. )
  6018. porcelain.tag_create(
  6019. self.repo.path,
  6020. b"v1.0",
  6021. objectish=c2.id,
  6022. annotated=True,
  6023. message=b"1.0",
  6024. )
  6025. porcelain.tag_create(self.repo.path, b"simple-tag", objectish=c3.id)
  6026. porcelain.tag_create(
  6027. self.repo.path,
  6028. b"v1.1",
  6029. objectish=c4.id,
  6030. annotated=True,
  6031. message=b"1.1",
  6032. )
  6033. porcelain.branch_create(
  6034. self.repo.path, b"feat", objectish=c2.id.decode("ascii")
  6035. )
  6036. self.repo.refs[b"HEAD"] = c4.id
  6037. def test_for_each_ref(self) -> None:
  6038. refs = porcelain.for_each_ref(self.repo)
  6039. self.assertEqual(
  6040. [(object_type, tag) for _, object_type, tag in refs],
  6041. [
  6042. (b"commit", b"refs/heads/feat"),
  6043. (b"commit", b"refs/heads/master"),
  6044. (b"commit", b"refs/tags/simple-tag"),
  6045. (b"tag", b"refs/tags/v0.1"),
  6046. (b"tag", b"refs/tags/v1.0"),
  6047. (b"tag", b"refs/tags/v1.1"),
  6048. ],
  6049. )
  6050. def test_for_each_ref_pattern(self) -> None:
  6051. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v*")
  6052. self.assertEqual(
  6053. [(object_type, tag) for _, object_type, tag in versions],
  6054. [
  6055. (b"tag", b"refs/tags/v0.1"),
  6056. (b"tag", b"refs/tags/v1.0"),
  6057. (b"tag", b"refs/tags/v1.1"),
  6058. ],
  6059. )
  6060. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v1.?")
  6061. self.assertEqual(
  6062. [(object_type, tag) for _, object_type, tag in versions],
  6063. [
  6064. (b"tag", b"refs/tags/v1.0"),
  6065. (b"tag", b"refs/tags/v1.1"),
  6066. ],
  6067. )
  6068. class SparseCheckoutTests(PorcelainTestCase):
  6069. """Integration tests for Dulwich's sparse checkout feature."""
  6070. # NOTE: We do NOT override `setUp()` here because the parent class
  6071. # (PorcelainTestCase) already:
  6072. # 1) Creates self.test_dir = a unique temp dir
  6073. # 2) Creates a subdir named "repo"
  6074. # 3) Calls Repo.init() on that path
  6075. # Re-initializing again caused FileExistsError.
  6076. #
  6077. # Utility/Placeholder
  6078. #
  6079. def sparse_checkout(self, repo, patterns, force=False):
  6080. """Wrapper around the actual porcelain.sparse_checkout function
  6081. to handle any test-specific setup or logging.
  6082. """
  6083. return porcelain.sparse_checkout(repo, patterns, force=force)
  6084. def _write_file(self, rel_path, content):
  6085. """Helper to write a file in the repository working tree."""
  6086. abs_path = os.path.join(self.repo_path, rel_path)
  6087. os.makedirs(os.path.dirname(abs_path), exist_ok=True)
  6088. with open(abs_path, "w") as f:
  6089. f.write(content)
  6090. return abs_path
  6091. def _commit_file(self, rel_path, content):
  6092. """Helper to write, add, and commit a file."""
  6093. abs_path = self._write_file(rel_path, content)
  6094. add(self.repo_path, paths=[abs_path])
  6095. commit(self.repo_path, message=b"Added " + rel_path.encode("utf-8"))
  6096. def _list_wtree_files(self):
  6097. """Return a set of all files (not dirs) present
  6098. in the working tree, ignoring .git/.
  6099. """
  6100. found_files = set()
  6101. for root, dirs, files in os.walk(self.repo_path):
  6102. # Skip .git in the walk
  6103. if ".git" in dirs:
  6104. dirs.remove(".git")
  6105. for filename in files:
  6106. file_rel = os.path.relpath(os.path.join(root, filename), self.repo_path)
  6107. found_files.add(file_rel)
  6108. return found_files
  6109. def test_only_included_paths_appear_in_wtree(self):
  6110. """Only included paths remain in the working tree, excluded paths are removed.
  6111. Commits two files, "keep_me.txt" and "exclude_me.txt". Then applies a
  6112. sparse-checkout pattern containing only "keep_me.txt". Ensures that
  6113. the latter remains in the working tree, while "exclude_me.txt" is
  6114. removed. This verifies correct application of sparse-checkout patterns
  6115. to remove files not listed.
  6116. """
  6117. self._commit_file("keep_me.txt", "I'll stay\n")
  6118. self._commit_file("exclude_me.txt", "I'll be excluded\n")
  6119. patterns = ["keep_me.txt"]
  6120. self.sparse_checkout(self.repo, patterns)
  6121. actual_files = self._list_wtree_files()
  6122. expected_files = {"keep_me.txt"}
  6123. self.assertEqual(
  6124. expected_files,
  6125. actual_files,
  6126. f"Expected only {expected_files}, but found {actual_files}",
  6127. )
  6128. def test_previously_included_paths_become_excluded(self):
  6129. """Previously included files become excluded after pattern changes.
  6130. Verifies that files initially brought into the working tree (e.g.,
  6131. by including `data/`) can later be excluded by narrowing the
  6132. sparse-checkout pattern to just `data/included_1.txt`. Confirms that
  6133. the file `data/included_2.txt` remains in the index with
  6134. skip-worktree set (rather than being removed entirely), ensuring
  6135. data is not lost and Dulwich correctly updates the index flags.
  6136. """
  6137. self._commit_file("data/included_1.txt", "some content\n")
  6138. self._commit_file("data/included_2.txt", "other content\n")
  6139. initial_patterns = ["data/"]
  6140. self.sparse_checkout(self.repo, initial_patterns)
  6141. updated_patterns = ["data/included_1.txt"]
  6142. self.sparse_checkout(self.repo, updated_patterns)
  6143. actual_files = self._list_wtree_files()
  6144. expected_files = {os.path.join("data", "included_1.txt")}
  6145. self.assertEqual(expected_files, actual_files)
  6146. idx = self.repo.open_index()
  6147. self.assertIn(b"data/included_2.txt", idx)
  6148. entry = idx[b"data/included_2.txt"]
  6149. self.assertTrue(entry.skip_worktree)
  6150. def test_force_removes_local_changes_for_excluded_paths(self):
  6151. """Forced sparse checkout removes local modifications for newly excluded paths.
  6152. Verifies that specifying force=True allows destructive operations
  6153. which discard uncommitted changes. First, we commit "file1.txt" and
  6154. then modify it. Next, we apply a pattern that excludes the file,
  6155. using force=True. The local modifications (and the file) should
  6156. be removed, leaving the working tree empty.
  6157. """
  6158. self._commit_file("file1.txt", "original content\n")
  6159. file1_path = os.path.join(self.repo_path, "file1.txt")
  6160. with open(file1_path, "a") as f:
  6161. f.write("local changes!\n")
  6162. new_patterns = ["some_other_file.txt"]
  6163. self.sparse_checkout(self.repo, new_patterns, force=True)
  6164. actual_files = self._list_wtree_files()
  6165. self.assertEqual(
  6166. set(),
  6167. actual_files,
  6168. "Force-sparse-checkout did not remove file with local changes.",
  6169. )
  6170. def test_destructive_refuse_uncommitted_changes_without_force(self):
  6171. """Fail on uncommitted changes for newly excluded paths without force.
  6172. Ensures that a sparse checkout is blocked if it would remove local
  6173. modifications from the working tree. We commit 'config.yaml', then
  6174. modify it, and finally attempt to exclude it via new patterns without
  6175. using force=True. This should raise a CheckoutError rather than
  6176. discarding the local changes.
  6177. """
  6178. self._commit_file("config.yaml", "initial\n")
  6179. cfg_path = os.path.join(self.repo_path, "config.yaml")
  6180. with open(cfg_path, "a") as f:
  6181. f.write("local modifications\n")
  6182. exclude_patterns = ["docs/"]
  6183. with self.assertRaises(CheckoutError):
  6184. self.sparse_checkout(self.repo, exclude_patterns, force=False)
  6185. def test_fnmatch_gitignore_pattern_expansion(self):
  6186. """Reading/writing patterns align with gitignore/fnmatch expansions.
  6187. Ensures that `sparse_checkout` interprets wildcard patterns (like `*.py`)
  6188. in the same way Git's sparse-checkout would. Multiple files are committed
  6189. to `src/` (e.g. `foo.py`, `foo_test.py`, `foo_helper.py`) and to `docs/`.
  6190. Then the pattern `src/foo*.py` is applied, confirming that only the
  6191. matching Python files remain in the working tree while the Markdown file
  6192. under `docs/` is excluded.
  6193. Finally, verifies that the `.git/info/sparse-checkout` file contains the
  6194. specified wildcard pattern (`src/foo*.py`), ensuring correct round-trip
  6195. of user-supplied patterns.
  6196. """
  6197. self._commit_file("src/foo.py", "print('hello')\n")
  6198. self._commit_file("src/foo_test.py", "print('test')\n")
  6199. self._commit_file("docs/readme.md", "# docs\n")
  6200. self._commit_file("src/foo_helper.py", "print('helper')\n")
  6201. patterns = ["src/foo*.py"]
  6202. self.sparse_checkout(self.repo, patterns)
  6203. actual_files = self._list_wtree_files()
  6204. expected_files = {
  6205. os.path.join("src", "foo.py"),
  6206. os.path.join("src", "foo_test.py"),
  6207. os.path.join("src", "foo_helper.py"),
  6208. }
  6209. self.assertEqual(
  6210. expected_files,
  6211. actual_files,
  6212. "Wildcard pattern not matched as expected. Either too strict or too broad.",
  6213. )
  6214. sc_file = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  6215. self.assertTrue(os.path.isfile(sc_file))
  6216. with open(sc_file) as f:
  6217. lines = f.read().strip().split()
  6218. self.assertIn("src/foo*.py", lines)
  6219. class ConeModeTests(PorcelainTestCase):
  6220. """Provide integration tests for Dulwich's cone mode sparse checkout.
  6221. This test suite verifies the expected behavior for:
  6222. * cone_mode_init
  6223. * cone_mode_set
  6224. * cone_mode_add
  6225. Although Dulwich does not yet implement cone mode, these tests are
  6226. prepared in advance to guide future development.
  6227. """
  6228. def setUp(self):
  6229. """Set up a fresh repository for each test.
  6230. This method creates a new empty repo_path and Repo object
  6231. as provided by the PorcelainTestCase base class.
  6232. """
  6233. super().setUp()
  6234. def _commit_file(self, rel_path, content=b"contents"):
  6235. """Add a file at the given relative path and commit it.
  6236. Creates necessary directories, writes the file content,
  6237. stages, and commits. The commit message and author/committer
  6238. are also provided.
  6239. """
  6240. full_path = os.path.join(self.repo_path, rel_path)
  6241. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  6242. with open(full_path, "wb") as f:
  6243. f.write(content)
  6244. porcelain.add(self.repo_path, paths=[full_path])
  6245. porcelain.commit(
  6246. self.repo_path,
  6247. message=b"Adding " + rel_path.encode("utf-8"),
  6248. author=b"Test Author <author@example.com>",
  6249. committer=b"Test Committer <committer@example.com>",
  6250. )
  6251. def _list_wtree_files(self):
  6252. """Return a set of all file paths relative to the repository root.
  6253. Walks the working tree, skipping the .git directory.
  6254. """
  6255. found_files = set()
  6256. for root, dirs, files in os.walk(self.repo_path):
  6257. if ".git" in dirs:
  6258. dirs.remove(".git")
  6259. for fn in files:
  6260. relp = os.path.relpath(os.path.join(root, fn), self.repo_path)
  6261. found_files.add(relp)
  6262. return found_files
  6263. def test_init_excludes_everything(self):
  6264. """Verify that cone_mode_init writes minimal patterns and empties the working tree.
  6265. Make some dummy files, commit them, then call cone_mode_init. Confirm
  6266. that the working tree is empty, the sparse-checkout file has the
  6267. minimal patterns (/*, !/*/), and the relevant config values are set.
  6268. """
  6269. self._commit_file("docs/readme.md", b"# doc\n")
  6270. self._commit_file("src/main.py", b"print('hello')\n")
  6271. porcelain.cone_mode_init(self.repo)
  6272. actual_files = self._list_wtree_files()
  6273. self.assertEqual(
  6274. set(),
  6275. actual_files,
  6276. "cone_mode_init did not exclude all files from the working tree.",
  6277. )
  6278. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  6279. with open(sp_path) as f:
  6280. lines = [ln.strip() for ln in f if ln.strip()]
  6281. self.assertIn("/*", lines)
  6282. self.assertIn("!/*/", lines)
  6283. config = self.repo.get_config()
  6284. self.assertEqual(config.get((b"core",), b"sparseCheckout"), b"true")
  6285. self.assertEqual(config.get((b"core",), b"sparseCheckoutCone"), b"true")
  6286. def test_set_specific_dirs(self):
  6287. """Verify that cone_mode_set overwrites the included directories to only the specified ones.
  6288. Initializes cone mode, commits some files, then calls cone_mode_set with
  6289. a list of directories. Expects that only those directories remain in the
  6290. working tree.
  6291. """
  6292. porcelain.cone_mode_init(self.repo)
  6293. self._commit_file("docs/readme.md", b"# doc\n")
  6294. self._commit_file("src/main.py", b"print('hello')\n")
  6295. self._commit_file("tests/test_foo.py", b"# tests\n")
  6296. # Everything is still excluded initially by init.
  6297. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  6298. actual_files = self._list_wtree_files()
  6299. expected_files = {
  6300. os.path.join("docs", "readme.md"),
  6301. os.path.join("src", "main.py"),
  6302. }
  6303. self.assertEqual(
  6304. expected_files,
  6305. actual_files,
  6306. "Did not see only the 'docs/' and 'src/' dirs in the working tree.",
  6307. )
  6308. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  6309. with open(sp_path) as f:
  6310. lines = [ln.strip() for ln in f if ln.strip()]
  6311. # For standard cone mode, we'd expect lines like:
  6312. # /* (include top-level files)
  6313. # !/*/ (exclude subdirectories)
  6314. # !/docs/ (re-include docs)
  6315. # !/src/ (re-include src)
  6316. # Instead of the wildcard-based lines the old test used.
  6317. self.assertIn("/*", lines)
  6318. self.assertIn("!/*/", lines)
  6319. self.assertIn("/docs/", lines)
  6320. self.assertIn("/src/", lines)
  6321. self.assertNotIn("/tests/", lines)
  6322. def test_set_overwrites_old_dirs(self):
  6323. """Ensure that calling cone_mode_set again overwrites old includes.
  6324. Initializes cone mode, includes two directories, then calls
  6325. cone_mode_set again with a different directory to confirm the
  6326. new set of includes replaces the old.
  6327. """
  6328. porcelain.cone_mode_init(self.repo)
  6329. self._commit_file("docs/readme.md")
  6330. self._commit_file("src/main.py")
  6331. self._commit_file("tests/test_bar.py")
  6332. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  6333. self.assertEqual(
  6334. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  6335. self._list_wtree_files(),
  6336. )
  6337. # Overwrite includes, now only 'tests'
  6338. porcelain.cone_mode_set(self.repo, dirs=["tests"], force=True)
  6339. actual_files = self._list_wtree_files()
  6340. expected_files = {os.path.join("tests", "test_bar.py")}
  6341. self.assertEqual(expected_files, actual_files)
  6342. def test_force_removal_of_local_mods(self):
  6343. """Confirm that force=True removes local changes in excluded paths.
  6344. cone_mode_init and cone_mode_set are called, a file is locally modified,
  6345. and then cone_mode_set is called again with force=True to exclude that path.
  6346. The excluded file should be removed with no CheckoutError.
  6347. """
  6348. porcelain.cone_mode_init(self.repo)
  6349. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  6350. self._commit_file("docs/readme.md", b"Docs stuff\n")
  6351. self._commit_file("src/main.py", b"print('hello')\n")
  6352. # Modify src/main.py
  6353. with open(os.path.join(self.repo_path, "src/main.py"), "ab") as f:
  6354. f.write(b"extra line\n")
  6355. # Exclude src/ with force=True
  6356. porcelain.cone_mode_set(self.repo, dirs=["docs"], force=True)
  6357. actual_files = self._list_wtree_files()
  6358. expected_files = {os.path.join("docs", "readme.md")}
  6359. self.assertEqual(expected_files, actual_files)
  6360. def test_add_and_merge_dirs(self):
  6361. """Verify that cone_mode_add merges new directories instead of overwriting them.
  6362. After initializing cone mode and including a single directory, call
  6363. cone_mode_add with a new directory. Confirm that both directories
  6364. remain included. Repeat for an additional directory to ensure it
  6365. is merged, not overwritten.
  6366. """
  6367. porcelain.cone_mode_init(self.repo)
  6368. self._commit_file("docs/readme.md", b"# doc\n")
  6369. self._commit_file("src/main.py", b"print('hello')\n")
  6370. self._commit_file("tests/test_bar.py", b"# tests\n")
  6371. # Include "docs" only
  6372. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  6373. self.assertEqual({os.path.join("docs", "readme.md")}, self._list_wtree_files())
  6374. # Add "src"
  6375. porcelain.cone_mode_add(self.repo, dirs=["src"])
  6376. actual_files = self._list_wtree_files()
  6377. self.assertEqual(
  6378. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  6379. actual_files,
  6380. )
  6381. # Add "tests" as well
  6382. porcelain.cone_mode_add(self.repo, dirs=["tests"])
  6383. actual_files = self._list_wtree_files()
  6384. expected_files = {
  6385. os.path.join("docs", "readme.md"),
  6386. os.path.join("src", "main.py"),
  6387. os.path.join("tests", "test_bar.py"),
  6388. }
  6389. self.assertEqual(expected_files, actual_files)
  6390. # Check .git/info/sparse-checkout
  6391. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  6392. with open(sp_path) as f:
  6393. lines = [ln.strip() for ln in f if ln.strip()]
  6394. # Standard cone mode lines:
  6395. # "/*" -> include top-level
  6396. # "!/*/" -> exclude subdirectories
  6397. # "!/docs/", "!/src/", "!/tests/" -> re-include the directories we added
  6398. self.assertIn("/*", lines)
  6399. self.assertIn("!/*/", lines)
  6400. self.assertIn("/docs/", lines)
  6401. self.assertIn("/src/", lines)
  6402. self.assertIn("/tests/", lines)
  6403. class UnpackObjectsTest(PorcelainTestCase):
  6404. def test_unpack_objects(self):
  6405. """Test unpacking objects from a pack file."""
  6406. # Create a test repository with some objects
  6407. b1 = Blob()
  6408. b1.data = b"test content 1"
  6409. b2 = Blob()
  6410. b2.data = b"test content 2"
  6411. # Add objects to the repo
  6412. self.repo.object_store.add_object(b1)
  6413. self.repo.object_store.add_object(b2)
  6414. # Create a pack file with these objects
  6415. pack_path = os.path.join(self.test_dir, "test_pack")
  6416. with (
  6417. open(pack_path + ".pack", "wb") as pack_f,
  6418. open(pack_path + ".idx", "wb") as idx_f,
  6419. ):
  6420. porcelain.pack_objects(
  6421. self.repo,
  6422. [b1.id, b2.id],
  6423. pack_f,
  6424. idx_f,
  6425. )
  6426. # Create a new repository to unpack into
  6427. target_repo_path = os.path.join(self.test_dir, "target_repo")
  6428. target_repo = Repo.init(target_repo_path, mkdir=True)
  6429. self.addCleanup(target_repo.close)
  6430. # Unpack the objects
  6431. count = porcelain.unpack_objects(pack_path + ".pack", target_repo_path)
  6432. # Verify the objects were unpacked
  6433. self.assertEqual(2, count)
  6434. self.assertIn(b1.id, target_repo.object_store)
  6435. self.assertIn(b2.id, target_repo.object_store)
  6436. # Verify the content is correct
  6437. unpacked_b1 = target_repo.object_store[b1.id]
  6438. unpacked_b2 = target_repo.object_store[b2.id]
  6439. self.assertEqual(b1.data, unpacked_b1.data)
  6440. self.assertEqual(b2.data, unpacked_b2.data)
  6441. class CountObjectsTests(PorcelainTestCase):
  6442. def test_count_objects_empty_repo(self):
  6443. """Test counting objects in an empty repository."""
  6444. stats = porcelain.count_objects(self.repo)
  6445. self.assertEqual(0, stats.count)
  6446. self.assertEqual(0, stats.size)
  6447. def test_count_objects_verbose_empty_repo(self):
  6448. """Test verbose counting in an empty repository."""
  6449. stats = porcelain.count_objects(self.repo, verbose=True)
  6450. self.assertEqual(0, stats.count)
  6451. self.assertEqual(0, stats.size)
  6452. self.assertEqual(0, stats.in_pack)
  6453. self.assertEqual(0, stats.packs)
  6454. self.assertEqual(0, stats.size_pack)
  6455. def test_count_objects_with_loose_objects(self):
  6456. """Test counting loose objects."""
  6457. # Create some loose objects
  6458. blob1 = make_object(Blob, data=b"data1")
  6459. blob2 = make_object(Blob, data=b"data2")
  6460. self.repo.object_store.add_object(blob1)
  6461. self.repo.object_store.add_object(blob2)
  6462. stats = porcelain.count_objects(self.repo)
  6463. self.assertEqual(2, stats.count)
  6464. self.assertGreater(stats.size, 0)
  6465. def test_count_objects_verbose_with_objects(self):
  6466. """Test verbose counting with both loose and packed objects."""
  6467. # Add some loose objects
  6468. for i in range(3):
  6469. blob = make_object(Blob, data=f"data{i}".encode())
  6470. self.repo.object_store.add_object(blob)
  6471. # Create a simple commit to have some objects in a pack
  6472. tree = Tree()
  6473. c1 = make_commit(tree=tree.id, message=b"Test commit")
  6474. self.repo.object_store.add_objects([(tree, None), (c1, None)])
  6475. self.repo.refs[b"HEAD"] = c1.id
  6476. # Repack to create a pack file
  6477. porcelain.repack(self.repo)
  6478. stats = porcelain.count_objects(self.repo, verbose=True)
  6479. # After repacking, loose objects might be cleaned up
  6480. self.assertIsInstance(stats.count, int)
  6481. self.assertIsInstance(stats.size, int)
  6482. self.assertGreater(stats.in_pack, 0) # Should have packed objects
  6483. self.assertGreater(stats.packs, 0) # Should have at least one pack
  6484. self.assertGreater(stats.size_pack, 0) # Pack should have size
  6485. # Verify it's the correct dataclass type
  6486. self.assertIsInstance(stats, CountObjectsResult)
  6487. class PruneTests(PorcelainTestCase):
  6488. def test_prune_removes_old_tempfiles(self):
  6489. """Test that prune removes old temporary files."""
  6490. # Create an old temporary file in the objects directory
  6491. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  6492. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_test")
  6493. with open(tmp_pack_path, "wb") as f:
  6494. f.write(b"old temporary data")
  6495. # Make it old
  6496. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  6497. os.utime(tmp_pack_path, (old_time, old_time))
  6498. # Run prune
  6499. porcelain.prune(self.repo.path)
  6500. # Verify the file was removed
  6501. self.assertFalse(os.path.exists(tmp_pack_path))
  6502. def test_prune_keeps_recent_tempfiles(self):
  6503. """Test that prune keeps recent temporary files."""
  6504. # Create a recent temporary file
  6505. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  6506. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_recent")
  6507. with open(tmp_pack_path, "wb") as f:
  6508. f.write(b"recent temporary data")
  6509. self.addCleanup(os.remove, tmp_pack_path)
  6510. # Run prune
  6511. porcelain.prune(self.repo.path)
  6512. # Verify the file was NOT removed
  6513. self.assertTrue(os.path.exists(tmp_pack_path))
  6514. def test_prune_with_custom_grace_period(self):
  6515. """Test prune with custom grace period."""
  6516. # Create a 1-hour-old temporary file
  6517. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  6518. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_1hour")
  6519. with open(tmp_pack_path, "wb") as f:
  6520. f.write(b"1 hour old data")
  6521. # Make it 1 hour old
  6522. old_time = time.time() - 3600
  6523. os.utime(tmp_pack_path, (old_time, old_time))
  6524. # Prune with 30-minute grace period should remove it
  6525. porcelain.prune(self.repo.path, grace_period=1800)
  6526. # Verify the file was removed
  6527. self.assertFalse(os.path.exists(tmp_pack_path))
  6528. def test_prune_dry_run(self):
  6529. """Test prune in dry-run mode."""
  6530. # Create an old temporary file
  6531. objects_dir = os.path.join(self.repo.path, ".git", "objects")
  6532. tmp_pack_path = os.path.join(objects_dir, "tmp_pack_dryrun")
  6533. with open(tmp_pack_path, "wb") as f:
  6534. f.write(b"old temporary data")
  6535. self.addCleanup(os.remove, tmp_pack_path)
  6536. # Make it old
  6537. old_time = time.time() - (DEFAULT_TEMPFILE_GRACE_PERIOD + 3600)
  6538. os.utime(tmp_pack_path, (old_time, old_time))
  6539. # Run prune in dry-run mode
  6540. porcelain.prune(self.repo.path, dry_run=True)
  6541. # Verify the file was NOT removed (dry run)
  6542. self.assertTrue(os.path.exists(tmp_pack_path))
  6543. class FilterBranchTests(PorcelainTestCase):
  6544. def setUp(self):
  6545. super().setUp()
  6546. # Create initial commits with different authors
  6547. from dulwich.objects import Commit, Tree
  6548. # Create actual tree and blob objects
  6549. tree = Tree()
  6550. self.repo.object_store.add_object(tree)
  6551. c1 = Commit()
  6552. c1.tree = tree.id
  6553. c1.parents = []
  6554. c1.author = b"Old Author <old@example.com>"
  6555. c1.author_time = 1000
  6556. c1.author_timezone = 0
  6557. c1.committer = b"Old Committer <old@example.com>"
  6558. c1.commit_time = 1000
  6559. c1.commit_timezone = 0
  6560. c1.message = b"Initial commit"
  6561. self.repo.object_store.add_object(c1)
  6562. c2 = Commit()
  6563. c2.tree = tree.id
  6564. c2.parents = [c1.id]
  6565. c2.author = b"Another Author <another@example.com>"
  6566. c2.author_time = 2000
  6567. c2.author_timezone = 0
  6568. c2.committer = b"Another Committer <another@example.com>"
  6569. c2.commit_time = 2000
  6570. c2.commit_timezone = 0
  6571. c2.message = b"Second commit\n\nWith body"
  6572. self.repo.object_store.add_object(c2)
  6573. c3 = Commit()
  6574. c3.tree = tree.id
  6575. c3.parents = [c2.id]
  6576. c3.author = b"Third Author <third@example.com>"
  6577. c3.author_time = 3000
  6578. c3.author_timezone = 0
  6579. c3.committer = b"Third Committer <third@example.com>"
  6580. c3.commit_time = 3000
  6581. c3.commit_timezone = 0
  6582. c3.message = b"Third commit"
  6583. self.repo.object_store.add_object(c3)
  6584. self.repo.refs[b"refs/heads/master"] = c3.id
  6585. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  6586. # Store IDs for test assertions
  6587. self.c1_id = c1.id
  6588. self.c2_id = c2.id
  6589. self.c3_id = c3.id
  6590. def test_filter_branch_author(self):
  6591. """Test filtering branch with author changes."""
  6592. def filter_author(author):
  6593. # Change all authors to "New Author"
  6594. return b"New Author <new@example.com>"
  6595. result = porcelain.filter_branch(
  6596. self.repo_path, "master", filter_author=filter_author
  6597. )
  6598. # Check that we have mappings for all commits
  6599. self.assertEqual(len(result), 3)
  6600. # Verify the branch ref was updated
  6601. new_head = self.repo.refs[b"refs/heads/master"]
  6602. self.assertNotEqual(new_head, self.c3_id)
  6603. # Verify the original ref was saved
  6604. original_ref = self.repo.refs[b"refs/original/refs/heads/master"]
  6605. self.assertEqual(original_ref, self.c3_id)
  6606. # Check that authors were updated
  6607. new_commit = self.repo[new_head]
  6608. self.assertEqual(new_commit.author, b"New Author <new@example.com>")
  6609. # Check parent chain
  6610. parent = self.repo[new_commit.parents[0]]
  6611. self.assertEqual(parent.author, b"New Author <new@example.com>")
  6612. def test_filter_branch_message(self):
  6613. """Test filtering branch with message changes."""
  6614. def filter_message(message):
  6615. # Add prefix to all messages
  6616. return b"[FILTERED] " + message
  6617. porcelain.filter_branch(self.repo_path, "master", filter_message=filter_message)
  6618. # Verify messages were updated
  6619. new_head = self.repo.refs[b"refs/heads/master"]
  6620. new_commit = self.repo[new_head]
  6621. self.assertTrue(new_commit.message.startswith(b"[FILTERED] "))
  6622. def test_filter_branch_custom_filter(self):
  6623. """Test filtering branch with custom filter function."""
  6624. def custom_filter(commit):
  6625. # Change both author and message
  6626. return {
  6627. "author": b"Custom Author <custom@example.com>",
  6628. "message": b"Custom: " + commit.message,
  6629. }
  6630. porcelain.filter_branch(self.repo_path, "master", filter_fn=custom_filter)
  6631. # Verify custom filter was applied
  6632. new_head = self.repo.refs[b"refs/heads/master"]
  6633. new_commit = self.repo[new_head]
  6634. self.assertEqual(new_commit.author, b"Custom Author <custom@example.com>")
  6635. self.assertTrue(new_commit.message.startswith(b"Custom: "))
  6636. def test_filter_branch_no_changes(self):
  6637. """Test filtering branch with no changes."""
  6638. result = porcelain.filter_branch(self.repo_path, "master")
  6639. # All commits should map to themselves
  6640. for old_sha, new_sha in result.items():
  6641. self.assertEqual(old_sha, new_sha)
  6642. # HEAD should be unchanged
  6643. self.assertEqual(self.repo.refs[b"refs/heads/master"], self.c3_id)
  6644. def test_filter_branch_force(self):
  6645. """Test force filtering a previously filtered branch."""
  6646. # First filter
  6647. porcelain.filter_branch(
  6648. self.repo_path, "master", filter_message=lambda m: b"First: " + m
  6649. )
  6650. # Try again without force - should fail
  6651. with self.assertRaises(porcelain.Error):
  6652. porcelain.filter_branch(
  6653. self.repo_path, "master", filter_message=lambda m: b"Second: " + m
  6654. )
  6655. # Try again with force - should succeed
  6656. porcelain.filter_branch(
  6657. self.repo_path,
  6658. "master",
  6659. filter_message=lambda m: b"Second: " + m,
  6660. force=True,
  6661. )
  6662. # Verify second filter was applied
  6663. new_head = self.repo.refs[b"refs/heads/master"]
  6664. new_commit = self.repo[new_head]
  6665. self.assertTrue(new_commit.message.startswith(b"Second: First: "))
  6666. class StashTests(PorcelainTestCase):
  6667. def setUp(self) -> None:
  6668. super().setUp()
  6669. # Create initial commit
  6670. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  6671. f.write(b"initial content")
  6672. porcelain.add(repo=self.repo.path, paths=["initial.txt"])
  6673. porcelain.commit(
  6674. repo=self.repo.path,
  6675. message=b"Initial commit",
  6676. author=b"Test Author <test@example.com>",
  6677. committer=b"Test Committer <test@example.com>",
  6678. )
  6679. def test_stash_push_and_pop(self) -> None:
  6680. # Create a new file and stage it
  6681. new_file = os.path.join(self.repo.path, "new.txt")
  6682. with open(new_file, "wb") as f:
  6683. f.write(b"new file content")
  6684. porcelain.add(repo=self.repo.path, paths=["new.txt"])
  6685. # Modify existing file
  6686. with open(os.path.join(self.repo.path, "initial.txt"), "wb") as f:
  6687. f.write(b"modified content")
  6688. # Push to stash
  6689. porcelain.stash_push(self.repo.path)
  6690. # Verify files are reset
  6691. self.assertFalse(os.path.exists(new_file))
  6692. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  6693. self.assertEqual(b"initial content", f.read())
  6694. # Pop the stash
  6695. porcelain.stash_pop(self.repo.path)
  6696. # Verify files are restored
  6697. self.assertTrue(os.path.exists(new_file))
  6698. with open(new_file, "rb") as f:
  6699. self.assertEqual(b"new file content", f.read())
  6700. with open(os.path.join(self.repo.path, "initial.txt"), "rb") as f:
  6701. self.assertEqual(b"modified content", f.read())
  6702. # Verify new file is in the index
  6703. from dulwich.index import Index
  6704. index = Index(os.path.join(self.repo.path, ".git", "index"))
  6705. self.assertIn(b"new.txt", index)
  6706. def test_stash_list(self) -> None:
  6707. # Initially no stashes
  6708. stashes = list(porcelain.stash_list(self.repo.path))
  6709. self.assertEqual(0, len(stashes))
  6710. # Create a file and stash it
  6711. test_file = os.path.join(self.repo.path, "test.txt")
  6712. with open(test_file, "wb") as f:
  6713. f.write(b"test content")
  6714. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  6715. # Push first stash
  6716. porcelain.stash_push(self.repo.path)
  6717. # Create another file and stash it
  6718. test_file2 = os.path.join(self.repo.path, "test2.txt")
  6719. with open(test_file2, "wb") as f:
  6720. f.write(b"test content 2")
  6721. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  6722. # Push second stash
  6723. porcelain.stash_push(self.repo.path)
  6724. # Check stash list
  6725. stashes = list(porcelain.stash_list(self.repo.path))
  6726. self.assertEqual(2, len(stashes))
  6727. # Stashes are returned in order (most recent first)
  6728. self.assertEqual(0, stashes[0][0])
  6729. self.assertEqual(1, stashes[1][0])
  6730. def test_stash_drop(self) -> None:
  6731. # Create and stash some changes
  6732. test_file = os.path.join(self.repo.path, "test.txt")
  6733. with open(test_file, "wb") as f:
  6734. f.write(b"test content")
  6735. porcelain.add(repo=self.repo.path, paths=["test.txt"])
  6736. porcelain.stash_push(self.repo.path)
  6737. # Create another stash
  6738. test_file2 = os.path.join(self.repo.path, "test2.txt")
  6739. with open(test_file2, "wb") as f:
  6740. f.write(b"test content 2")
  6741. porcelain.add(repo=self.repo.path, paths=["test2.txt"])
  6742. porcelain.stash_push(self.repo.path)
  6743. # Verify we have 2 stashes
  6744. stashes = list(porcelain.stash_list(self.repo.path))
  6745. self.assertEqual(2, len(stashes))
  6746. # Drop the first stash (index 0)
  6747. porcelain.stash_drop(self.repo.path, 0)
  6748. # Verify we have 1 stash left
  6749. stashes = list(porcelain.stash_list(self.repo.path))
  6750. self.assertEqual(1, len(stashes))
  6751. # The remaining stash should be the one we created first
  6752. # Pop it and verify it's the first file
  6753. porcelain.stash_pop(self.repo.path)
  6754. self.assertTrue(os.path.exists(test_file))
  6755. self.assertFalse(os.path.exists(test_file2))
  6756. def test_stash_pop_empty(self) -> None:
  6757. # Attempting to pop from empty stash should raise an error
  6758. with self.assertRaises(IndexError):
  6759. porcelain.stash_pop(self.repo.path)
  6760. def test_stash_with_untracked_files(self) -> None:
  6761. # Create an untracked file
  6762. untracked_file = os.path.join(self.repo.path, "untracked.txt")
  6763. with open(untracked_file, "wb") as f:
  6764. f.write(b"untracked content")
  6765. # Create a tracked change
  6766. tracked_file = os.path.join(self.repo.path, "tracked.txt")
  6767. with open(tracked_file, "wb") as f:
  6768. f.write(b"tracked content")
  6769. porcelain.add(repo=self.repo.path, paths=["tracked.txt"])
  6770. # Stash (by default, untracked files are not included)
  6771. porcelain.stash_push(self.repo.path)
  6772. # Untracked file should still exist
  6773. self.assertTrue(os.path.exists(untracked_file))
  6774. # Tracked file should be gone
  6775. self.assertFalse(os.path.exists(tracked_file))
  6776. # Pop the stash
  6777. porcelain.stash_pop(self.repo.path)
  6778. # Tracked file should be restored
  6779. self.assertTrue(os.path.exists(tracked_file))
  6780. class BisectTests(PorcelainTestCase):
  6781. """Tests for bisect porcelain functions."""
  6782. def test_bisect_start(self):
  6783. """Test starting a bisect session."""
  6784. # Create some commits
  6785. c1, c2, c3 = build_commit_graph(
  6786. self.repo.object_store,
  6787. [[1], [2, 1], [3, 2]],
  6788. attrs={
  6789. 1: {"message": b"initial"},
  6790. 2: {"message": b"second"},
  6791. 3: {"message": b"third"},
  6792. },
  6793. )
  6794. self.repo.refs[b"refs/heads/master"] = c3.id
  6795. self.repo.refs[b"HEAD"] = c3.id
  6796. # Start bisect
  6797. porcelain.bisect_start(self.repo_path)
  6798. # Check that bisect state files exist
  6799. self.assertTrue(
  6800. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  6801. )
  6802. self.assertTrue(
  6803. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_TERMS"))
  6804. )
  6805. self.assertTrue(
  6806. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_NAMES"))
  6807. )
  6808. self.assertTrue(
  6809. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_LOG"))
  6810. )
  6811. def test_bisect_workflow(self):
  6812. """Test a complete bisect workflow."""
  6813. # Create some commits
  6814. c1, c2, c3, c4 = build_commit_graph(
  6815. self.repo.object_store,
  6816. [[1], [2, 1], [3, 2], [4, 3]],
  6817. attrs={
  6818. 1: {"message": b"good commit 1"},
  6819. 2: {"message": b"good commit 2"},
  6820. 3: {"message": b"bad commit"},
  6821. 4: {"message": b"bad commit 2"},
  6822. },
  6823. )
  6824. self.repo.refs[b"refs/heads/master"] = c4.id
  6825. self.repo.refs[b"HEAD"] = c4.id
  6826. # Start bisect with bad and good
  6827. next_sha = porcelain.bisect_start(self.repo_path, bad=c4.id, good=c1.id)
  6828. # Should return the middle commit
  6829. self.assertIsNotNone(next_sha)
  6830. self.assertIn(next_sha, [c2.id, c3.id])
  6831. # Mark the middle commit as good or bad
  6832. if next_sha == c2.id:
  6833. # c2 is good, next should be c3
  6834. next_sha = porcelain.bisect_good(self.repo_path)
  6835. self.assertEqual(next_sha, c3.id)
  6836. # Mark c3 as bad - bisect complete
  6837. next_sha = porcelain.bisect_bad(self.repo_path)
  6838. self.assertIsNone(next_sha)
  6839. else:
  6840. # c3 is bad, next should be c2
  6841. next_sha = porcelain.bisect_bad(self.repo_path)
  6842. self.assertEqual(next_sha, c2.id)
  6843. # Mark c2 as good - bisect complete
  6844. next_sha = porcelain.bisect_good(self.repo_path)
  6845. self.assertIsNone(next_sha)
  6846. def test_bisect_log(self):
  6847. """Test getting bisect log."""
  6848. # Create some commits
  6849. c1, c2, c3 = build_commit_graph(
  6850. self.repo.object_store,
  6851. [[1], [2, 1], [3, 2]],
  6852. attrs={
  6853. 1: {"message": b"initial"},
  6854. 2: {"message": b"second"},
  6855. 3: {"message": b"third"},
  6856. },
  6857. )
  6858. self.repo.refs[b"refs/heads/master"] = c3.id
  6859. self.repo.refs[b"HEAD"] = c3.id
  6860. # Start bisect and mark commits
  6861. porcelain.bisect_start(self.repo_path)
  6862. porcelain.bisect_bad(self.repo_path, c3.id)
  6863. porcelain.bisect_good(self.repo_path, c1.id)
  6864. # Get log
  6865. log = porcelain.bisect_log(self.repo_path)
  6866. self.assertIn("git bisect start", log)
  6867. self.assertIn("git bisect bad", log)
  6868. self.assertIn("git bisect good", log)
  6869. def test_bisect_reset(self):
  6870. """Test resetting bisect state."""
  6871. # Create some commits
  6872. c1, c2, c3 = build_commit_graph(
  6873. self.repo.object_store,
  6874. [[1], [2, 1], [3, 2]],
  6875. attrs={
  6876. 1: {"message": b"initial"},
  6877. 2: {"message": b"second"},
  6878. 3: {"message": b"third"},
  6879. },
  6880. )
  6881. self.repo.refs[b"refs/heads/master"] = c3.id
  6882. self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
  6883. # Start bisect
  6884. porcelain.bisect_start(self.repo_path)
  6885. porcelain.bisect_bad(self.repo_path)
  6886. porcelain.bisect_good(self.repo_path, c1.id)
  6887. # Reset
  6888. porcelain.bisect_reset(self.repo_path)
  6889. # Check that bisect state files are removed
  6890. self.assertFalse(
  6891. os.path.exists(os.path.join(self.repo.controldir(), "BISECT_START"))
  6892. )
  6893. self.assertFalse(
  6894. os.path.exists(os.path.join(self.repo.controldir(), "refs", "bisect"))
  6895. )
  6896. # HEAD should be back to being a symbolic ref to master
  6897. head_target, _ = self.repo.refs.follow(b"HEAD")
  6898. self.assertEqual(head_target[-1], b"refs/heads/master")
  6899. def test_bisect_skip(self):
  6900. """Test skipping commits during bisect."""
  6901. # Create some commits
  6902. c1, c2, c3, c4, c5 = build_commit_graph(
  6903. self.repo.object_store,
  6904. [[1], [2, 1], [3, 2], [4, 3], [5, 4]],
  6905. attrs={
  6906. 1: {"message": b"good"},
  6907. 2: {"message": b"skip this"},
  6908. 3: {"message": b"bad"},
  6909. 4: {"message": b"bad"},
  6910. 5: {"message": b"bad"},
  6911. },
  6912. )
  6913. self.repo.refs[b"refs/heads/master"] = c5.id
  6914. self.repo.refs[b"HEAD"] = c5.id
  6915. # Start bisect
  6916. porcelain.bisect_start(self.repo_path, bad=c5.id, good=c1.id)
  6917. # Skip c2 if it's selected
  6918. next_sha = porcelain.bisect_skip(self.repo_path, [c2.id])
  6919. self.assertIsNotNone(next_sha)
  6920. class ReflogTest(PorcelainTestCase):
  6921. def test_reflog_head(self):
  6922. """Test reading HEAD reflog."""
  6923. # Create a commit
  6924. blob = Blob.from_string(b"test content")
  6925. self.repo.object_store.add_object(blob)
  6926. tree = Tree()
  6927. tree.add(b"test", 0o100644, blob.id)
  6928. self.repo.object_store.add_object(tree)
  6929. commit = Commit()
  6930. commit.tree = tree.id
  6931. commit.author = b"Test Author <test@example.com>"
  6932. commit.committer = b"Test Author <test@example.com>"
  6933. commit.commit_time = 1234567890
  6934. commit.commit_timezone = 0
  6935. commit.author_time = 1234567890
  6936. commit.author_timezone = 0
  6937. commit.message = b"Initial commit"
  6938. self.repo.object_store.add_object(commit)
  6939. # Write a reflog entry
  6940. self.repo._write_reflog(
  6941. b"HEAD",
  6942. ZERO_SHA,
  6943. commit.id,
  6944. b"Test Author <test@example.com>",
  6945. 1234567890,
  6946. 0,
  6947. b"commit (initial): Initial commit",
  6948. )
  6949. # Read reflog using porcelain
  6950. entries = list(porcelain.reflog(self.repo_path))
  6951. self.assertEqual(1, len(entries))
  6952. self.assertEqual(ZERO_SHA, entries[0].old_sha)
  6953. self.assertEqual(commit.id, entries[0].new_sha)
  6954. self.assertEqual(b"Test Author <test@example.com>", entries[0].committer)
  6955. self.assertEqual(1234567890, entries[0].timestamp)
  6956. self.assertEqual(0, entries[0].timezone)
  6957. self.assertEqual(b"commit (initial): Initial commit", entries[0].message)
  6958. def test_reflog_with_string_ref(self):
  6959. """Test reading reflog with string reference."""
  6960. # Create a commit
  6961. blob = Blob.from_string(b"test content")
  6962. self.repo.object_store.add_object(blob)
  6963. tree = Tree()
  6964. tree.add(b"test", 0o100644, blob.id)
  6965. self.repo.object_store.add_object(tree)
  6966. commit = Commit()
  6967. commit.tree = tree.id
  6968. commit.author = b"Test Author <test@example.com>"
  6969. commit.committer = b"Test Author <test@example.com>"
  6970. commit.commit_time = 1234567890
  6971. commit.commit_timezone = 0
  6972. commit.author_time = 1234567890
  6973. commit.author_timezone = 0
  6974. commit.message = b"Initial commit"
  6975. self.repo.object_store.add_object(commit)
  6976. # Write a reflog entry
  6977. self.repo._write_reflog(
  6978. b"refs/heads/master",
  6979. ZERO_SHA,
  6980. commit.id,
  6981. b"Test Author <test@example.com>",
  6982. 1234567890,
  6983. 0,
  6984. b"commit (initial): Initial commit",
  6985. )
  6986. # Read reflog using porcelain with string ref
  6987. entries = list(porcelain.reflog(self.repo_path, "refs/heads/master"))
  6988. self.assertEqual(1, len(entries))
  6989. self.assertEqual(commit.id, entries[0].new_sha)
  6990. def test_reflog_all(self):
  6991. """Test reading all reflogs."""
  6992. # Create a commit
  6993. blob = Blob.from_string(b"test content")
  6994. self.repo.object_store.add_object(blob)
  6995. tree = Tree()
  6996. tree.add(b"test", 0o100644, blob.id)
  6997. self.repo.object_store.add_object(tree)
  6998. commit = Commit()
  6999. commit.tree = tree.id
  7000. commit.author = b"Test Author <test@example.com>"
  7001. commit.committer = b"Test Author <test@example.com>"
  7002. commit.commit_time = 1234567890
  7003. commit.commit_timezone = 0
  7004. commit.author_time = 1234567890
  7005. commit.author_timezone = 0
  7006. commit.message = b"Initial commit"
  7007. self.repo.object_store.add_object(commit)
  7008. # Write reflog entries for HEAD and master
  7009. self.repo._write_reflog(
  7010. b"HEAD",
  7011. ZERO_SHA,
  7012. commit.id,
  7013. b"Test Author <test@example.com>",
  7014. 1234567890,
  7015. 0,
  7016. b"commit (initial): Initial commit",
  7017. )
  7018. self.repo._write_reflog(
  7019. b"refs/heads/master",
  7020. ZERO_SHA,
  7021. commit.id,
  7022. b"Test Author <test@example.com>",
  7023. 1234567891,
  7024. 0,
  7025. b"branch: Created from HEAD",
  7026. )
  7027. # Read all reflogs using porcelain
  7028. entries = list(porcelain.reflog(self.repo_path, all=True))
  7029. # Should have at least 2 entries (HEAD and refs/heads/master)
  7030. self.assertGreaterEqual(len(entries), 2)
  7031. # Check that we got entries from different refs
  7032. refs_seen = set()
  7033. for ref, entry in entries:
  7034. refs_seen.add(ref)
  7035. self.assertEqual(commit.id, entry.new_sha)
  7036. # Should have seen at least HEAD and refs/heads/master
  7037. self.assertIn(b"HEAD", refs_seen)
  7038. self.assertIn(b"refs/heads/master", refs_seen)
  7039. class WriteCommitGraphTests(PorcelainTestCase):
  7040. """Tests for the write_commit_graph porcelain function."""
  7041. def test_write_commit_graph_empty_repo(self):
  7042. """Test writing commit graph on empty repository."""
  7043. # Should not fail on empty repo
  7044. porcelain.write_commit_graph(self.repo_path)
  7045. # No commit graph should be created for empty repo
  7046. graph_path = os.path.join(
  7047. self.repo_path, ".git", "objects", "info", "commit-graph"
  7048. )
  7049. self.assertFalse(os.path.exists(graph_path))
  7050. def test_write_commit_graph_with_commits(self):
  7051. """Test writing commit graph with commits."""
  7052. # Create some commits
  7053. c1, c2, c3 = build_commit_graph(
  7054. self.repo.object_store,
  7055. [[1], [2, 1], [3, 1, 2]],
  7056. attrs={
  7057. 1: {"message": b"First commit"},
  7058. 2: {"message": b"Second commit"},
  7059. 3: {"message": b"Merge commit"},
  7060. },
  7061. )
  7062. self.repo.refs[b"refs/heads/master"] = c3.id
  7063. self.repo.refs[b"refs/heads/branch"] = c2.id
  7064. # Write commit graph
  7065. porcelain.write_commit_graph(self.repo_path)
  7066. # Verify commit graph was created
  7067. graph_path = os.path.join(
  7068. self.repo_path, ".git", "objects", "info", "commit-graph"
  7069. )
  7070. self.assertTrue(os.path.exists(graph_path))
  7071. # Load and verify the commit graph
  7072. from dulwich.commit_graph import read_commit_graph
  7073. commit_graph = read_commit_graph(graph_path)
  7074. self.assertIsNotNone(commit_graph)
  7075. self.assertEqual(3, len(commit_graph))
  7076. # Verify all commits are in the graph
  7077. for commit_obj in [c1, c2, c3]:
  7078. entry = commit_graph.get_entry_by_oid(commit_obj.id)
  7079. self.assertIsNotNone(entry)
  7080. def test_write_commit_graph_config_disabled(self):
  7081. """Test that commit graph is not written when disabled by config."""
  7082. # Create a commit
  7083. (c1,) = build_commit_graph(
  7084. self.repo.object_store, [[1]], attrs={1: {"message": b"First commit"}}
  7085. )
  7086. self.repo.refs[b"refs/heads/master"] = c1.id
  7087. # Disable commit graph in config
  7088. config = self.repo.get_config()
  7089. config.set((b"core",), b"commitGraph", b"false")
  7090. config.write_to_path()
  7091. # Write commit graph (should respect config)
  7092. porcelain.write_commit_graph(self.repo_path)
  7093. # Verify commit graph still gets written
  7094. # (porcelain.write_commit_graph explicitly writes regardless of config)
  7095. graph_path = os.path.join(
  7096. self.repo_path, ".git", "objects", "info", "commit-graph"
  7097. )
  7098. self.assertTrue(os.path.exists(graph_path))
  7099. def test_write_commit_graph_reachable_false(self):
  7100. """Test writing commit graph with reachable=False."""
  7101. # Create commits
  7102. c1, c2, c3 = build_commit_graph(
  7103. self.repo.object_store,
  7104. [[1], [2, 1], [3, 2]],
  7105. attrs={
  7106. 1: {"message": b"First commit"},
  7107. 2: {"message": b"Second commit"},
  7108. 3: {"message": b"Third commit"},
  7109. },
  7110. )
  7111. # Only reference the third commit
  7112. self.repo.refs[b"refs/heads/master"] = c3.id
  7113. # Write commit graph with reachable=False
  7114. porcelain.write_commit_graph(self.repo_path, reachable=False)
  7115. # Verify commit graph was created
  7116. graph_path = os.path.join(
  7117. self.repo_path, ".git", "objects", "info", "commit-graph"
  7118. )
  7119. self.assertTrue(os.path.exists(graph_path))
  7120. # Load and verify the commit graph
  7121. from dulwich.commit_graph import read_commit_graph
  7122. commit_graph = read_commit_graph(graph_path)
  7123. self.assertIsNotNone(commit_graph)
  7124. # With reachable=False, only directly referenced commits should be included
  7125. # In this case, only c3 (from refs/heads/master)
  7126. self.assertEqual(1, len(commit_graph))
  7127. entry = commit_graph.get_entry_by_oid(c3.id)
  7128. self.assertIsNotNone(entry)