test_porcelain.py 178 KB

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