test_porcelain.py 208 KB

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