test_porcelain.py 179 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926
  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. # After fix: add() with no paths should behave like git add -A (add everything)
  844. self.assertEqual(sorted(index), [b"blah", b"foo/blie"])
  845. def test_add_file(self) -> None:
  846. fullpath = os.path.join(self.repo.path, "foo")
  847. with open(fullpath, "w") as f:
  848. f.write("BAR")
  849. porcelain.add(self.repo.path, paths=[fullpath])
  850. self.assertIn(b"foo", self.repo.open_index())
  851. def test_add_ignored(self) -> None:
  852. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  853. f.write("foo\nsubdir/")
  854. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  855. f.write("BAR")
  856. with open(os.path.join(self.repo.path, "bar"), "w") as f:
  857. f.write("BAR")
  858. os.mkdir(os.path.join(self.repo.path, "subdir"))
  859. with open(os.path.join(self.repo.path, "subdir", "baz"), "w") as f:
  860. f.write("BAZ")
  861. (added, ignored) = porcelain.add(
  862. self.repo.path,
  863. paths=[
  864. os.path.join(self.repo.path, "foo"),
  865. os.path.join(self.repo.path, "bar"),
  866. os.path.join(self.repo.path, "subdir"),
  867. ],
  868. )
  869. self.assertIn(b"bar", self.repo.open_index())
  870. self.assertEqual({"bar"}, set(added))
  871. self.assertEqual({"foo", "subdir/"}, ignored)
  872. def test_add_file_absolute_path(self) -> None:
  873. # Absolute paths are (not yet) supported
  874. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  875. f.write("BAR")
  876. porcelain.add(self.repo, paths=[os.path.join(self.repo.path, "foo")])
  877. self.assertIn(b"foo", self.repo.open_index())
  878. def test_add_not_in_repo(self) -> None:
  879. with open(os.path.join(self.test_dir, "foo"), "w") as f:
  880. f.write("BAR")
  881. self.assertRaises(
  882. ValueError,
  883. porcelain.add,
  884. self.repo,
  885. paths=[os.path.join(self.test_dir, "foo")],
  886. )
  887. self.assertRaises(
  888. (ValueError, FileNotFoundError),
  889. porcelain.add,
  890. self.repo,
  891. paths=["../foo"],
  892. )
  893. self.assertEqual([], list(self.repo.open_index()))
  894. def test_add_file_clrf_conversion(self) -> None:
  895. # Set the right configuration to the repo
  896. c = self.repo.get_config()
  897. c.set("core", "autocrlf", "input")
  898. c.write_to_path()
  899. # Add a file with CRLF line-ending
  900. fullpath = os.path.join(self.repo.path, "foo")
  901. with open(fullpath, "wb") as f:
  902. f.write(b"line1\r\nline2")
  903. porcelain.add(self.repo.path, paths=[fullpath])
  904. # The line-endings should have been converted to LF
  905. index = self.repo.open_index()
  906. self.assertIn(b"foo", index)
  907. entry = index[b"foo"]
  908. blob = self.repo[entry.sha]
  909. self.assertEqual(blob.data, b"line1\nline2")
  910. def test_add_symlink_outside_repo(self) -> None:
  911. """Test adding a symlink that points outside the repository."""
  912. # Create a symlink pointing outside the repository
  913. symlink_path = os.path.join(self.repo.path, "symlink_to_nowhere")
  914. os.symlink("/nonexistent/path", symlink_path)
  915. # Adding the symlink should succeed (matching Git's behavior)
  916. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  917. # Should successfully add the symlink
  918. self.assertIn("symlink_to_nowhere", added)
  919. self.assertEqual(len(ignored), 0)
  920. # Verify symlink is actually staged
  921. index = self.repo.open_index()
  922. self.assertIn(b"symlink_to_nowhere", index)
  923. def test_add_symlink_to_file_inside_repo(self) -> None:
  924. """Test adding a symlink that points to a file inside the repository."""
  925. # Create a regular file
  926. target_file = os.path.join(self.repo.path, "target.txt")
  927. with open(target_file, "w") as f:
  928. f.write("target content")
  929. # Create a symlink to the file
  930. symlink_path = os.path.join(self.repo.path, "link_to_target")
  931. os.symlink("target.txt", symlink_path)
  932. # Add both the target and the symlink
  933. added, ignored = porcelain.add(
  934. self.repo.path, paths=[target_file, symlink_path]
  935. )
  936. # Both should be added successfully
  937. self.assertIn("target.txt", added)
  938. self.assertIn("link_to_target", added)
  939. self.assertEqual(len(ignored), 0)
  940. # Verify both are in the index
  941. index = self.repo.open_index()
  942. self.assertIn(b"target.txt", index)
  943. self.assertIn(b"link_to_target", index)
  944. def test_add_symlink_to_directory_inside_repo(self) -> None:
  945. """Test adding a symlink that points to a directory inside the repository."""
  946. # Create a directory with some files
  947. target_dir = os.path.join(self.repo.path, "target_dir")
  948. os.mkdir(target_dir)
  949. with open(os.path.join(target_dir, "file1.txt"), "w") as f:
  950. f.write("content1")
  951. with open(os.path.join(target_dir, "file2.txt"), "w") as f:
  952. f.write("content2")
  953. # Create a symlink to the directory
  954. symlink_path = os.path.join(self.repo.path, "link_to_dir")
  955. os.symlink("target_dir", symlink_path)
  956. # Add the symlink
  957. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  958. # When adding a symlink to a directory, it follows the symlink and adds contents
  959. self.assertEqual(len(added), 2)
  960. self.assertIn("link_to_dir/file1.txt", added)
  961. self.assertIn("link_to_dir/file2.txt", added)
  962. self.assertEqual(len(ignored), 0)
  963. # Verify files are added through the symlink path
  964. index = self.repo.open_index()
  965. self.assertIn(b"link_to_dir/file1.txt", index)
  966. self.assertIn(b"link_to_dir/file2.txt", index)
  967. # The original target directory files are not added
  968. self.assertNotIn(b"target_dir/file1.txt", index)
  969. self.assertNotIn(b"target_dir/file2.txt", index)
  970. def test_add_symlink_chain(self) -> None:
  971. """Test adding a chain of symlinks (symlink to symlink)."""
  972. # Create a regular file
  973. target_file = os.path.join(self.repo.path, "original.txt")
  974. with open(target_file, "w") as f:
  975. f.write("original content")
  976. # Create first symlink
  977. first_link = os.path.join(self.repo.path, "link1")
  978. os.symlink("original.txt", first_link)
  979. # Create second symlink pointing to first
  980. second_link = os.path.join(self.repo.path, "link2")
  981. os.symlink("link1", second_link)
  982. # Add all files
  983. added, ignored = porcelain.add(
  984. self.repo.path, paths=[target_file, first_link, second_link]
  985. )
  986. # All should be added
  987. self.assertEqual(len(added), 3)
  988. self.assertIn("original.txt", added)
  989. self.assertIn("link1", added)
  990. self.assertIn("link2", added)
  991. # Verify all are in the index
  992. index = self.repo.open_index()
  993. self.assertIn(b"original.txt", index)
  994. self.assertIn(b"link1", index)
  995. self.assertIn(b"link2", index)
  996. def test_add_broken_symlink(self) -> None:
  997. """Test adding a broken symlink (points to non-existent target)."""
  998. # Create a symlink to a non-existent file
  999. broken_link = os.path.join(self.repo.path, "broken_link")
  1000. os.symlink("does_not_exist.txt", broken_link)
  1001. # Add the broken symlink
  1002. added, ignored = porcelain.add(self.repo.path, paths=[broken_link])
  1003. # Should be added successfully (Git tracks the symlink, not its target)
  1004. self.assertIn("broken_link", added)
  1005. self.assertEqual(len(ignored), 0)
  1006. # Verify it's in the index
  1007. index = self.repo.open_index()
  1008. self.assertIn(b"broken_link", index)
  1009. def test_add_symlink_relative_outside_repo(self) -> None:
  1010. """Test adding a symlink that uses '..' to point outside the repository."""
  1011. # Create a file outside the repo
  1012. outside_file = os.path.join(self.test_dir, "outside.txt")
  1013. with open(outside_file, "w") as f:
  1014. f.write("outside content")
  1015. # Create a symlink using relative path to go outside
  1016. symlink_path = os.path.join(self.repo.path, "link_outside")
  1017. os.symlink("../outside.txt", symlink_path)
  1018. # Add the symlink
  1019. added, ignored = porcelain.add(self.repo.path, paths=[symlink_path])
  1020. # Should be added successfully
  1021. self.assertIn("link_outside", added)
  1022. self.assertEqual(len(ignored), 0)
  1023. # Verify it's in the index
  1024. index = self.repo.open_index()
  1025. self.assertIn(b"link_outside", index)
  1026. def test_add_symlink_absolute_to_system(self) -> None:
  1027. """Test adding a symlink with absolute path to system directory."""
  1028. # Create a symlink to a system directory
  1029. symlink_path = os.path.join(self.repo.path, "link_to_tmp")
  1030. if os.name == "nt":
  1031. # On Windows, use a system directory like TEMP
  1032. symlink_target = os.environ["TEMP"]
  1033. else:
  1034. # On Unix-like systems, use /tmp
  1035. symlink_target = "/tmp"
  1036. os.symlink(symlink_target, symlink_path)
  1037. # Adding a symlink to a directory outside the repo should raise ValueError
  1038. with self.assertRaises(ValueError) as cm:
  1039. porcelain.add(self.repo.path, paths=[symlink_path])
  1040. # Check that the error indicates the path is outside the repository
  1041. self.assertIn("is not in the subpath of", str(cm.exception))
  1042. def test_add_file_through_symlink(self) -> None:
  1043. """Test adding a file through a symlinked directory."""
  1044. # Create a directory with a file
  1045. real_dir = os.path.join(self.repo.path, "real_dir")
  1046. os.mkdir(real_dir)
  1047. real_file = os.path.join(real_dir, "file.txt")
  1048. with open(real_file, "w") as f:
  1049. f.write("content")
  1050. # Create a symlink to the directory
  1051. link_dir = os.path.join(self.repo.path, "link_dir")
  1052. os.symlink("real_dir", link_dir)
  1053. # Try to add the file through the symlink path
  1054. symlink_file_path = os.path.join(link_dir, "file.txt")
  1055. # This should add the real file, not create a new entry
  1056. added, ignored = porcelain.add(self.repo.path, paths=[symlink_file_path])
  1057. # The real file should be added
  1058. self.assertIn("real_dir/file.txt", added)
  1059. self.assertEqual(len(added), 1)
  1060. # Verify correct path in index
  1061. index = self.repo.open_index()
  1062. self.assertIn(b"real_dir/file.txt", index)
  1063. # Should not create a separate entry for the symlink path
  1064. self.assertNotIn(b"link_dir/file.txt", index)
  1065. def test_add_repo_path(self) -> None:
  1066. """Test adding the repository path itself should add all untracked files."""
  1067. # Create some untracked files
  1068. with open(os.path.join(self.repo.path, "file1.txt"), "w") as f:
  1069. f.write("content1")
  1070. with open(os.path.join(self.repo.path, "file2.txt"), "w") as f:
  1071. f.write("content2")
  1072. # Add the repository path itself
  1073. added, ignored = porcelain.add(self.repo.path, paths=[self.repo.path])
  1074. # Should add all untracked files, not stage './'
  1075. self.assertIn("file1.txt", added)
  1076. self.assertIn("file2.txt", added)
  1077. self.assertNotIn("./", added)
  1078. # Verify files are actually staged
  1079. index = self.repo.open_index()
  1080. self.assertIn(b"file1.txt", index)
  1081. self.assertIn(b"file2.txt", index)
  1082. def test_add_directory_contents(self) -> None:
  1083. """Test adding a directory adds all files within it."""
  1084. # Create a subdirectory with multiple files
  1085. subdir = os.path.join(self.repo.path, "subdir")
  1086. os.mkdir(subdir)
  1087. with open(os.path.join(subdir, "file1.txt"), "w") as f:
  1088. f.write("content1")
  1089. with open(os.path.join(subdir, "file2.txt"), "w") as f:
  1090. f.write("content2")
  1091. with open(os.path.join(subdir, "file3.txt"), "w") as f:
  1092. f.write("content3")
  1093. # Add the directory
  1094. added, ignored = porcelain.add(self.repo.path, paths=["subdir"])
  1095. # Should add all files in the directory
  1096. self.assertEqual(len(added), 3)
  1097. # Normalize paths to use forward slashes for comparison
  1098. added_normalized = [path.replace(os.sep, "/") for path in added]
  1099. self.assertIn("subdir/file1.txt", added_normalized)
  1100. self.assertIn("subdir/file2.txt", added_normalized)
  1101. self.assertIn("subdir/file3.txt", added_normalized)
  1102. # Verify files are actually staged
  1103. index = self.repo.open_index()
  1104. self.assertIn(b"subdir/file1.txt", index)
  1105. self.assertIn(b"subdir/file2.txt", index)
  1106. self.assertIn(b"subdir/file3.txt", index)
  1107. def test_add_nested_directories(self) -> None:
  1108. """Test adding a directory with nested subdirectories."""
  1109. # Create nested directory structure
  1110. dir1 = os.path.join(self.repo.path, "dir1")
  1111. dir2 = os.path.join(dir1, "dir2")
  1112. dir3 = os.path.join(dir2, "dir3")
  1113. os.makedirs(dir3)
  1114. # Add files at each level
  1115. with open(os.path.join(dir1, "file1.txt"), "w") as f:
  1116. f.write("level1")
  1117. with open(os.path.join(dir2, "file2.txt"), "w") as f:
  1118. f.write("level2")
  1119. with open(os.path.join(dir3, "file3.txt"), "w") as f:
  1120. f.write("level3")
  1121. # Add the top-level directory
  1122. added, ignored = porcelain.add(self.repo.path, paths=["dir1"])
  1123. # Should add all files recursively
  1124. self.assertEqual(len(added), 3)
  1125. # Normalize paths to use forward slashes for comparison
  1126. added_normalized = [path.replace(os.sep, "/") for path in added]
  1127. self.assertIn("dir1/file1.txt", added_normalized)
  1128. self.assertIn("dir1/dir2/file2.txt", added_normalized)
  1129. self.assertIn("dir1/dir2/dir3/file3.txt", added_normalized)
  1130. # Verify files are actually staged
  1131. index = self.repo.open_index()
  1132. self.assertIn(b"dir1/file1.txt", index)
  1133. self.assertIn(b"dir1/dir2/file2.txt", index)
  1134. self.assertIn(b"dir1/dir2/dir3/file3.txt", index)
  1135. def test_add_directory_with_tracked_files(self) -> None:
  1136. """Test adding a directory with some files already tracked."""
  1137. # Create a subdirectory with files
  1138. subdir = os.path.join(self.repo.path, "mixed")
  1139. os.mkdir(subdir)
  1140. # Create and commit one file
  1141. tracked_file = os.path.join(subdir, "tracked.txt")
  1142. with open(tracked_file, "w") as f:
  1143. f.write("already tracked")
  1144. porcelain.add(self.repo.path, paths=[tracked_file])
  1145. porcelain.commit(
  1146. repo=self.repo.path,
  1147. message=b"Add tracked file",
  1148. author=b"test <email>",
  1149. committer=b"test <email>",
  1150. )
  1151. # Add more untracked files
  1152. with open(os.path.join(subdir, "untracked1.txt"), "w") as f:
  1153. f.write("new file 1")
  1154. with open(os.path.join(subdir, "untracked2.txt"), "w") as f:
  1155. f.write("new file 2")
  1156. # Add the directory
  1157. added, ignored = porcelain.add(self.repo.path, paths=["mixed"])
  1158. # Should only add the untracked files
  1159. self.assertEqual(len(added), 2)
  1160. # Normalize paths to use forward slashes for comparison
  1161. added_normalized = [path.replace(os.sep, "/") for path in added]
  1162. self.assertIn("mixed/untracked1.txt", added_normalized)
  1163. self.assertIn("mixed/untracked2.txt", added_normalized)
  1164. self.assertNotIn("mixed/tracked.txt", added)
  1165. # Verify the index contains all files
  1166. index = self.repo.open_index()
  1167. self.assertIn(b"mixed/tracked.txt", index)
  1168. self.assertIn(b"mixed/untracked1.txt", index)
  1169. self.assertIn(b"mixed/untracked2.txt", index)
  1170. def test_add_directory_with_gitignore(self) -> None:
  1171. """Test adding a directory respects .gitignore patterns."""
  1172. # Create .gitignore
  1173. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  1174. f.write("*.log\n*.tmp\nbuild/\n")
  1175. # Create directory with mixed files
  1176. testdir = os.path.join(self.repo.path, "testdir")
  1177. os.mkdir(testdir)
  1178. # Create various files
  1179. with open(os.path.join(testdir, "important.txt"), "w") as f:
  1180. f.write("keep this")
  1181. with open(os.path.join(testdir, "debug.log"), "w") as f:
  1182. f.write("ignore this")
  1183. with open(os.path.join(testdir, "temp.tmp"), "w") as f:
  1184. f.write("ignore this too")
  1185. with open(os.path.join(testdir, "readme.md"), "w") as f:
  1186. f.write("keep this too")
  1187. # Create a build directory that should be ignored
  1188. builddir = os.path.join(testdir, "build")
  1189. os.mkdir(builddir)
  1190. with open(os.path.join(builddir, "output.txt"), "w") as f:
  1191. f.write("ignore entire directory")
  1192. # Add the directory
  1193. added, ignored = porcelain.add(self.repo.path, paths=["testdir"])
  1194. # Should only add non-ignored files
  1195. # Normalize paths to use forward slashes for comparison
  1196. added_normalized = {path.replace(os.sep, "/") for path in added}
  1197. self.assertEqual(
  1198. added_normalized, {"testdir/important.txt", "testdir/readme.md"}
  1199. )
  1200. # Check ignored files
  1201. # Normalize paths to use forward slashes for comparison
  1202. ignored_normalized = {path.replace(os.sep, "/") for path in ignored}
  1203. self.assertIn("testdir/debug.log", ignored_normalized)
  1204. self.assertIn("testdir/temp.tmp", ignored_normalized)
  1205. self.assertIn("testdir/build/", ignored_normalized)
  1206. def test_add_multiple_directories(self) -> None:
  1207. """Test adding multiple directories in one call."""
  1208. # Create multiple directories
  1209. for dirname in ["dir1", "dir2", "dir3"]:
  1210. dirpath = os.path.join(self.repo.path, dirname)
  1211. os.mkdir(dirpath)
  1212. # Add files to each directory
  1213. for i in range(2):
  1214. with open(os.path.join(dirpath, f"file{i}.txt"), "w") as f:
  1215. f.write(f"content {dirname} {i}")
  1216. # Add all directories at once
  1217. added, ignored = porcelain.add(self.repo.path, paths=["dir1", "dir2", "dir3"])
  1218. # Should add all files from all directories
  1219. self.assertEqual(len(added), 6)
  1220. # Normalize paths to use forward slashes for comparison
  1221. added_normalized = [path.replace(os.sep, "/") for path in added]
  1222. for dirname in ["dir1", "dir2", "dir3"]:
  1223. for i in range(2):
  1224. self.assertIn(f"{dirname}/file{i}.txt", added_normalized)
  1225. # Verify all files are staged
  1226. index = self.repo.open_index()
  1227. self.assertEqual(len(index), 6)
  1228. def test_add_default_paths_includes_modified_files(self) -> None:
  1229. """Test that add() with no paths includes both untracked and modified files."""
  1230. # Create and commit initial file
  1231. initial_file = os.path.join(self.repo.path, "existing.txt")
  1232. with open(initial_file, "w") as f:
  1233. f.write("initial content\n")
  1234. porcelain.add(repo=self.repo.path, paths=[initial_file])
  1235. porcelain.commit(
  1236. repo=self.repo.path,
  1237. message=b"initial commit",
  1238. author=b"test <email>",
  1239. committer=b"test <email>",
  1240. )
  1241. # Modify the existing file (this creates an unstaged change)
  1242. with open(initial_file, "w") as f:
  1243. f.write("modified content\n")
  1244. # Create a new untracked file
  1245. new_file = os.path.join(self.repo.path, "new.txt")
  1246. with open(new_file, "w") as f:
  1247. f.write("new file content\n")
  1248. # Call add() with no paths - should stage both modified and untracked files
  1249. added_files, ignored_files = porcelain.add(repo=self.repo.path)
  1250. # Verify both files were added
  1251. self.assertIn("existing.txt", added_files)
  1252. self.assertIn("new.txt", added_files)
  1253. self.assertEqual(len(ignored_files), 0)
  1254. # Verify both files are now staged
  1255. index = self.repo.open_index()
  1256. self.assertIn(b"existing.txt", index)
  1257. self.assertIn(b"new.txt", index)
  1258. class RemoveTests(PorcelainTestCase):
  1259. def test_remove_file(self) -> None:
  1260. fullpath = os.path.join(self.repo.path, "foo")
  1261. with open(fullpath, "w") as f:
  1262. f.write("BAR")
  1263. porcelain.add(self.repo.path, paths=[fullpath])
  1264. porcelain.commit(
  1265. repo=self.repo,
  1266. message=b"test",
  1267. author=b"test <email>",
  1268. committer=b"test <email>",
  1269. )
  1270. self.assertTrue(os.path.exists(os.path.join(self.repo.path, "foo")))
  1271. cwd = os.getcwd()
  1272. try:
  1273. os.chdir(self.repo.path)
  1274. porcelain.remove(self.repo.path, paths=["foo"])
  1275. finally:
  1276. os.chdir(cwd)
  1277. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1278. def test_remove_file_staged(self) -> None:
  1279. fullpath = os.path.join(self.repo.path, "foo")
  1280. with open(fullpath, "w") as f:
  1281. f.write("BAR")
  1282. cwd = os.getcwd()
  1283. try:
  1284. os.chdir(self.repo.path)
  1285. porcelain.add(self.repo.path, paths=[fullpath])
  1286. self.assertRaises(Exception, porcelain.rm, self.repo.path, paths=["foo"])
  1287. finally:
  1288. os.chdir(cwd)
  1289. def test_remove_file_removed_on_disk(self) -> None:
  1290. fullpath = os.path.join(self.repo.path, "foo")
  1291. with open(fullpath, "w") as f:
  1292. f.write("BAR")
  1293. porcelain.add(self.repo.path, paths=[fullpath])
  1294. cwd = os.getcwd()
  1295. try:
  1296. os.chdir(self.repo.path)
  1297. os.remove(fullpath)
  1298. porcelain.remove(self.repo.path, paths=["foo"])
  1299. finally:
  1300. os.chdir(cwd)
  1301. self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo")))
  1302. class LogTests(PorcelainTestCase):
  1303. def test_simple(self) -> None:
  1304. c1, c2, c3 = build_commit_graph(
  1305. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1306. )
  1307. self.repo.refs[b"HEAD"] = c3.id
  1308. self.maxDiff = None
  1309. outstream = StringIO()
  1310. porcelain.log(self.repo.path, outstream=outstream)
  1311. self.assertEqual(
  1312. outstream.getvalue(),
  1313. """\
  1314. --------------------------------------------------
  1315. commit: 4a3b887baa9ecb2d054d2469b628aef84e2d74f0
  1316. merge: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  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. Commit 3
  1321. --------------------------------------------------
  1322. commit: 7508036b1cfec5aa9cef0d5a7f04abcecfe09112
  1323. Author: Test Author <test@nodomain.com>
  1324. Committer: Test Committer <test@nodomain.com>
  1325. Date: Fri Jan 01 2010 00:00:00 +0000
  1326. Commit 2
  1327. --------------------------------------------------
  1328. commit: 11d3cf672a19366435c1983c7340b008ec6b8bf3
  1329. Author: Test Author <test@nodomain.com>
  1330. Committer: Test Committer <test@nodomain.com>
  1331. Date: Fri Jan 01 2010 00:00:00 +0000
  1332. Commit 1
  1333. """,
  1334. )
  1335. def test_max_entries(self) -> None:
  1336. c1, c2, c3 = build_commit_graph(
  1337. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1338. )
  1339. self.repo.refs[b"HEAD"] = c3.id
  1340. outstream = StringIO()
  1341. porcelain.log(self.repo.path, outstream=outstream, max_entries=1)
  1342. self.assertEqual(1, outstream.getvalue().count("-" * 50))
  1343. def test_no_revisions(self) -> None:
  1344. outstream = StringIO()
  1345. porcelain.log(self.repo.path, outstream=outstream)
  1346. self.assertEqual("", outstream.getvalue())
  1347. def test_empty_message(self) -> None:
  1348. c1 = make_commit(message="")
  1349. self.repo.object_store.add_object(c1)
  1350. self.repo.refs[b"HEAD"] = c1.id
  1351. outstream = StringIO()
  1352. porcelain.log(self.repo.path, outstream=outstream)
  1353. self.assertEqual(
  1354. outstream.getvalue(),
  1355. """\
  1356. --------------------------------------------------
  1357. commit: 4a7ad5552fad70647a81fb9a4a923ccefcca4b76
  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. """,
  1362. )
  1363. class ShowTests(PorcelainTestCase):
  1364. def test_nolist(self) -> None:
  1365. c1, c2, c3 = build_commit_graph(
  1366. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1367. )
  1368. self.repo.refs[b"HEAD"] = c3.id
  1369. outstream = StringIO()
  1370. porcelain.show(self.repo.path, objects=c3.id, outstream=outstream)
  1371. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  1372. def test_simple(self) -> None:
  1373. c1, c2, c3 = build_commit_graph(
  1374. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1375. )
  1376. self.repo.refs[b"HEAD"] = c3.id
  1377. outstream = StringIO()
  1378. porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream)
  1379. self.assertTrue(outstream.getvalue().startswith("-" * 50))
  1380. def test_blob(self) -> None:
  1381. b = Blob.from_string(b"The Foo\n")
  1382. self.repo.object_store.add_object(b)
  1383. outstream = StringIO()
  1384. porcelain.show(self.repo.path, objects=[b.id], outstream=outstream)
  1385. self.assertEqual(outstream.getvalue(), "The Foo\n")
  1386. def test_commit_no_parent(self) -> None:
  1387. a = Blob.from_string(b"The Foo\n")
  1388. ta = Tree()
  1389. ta.add(b"somename", 0o100644, a.id)
  1390. ca = make_commit(tree=ta.id)
  1391. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  1392. outstream = StringIO()
  1393. porcelain.show(self.repo.path, objects=[ca.id], outstream=outstream)
  1394. self.assertMultiLineEqual(
  1395. outstream.getvalue(),
  1396. """\
  1397. --------------------------------------------------
  1398. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  1399. Author: Test Author <test@nodomain.com>
  1400. Committer: Test Committer <test@nodomain.com>
  1401. Date: Fri Jan 01 2010 00:00:00 +0000
  1402. Test message.
  1403. diff --git a/somename b/somename
  1404. new file mode 100644
  1405. index 0000000..ea5c7bf
  1406. --- /dev/null
  1407. +++ b/somename
  1408. @@ -0,0 +1 @@
  1409. +The Foo
  1410. """,
  1411. )
  1412. def test_tag(self) -> None:
  1413. a = Blob.from_string(b"The Foo\n")
  1414. ta = Tree()
  1415. ta.add(b"somename", 0o100644, a.id)
  1416. ca = make_commit(tree=ta.id)
  1417. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  1418. porcelain.tag_create(
  1419. self.repo.path,
  1420. b"tryme",
  1421. b"foo <foo@bar.com>",
  1422. b"bar",
  1423. annotated=True,
  1424. objectish=ca.id,
  1425. tag_time=1552854211,
  1426. tag_timezone=0,
  1427. )
  1428. outstream = StringIO()
  1429. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  1430. self.maxDiff = None
  1431. self.assertMultiLineEqual(
  1432. outstream.getvalue(),
  1433. """\
  1434. Tagger: foo <foo@bar.com>
  1435. Date: Sun Mar 17 2019 20:23:31 +0000
  1436. bar
  1437. --------------------------------------------------
  1438. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  1439. Author: Test Author <test@nodomain.com>
  1440. Committer: Test Committer <test@nodomain.com>
  1441. Date: Fri Jan 01 2010 00:00:00 +0000
  1442. Test message.
  1443. diff --git a/somename b/somename
  1444. new file mode 100644
  1445. index 0000000..ea5c7bf
  1446. --- /dev/null
  1447. +++ b/somename
  1448. @@ -0,0 +1 @@
  1449. +The Foo
  1450. """,
  1451. )
  1452. def test_tag_unicode(self) -> None:
  1453. a = Blob.from_string(b"The Foo\n")
  1454. ta = Tree()
  1455. ta.add(b"somename", 0o100644, a.id)
  1456. ca = make_commit(tree=ta.id)
  1457. self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)])
  1458. porcelain.tag_create(
  1459. self.repo.path,
  1460. "tryme",
  1461. "foo <foo@bar.com>",
  1462. "bar",
  1463. annotated=True,
  1464. objectish=ca.id,
  1465. tag_time=1552854211,
  1466. tag_timezone=0,
  1467. )
  1468. outstream = StringIO()
  1469. porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream)
  1470. self.maxDiff = None
  1471. self.assertMultiLineEqual(
  1472. outstream.getvalue(),
  1473. """\
  1474. Tagger: foo <foo@bar.com>
  1475. Date: Sun Mar 17 2019 20:23:31 +0000
  1476. bar
  1477. --------------------------------------------------
  1478. commit: 344da06c1bb85901270b3e8875c988a027ec087d
  1479. Author: Test Author <test@nodomain.com>
  1480. Committer: Test Committer <test@nodomain.com>
  1481. Date: Fri Jan 01 2010 00:00:00 +0000
  1482. Test message.
  1483. diff --git a/somename b/somename
  1484. new file mode 100644
  1485. index 0000000..ea5c7bf
  1486. --- /dev/null
  1487. +++ b/somename
  1488. @@ -0,0 +1 @@
  1489. +The Foo
  1490. """,
  1491. )
  1492. def test_commit_with_change(self) -> None:
  1493. a = Blob.from_string(b"The Foo\n")
  1494. ta = Tree()
  1495. ta.add(b"somename", 0o100644, a.id)
  1496. ca = make_commit(tree=ta.id)
  1497. b = Blob.from_string(b"The Bar\n")
  1498. tb = Tree()
  1499. tb.add(b"somename", 0o100644, b.id)
  1500. cb = make_commit(tree=tb.id, parents=[ca.id])
  1501. self.repo.object_store.add_objects(
  1502. [
  1503. (a, None),
  1504. (b, None),
  1505. (ta, None),
  1506. (tb, None),
  1507. (ca, None),
  1508. (cb, None),
  1509. ]
  1510. )
  1511. outstream = StringIO()
  1512. porcelain.show(self.repo.path, objects=[cb.id], outstream=outstream)
  1513. self.assertMultiLineEqual(
  1514. outstream.getvalue(),
  1515. """\
  1516. --------------------------------------------------
  1517. commit: 2c6b6c9cb72c130956657e1fdae58e5b103744fa
  1518. Author: Test Author <test@nodomain.com>
  1519. Committer: Test Committer <test@nodomain.com>
  1520. Date: Fri Jan 01 2010 00:00:00 +0000
  1521. Test message.
  1522. diff --git a/somename b/somename
  1523. index ea5c7bf..fd38bcb 100644
  1524. --- a/somename
  1525. +++ b/somename
  1526. @@ -1 +1 @@
  1527. -The Foo
  1528. +The Bar
  1529. """,
  1530. )
  1531. class SymbolicRefTests(PorcelainTestCase):
  1532. def test_set_wrong_symbolic_ref(self) -> None:
  1533. c1, c2, c3 = build_commit_graph(
  1534. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1535. )
  1536. self.repo.refs[b"HEAD"] = c3.id
  1537. self.assertRaises(
  1538. porcelain.Error, porcelain.symbolic_ref, self.repo.path, b"foobar"
  1539. )
  1540. def test_set_force_wrong_symbolic_ref(self) -> None:
  1541. c1, c2, c3 = build_commit_graph(
  1542. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1543. )
  1544. self.repo.refs[b"HEAD"] = c3.id
  1545. porcelain.symbolic_ref(self.repo.path, b"force_foobar", force=True)
  1546. # test if we actually changed the file
  1547. with self.repo.get_named_file("HEAD") as f:
  1548. new_ref = f.read()
  1549. self.assertEqual(new_ref, b"ref: refs/heads/force_foobar\n")
  1550. def test_set_symbolic_ref(self) -> None:
  1551. c1, c2, c3 = build_commit_graph(
  1552. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1553. )
  1554. self.repo.refs[b"HEAD"] = c3.id
  1555. porcelain.symbolic_ref(self.repo.path, b"master")
  1556. def test_set_symbolic_ref_other_than_master(self) -> None:
  1557. c1, c2, c3 = build_commit_graph(
  1558. self.repo.object_store,
  1559. [[1], [2, 1], [3, 1, 2]],
  1560. attrs=dict(refs="develop"),
  1561. )
  1562. self.repo.refs[b"HEAD"] = c3.id
  1563. self.repo.refs[b"refs/heads/develop"] = c3.id
  1564. porcelain.symbolic_ref(self.repo.path, b"develop")
  1565. # test if we actually changed the file
  1566. with self.repo.get_named_file("HEAD") as f:
  1567. new_ref = f.read()
  1568. self.assertEqual(new_ref, b"ref: refs/heads/develop\n")
  1569. class DiffTreeTests(PorcelainTestCase):
  1570. def test_empty(self) -> None:
  1571. c1, c2, c3 = build_commit_graph(
  1572. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1573. )
  1574. self.repo.refs[b"HEAD"] = c3.id
  1575. outstream = BytesIO()
  1576. porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream)
  1577. self.assertEqual(outstream.getvalue(), b"")
  1578. class CommitTreeTests(PorcelainTestCase):
  1579. def test_simple(self) -> None:
  1580. c1, c2, c3 = build_commit_graph(
  1581. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1582. )
  1583. b = Blob()
  1584. b.data = b"foo the bar"
  1585. t = Tree()
  1586. t.add(b"somename", 0o100644, b.id)
  1587. self.repo.object_store.add_object(t)
  1588. self.repo.object_store.add_object(b)
  1589. sha = porcelain.commit_tree(
  1590. self.repo.path,
  1591. t.id,
  1592. message=b"Withcommit.",
  1593. author=b"Joe <joe@example.com>",
  1594. committer=b"Jane <jane@example.com>",
  1595. )
  1596. self.assertIsInstance(sha, bytes)
  1597. self.assertEqual(len(sha), 40)
  1598. class RevListTests(PorcelainTestCase):
  1599. def test_simple(self) -> None:
  1600. c1, c2, c3 = build_commit_graph(
  1601. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1602. )
  1603. outstream = BytesIO()
  1604. porcelain.rev_list(self.repo.path, [c3.id], outstream=outstream)
  1605. self.assertEqual(
  1606. c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue()
  1607. )
  1608. @skipIf(
  1609. platform.python_implementation() == "PyPy" or sys.platform == "win32",
  1610. "gpgme not easily available or supported on Windows and PyPy",
  1611. )
  1612. class TagCreateSignTests(PorcelainGpgTestCase):
  1613. def test_default_key(self) -> None:
  1614. c1, c2, c3 = build_commit_graph(
  1615. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1616. )
  1617. self.repo.refs[b"HEAD"] = c3.id
  1618. cfg = self.repo.get_config()
  1619. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  1620. self.import_default_key()
  1621. porcelain.tag_create(
  1622. self.repo.path,
  1623. b"tryme",
  1624. b"foo <foo@bar.com>",
  1625. b"bar",
  1626. annotated=True,
  1627. sign=True,
  1628. )
  1629. tags = self.repo.refs.as_dict(b"refs/tags")
  1630. self.assertEqual(list(tags.keys()), [b"tryme"])
  1631. tag = self.repo[b"refs/tags/tryme"]
  1632. self.assertIsInstance(tag, Tag)
  1633. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  1634. self.assertEqual(b"bar\n", tag.message)
  1635. self.assertRecentTimestamp(tag.tag_time)
  1636. tag = self.repo[b"refs/tags/tryme"]
  1637. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  1638. tag.verify()
  1639. tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID])
  1640. self.import_non_default_key()
  1641. self.assertRaises(
  1642. gpg.errors.MissingSignatures,
  1643. tag.verify,
  1644. keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID],
  1645. )
  1646. tag._chunked_text = [b"bad data", tag._signature]
  1647. self.assertRaises(
  1648. gpg.errors.BadSignatures,
  1649. tag.verify,
  1650. )
  1651. def test_non_default_key(self) -> None:
  1652. c1, c2, c3 = build_commit_graph(
  1653. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1654. )
  1655. self.repo.refs[b"HEAD"] = c3.id
  1656. cfg = self.repo.get_config()
  1657. cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID)
  1658. self.import_non_default_key()
  1659. porcelain.tag_create(
  1660. self.repo.path,
  1661. b"tryme",
  1662. b"foo <foo@bar.com>",
  1663. b"bar",
  1664. annotated=True,
  1665. sign=PorcelainGpgTestCase.NON_DEFAULT_KEY_ID,
  1666. )
  1667. tags = self.repo.refs.as_dict(b"refs/tags")
  1668. self.assertEqual(list(tags.keys()), [b"tryme"])
  1669. tag = self.repo[b"refs/tags/tryme"]
  1670. self.assertIsInstance(tag, Tag)
  1671. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  1672. self.assertEqual(b"bar\n", tag.message)
  1673. self.assertRecentTimestamp(tag.tag_time)
  1674. tag = self.repo[b"refs/tags/tryme"]
  1675. # GPG Signatures aren't deterministic, so we can't do a static assertion.
  1676. tag.verify()
  1677. class TagCreateTests(PorcelainTestCase):
  1678. def test_annotated(self) -> None:
  1679. c1, c2, c3 = build_commit_graph(
  1680. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1681. )
  1682. self.repo.refs[b"HEAD"] = c3.id
  1683. porcelain.tag_create(
  1684. self.repo.path,
  1685. b"tryme",
  1686. b"foo <foo@bar.com>",
  1687. b"bar",
  1688. annotated=True,
  1689. )
  1690. tags = self.repo.refs.as_dict(b"refs/tags")
  1691. self.assertEqual(list(tags.keys()), [b"tryme"])
  1692. tag = self.repo[b"refs/tags/tryme"]
  1693. self.assertIsInstance(tag, Tag)
  1694. self.assertEqual(b"foo <foo@bar.com>", tag.tagger)
  1695. self.assertEqual(b"bar\n", tag.message)
  1696. self.assertRecentTimestamp(tag.tag_time)
  1697. def test_unannotated(self) -> None:
  1698. c1, c2, c3 = build_commit_graph(
  1699. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1700. )
  1701. self.repo.refs[b"HEAD"] = c3.id
  1702. porcelain.tag_create(self.repo.path, b"tryme", annotated=False)
  1703. tags = self.repo.refs.as_dict(b"refs/tags")
  1704. self.assertEqual(list(tags.keys()), [b"tryme"])
  1705. self.repo[b"refs/tags/tryme"]
  1706. self.assertEqual(list(tags.values()), [self.repo.head()])
  1707. def test_unannotated_unicode(self) -> None:
  1708. c1, c2, c3 = build_commit_graph(
  1709. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  1710. )
  1711. self.repo.refs[b"HEAD"] = c3.id
  1712. porcelain.tag_create(self.repo.path, "tryme", annotated=False)
  1713. tags = self.repo.refs.as_dict(b"refs/tags")
  1714. self.assertEqual(list(tags.keys()), [b"tryme"])
  1715. self.repo[b"refs/tags/tryme"]
  1716. self.assertEqual(list(tags.values()), [self.repo.head()])
  1717. class TagListTests(PorcelainTestCase):
  1718. def test_empty(self) -> None:
  1719. tags = porcelain.tag_list(self.repo.path)
  1720. self.assertEqual([], tags)
  1721. def test_simple(self) -> None:
  1722. self.repo.refs[b"refs/tags/foo"] = b"aa" * 20
  1723. self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20
  1724. tags = porcelain.tag_list(self.repo.path)
  1725. self.assertEqual([b"bar/bla", b"foo"], tags)
  1726. class TagDeleteTests(PorcelainTestCase):
  1727. def test_simple(self) -> None:
  1728. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  1729. self.repo[b"HEAD"] = c1.id
  1730. porcelain.tag_create(self.repo, b"foo")
  1731. self.assertIn(b"foo", porcelain.tag_list(self.repo))
  1732. porcelain.tag_delete(self.repo, b"foo")
  1733. self.assertNotIn(b"foo", porcelain.tag_list(self.repo))
  1734. class ResetTests(PorcelainTestCase):
  1735. def test_hard_head(self) -> None:
  1736. fullpath = os.path.join(self.repo.path, "foo")
  1737. with open(fullpath, "w") as f:
  1738. f.write("BAR")
  1739. porcelain.add(self.repo.path, paths=[fullpath])
  1740. porcelain.commit(
  1741. self.repo.path,
  1742. message=b"Some message",
  1743. committer=b"Jane <jane@example.com>",
  1744. author=b"John <john@example.com>",
  1745. )
  1746. with open(os.path.join(self.repo.path, "foo"), "wb") as f:
  1747. f.write(b"OOH")
  1748. porcelain.reset(self.repo, "hard", b"HEAD")
  1749. index = self.repo.open_index()
  1750. changes = list(
  1751. tree_changes(
  1752. self.repo,
  1753. index.commit(self.repo.object_store),
  1754. self.repo[b"HEAD"].tree,
  1755. )
  1756. )
  1757. self.assertEqual([], changes)
  1758. def test_hard_commit(self) -> None:
  1759. fullpath = os.path.join(self.repo.path, "foo")
  1760. with open(fullpath, "w") as f:
  1761. f.write("BAR")
  1762. porcelain.add(self.repo.path, paths=[fullpath])
  1763. sha = porcelain.commit(
  1764. self.repo.path,
  1765. message=b"Some message",
  1766. committer=b"Jane <jane@example.com>",
  1767. author=b"John <john@example.com>",
  1768. )
  1769. with open(fullpath, "wb") as f:
  1770. f.write(b"BAZ")
  1771. porcelain.add(self.repo.path, paths=[fullpath])
  1772. porcelain.commit(
  1773. self.repo.path,
  1774. message=b"Some other message",
  1775. committer=b"Jane <jane@example.com>",
  1776. author=b"John <john@example.com>",
  1777. )
  1778. porcelain.reset(self.repo, "hard", sha)
  1779. index = self.repo.open_index()
  1780. changes = list(
  1781. tree_changes(
  1782. self.repo,
  1783. index.commit(self.repo.object_store),
  1784. self.repo[sha].tree,
  1785. )
  1786. )
  1787. self.assertEqual([], changes)
  1788. class ResetFileTests(PorcelainTestCase):
  1789. def test_reset_modify_file_to_commit(self) -> None:
  1790. file = "foo"
  1791. full_path = os.path.join(self.repo.path, file)
  1792. with open(full_path, "w") as f:
  1793. f.write("hello")
  1794. porcelain.add(self.repo, paths=[full_path])
  1795. sha = porcelain.commit(
  1796. self.repo,
  1797. message=b"unitest",
  1798. committer=b"Jane <jane@example.com>",
  1799. author=b"John <john@example.com>",
  1800. )
  1801. with open(full_path, "a") as f:
  1802. f.write("something new")
  1803. porcelain.reset_file(self.repo, file, target=sha)
  1804. with open(full_path) as f:
  1805. self.assertEqual("hello", f.read())
  1806. def test_reset_remove_file_to_commit(self) -> None:
  1807. file = "foo"
  1808. full_path = os.path.join(self.repo.path, file)
  1809. with open(full_path, "w") as f:
  1810. f.write("hello")
  1811. porcelain.add(self.repo, paths=[full_path])
  1812. sha = porcelain.commit(
  1813. self.repo,
  1814. message=b"unitest",
  1815. committer=b"Jane <jane@example.com>",
  1816. author=b"John <john@example.com>",
  1817. )
  1818. os.remove(full_path)
  1819. porcelain.reset_file(self.repo, file, target=sha)
  1820. with open(full_path) as f:
  1821. self.assertEqual("hello", f.read())
  1822. def test_resetfile_with_dir(self) -> None:
  1823. os.mkdir(os.path.join(self.repo.path, "new_dir"))
  1824. full_path = os.path.join(self.repo.path, "new_dir", "foo")
  1825. with open(full_path, "w") as f:
  1826. f.write("hello")
  1827. porcelain.add(self.repo, paths=[full_path])
  1828. sha = porcelain.commit(
  1829. self.repo,
  1830. message=b"unitest",
  1831. committer=b"Jane <jane@example.com>",
  1832. author=b"John <john@example.com>",
  1833. )
  1834. with open(full_path, "a") as f:
  1835. f.write("something new")
  1836. porcelain.commit(
  1837. self.repo,
  1838. message=b"unitest 2",
  1839. committer=b"Jane <jane@example.com>",
  1840. author=b"John <john@example.com>",
  1841. )
  1842. porcelain.reset_file(self.repo, os.path.join("new_dir", "foo"), target=sha)
  1843. with open(full_path) as f:
  1844. self.assertEqual("hello", f.read())
  1845. def _commit_file_with_content(repo, filename, content):
  1846. file_path = os.path.join(repo.path, filename)
  1847. with open(file_path, "w") as f:
  1848. f.write(content)
  1849. porcelain.add(repo, paths=[file_path])
  1850. sha = porcelain.commit(
  1851. repo,
  1852. message=b"add " + filename.encode(),
  1853. committer=b"Jane <jane@example.com>",
  1854. author=b"John <john@example.com>",
  1855. )
  1856. return sha, file_path
  1857. class CheckoutTests(PorcelainTestCase):
  1858. def setUp(self) -> None:
  1859. super().setUp()
  1860. self._sha, self._foo_path = _commit_file_with_content(
  1861. self.repo, "foo", "hello\n"
  1862. )
  1863. porcelain.branch_create(self.repo, "uni")
  1864. def test_checkout_to_existing_branch(self) -> None:
  1865. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  1866. porcelain.checkout(self.repo, b"uni")
  1867. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  1868. def test_checkout_to_non_existing_branch(self) -> None:
  1869. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  1870. with self.assertRaises(KeyError):
  1871. porcelain.checkout(self.repo, b"bob")
  1872. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  1873. def test_checkout_to_branch_with_modified_files(self) -> None:
  1874. with open(self._foo_path, "a") as f:
  1875. f.write("new message\n")
  1876. porcelain.add(self.repo, paths=[self._foo_path])
  1877. status = list(porcelain.status(self.repo))
  1878. self.assertEqual(
  1879. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  1880. )
  1881. # The new checkout behavior prevents switching with staged changes
  1882. with self.assertRaises(porcelain.CheckoutError):
  1883. porcelain.checkout(self.repo, b"uni")
  1884. # Should still be on master
  1885. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  1886. # Force checkout should work
  1887. porcelain.checkout(self.repo, b"uni", force=True)
  1888. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  1889. def test_checkout_with_deleted_files(self) -> None:
  1890. porcelain.remove(self.repo.path, [os.path.join(self.repo.path, "foo")])
  1891. status = list(porcelain.status(self.repo))
  1892. self.assertEqual(
  1893. [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status
  1894. )
  1895. # The new checkout behavior prevents switching with staged deletions
  1896. with self.assertRaises(porcelain.CheckoutError):
  1897. porcelain.checkout(self.repo, b"uni")
  1898. # Should still be on master
  1899. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  1900. # Force checkout should work
  1901. porcelain.checkout(self.repo, b"uni", force=True)
  1902. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  1903. def test_checkout_to_branch_with_added_files(self) -> None:
  1904. file_path = os.path.join(self.repo.path, "bar")
  1905. with open(file_path, "w") as f:
  1906. f.write("bar content\n")
  1907. porcelain.add(self.repo, paths=[file_path])
  1908. status = list(porcelain.status(self.repo))
  1909. self.assertEqual(
  1910. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  1911. )
  1912. # Both branches have file 'foo' checkout should be fine.
  1913. porcelain.checkout(self.repo, b"uni")
  1914. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  1915. status = list(porcelain.status(self.repo))
  1916. self.assertEqual(
  1917. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  1918. )
  1919. def test_checkout_to_branch_with_modified_file_not_present(self) -> None:
  1920. # Commit a new file that the other branch doesn't have.
  1921. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  1922. # Modify the file the other branch doesn't have.
  1923. with open(nee_path, "a") as f:
  1924. f.write("bar content\n")
  1925. porcelain.add(self.repo, paths=[nee_path])
  1926. status = list(porcelain.status(self.repo))
  1927. self.assertEqual(
  1928. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  1929. )
  1930. # The new checkout behavior allows switching if the file doesn't exist in target branch
  1931. # (changes can be preserved)
  1932. porcelain.checkout(self.repo, b"uni")
  1933. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  1934. # The staged changes are lost and the file is removed from working tree
  1935. # because it doesn't exist in the target branch
  1936. status = list(porcelain.status(self.repo))
  1937. # File 'nee' is gone completely
  1938. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  1939. self.assertFalse(os.path.exists(nee_path))
  1940. def test_checkout_to_branch_with_modified_file_not_present_forced(self) -> None:
  1941. # Commit a new file that the other branch doesn't have.
  1942. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  1943. # Modify the file the other branch doesn't have.
  1944. with open(nee_path, "a") as f:
  1945. f.write("bar content\n")
  1946. porcelain.add(self.repo, paths=[nee_path])
  1947. status = list(porcelain.status(self.repo))
  1948. self.assertEqual(
  1949. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  1950. )
  1951. # 'uni' branch doesn't have 'nee' and it has been modified, but we force to reset the entire index.
  1952. porcelain.checkout(self.repo, b"uni", force=True)
  1953. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  1954. status = list(porcelain.status(self.repo))
  1955. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  1956. def test_checkout_to_branch_with_unstaged_files(self) -> None:
  1957. # Edit `foo`.
  1958. with open(self._foo_path, "a") as f:
  1959. f.write("new message")
  1960. status = list(porcelain.status(self.repo))
  1961. self.assertEqual(
  1962. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  1963. )
  1964. # The new checkout behavior prevents switching with unstaged changes
  1965. with self.assertRaises(porcelain.CheckoutError):
  1966. porcelain.checkout(self.repo, b"uni")
  1967. # Should still be on master
  1968. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  1969. # Force checkout should work
  1970. porcelain.checkout(self.repo, b"uni", force=True)
  1971. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  1972. def test_checkout_to_branch_with_untracked_files(self) -> None:
  1973. with open(os.path.join(self.repo.path, "neu"), "a") as f:
  1974. f.write("new message\n")
  1975. status = list(porcelain.status(self.repo))
  1976. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  1977. porcelain.checkout(self.repo, b"uni")
  1978. status = list(porcelain.status(self.repo))
  1979. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  1980. def test_checkout_to_branch_with_new_files(self) -> None:
  1981. porcelain.checkout(self.repo, b"uni")
  1982. sub_directory = os.path.join(self.repo.path, "sub1")
  1983. os.mkdir(sub_directory)
  1984. for index in range(5):
  1985. _commit_file_with_content(
  1986. self.repo, "new_file_" + str(index + 1), "Some content\n"
  1987. )
  1988. _commit_file_with_content(
  1989. self.repo,
  1990. os.path.join("sub1", "new_file_" + str(index + 10)),
  1991. "Good content\n",
  1992. )
  1993. status = list(porcelain.status(self.repo))
  1994. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  1995. porcelain.checkout(self.repo, b"master")
  1996. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  1997. status = list(porcelain.status(self.repo))
  1998. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  1999. porcelain.checkout(self.repo, b"uni")
  2000. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2001. status = list(porcelain.status(self.repo))
  2002. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2003. def test_checkout_to_branch_with_file_in_sub_directory(self) -> None:
  2004. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  2005. os.makedirs(sub_directory)
  2006. sub_directory_file = os.path.join(sub_directory, "neu")
  2007. with open(sub_directory_file, "w") as f:
  2008. f.write("new message\n")
  2009. porcelain.add(self.repo, paths=[sub_directory_file])
  2010. porcelain.commit(
  2011. self.repo,
  2012. message=b"add " + sub_directory_file.encode(),
  2013. committer=b"Jane <jane@example.com>",
  2014. author=b"John <john@example.com>",
  2015. )
  2016. status = list(porcelain.status(self.repo))
  2017. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2018. self.assertTrue(os.path.isdir(sub_directory))
  2019. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  2020. porcelain.checkout(self.repo, b"uni")
  2021. status = list(porcelain.status(self.repo))
  2022. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2023. self.assertFalse(os.path.isdir(sub_directory))
  2024. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  2025. porcelain.checkout(self.repo, b"master")
  2026. self.assertTrue(os.path.isdir(sub_directory))
  2027. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  2028. def test_checkout_to_branch_with_multiple_files_in_sub_directory(self) -> None:
  2029. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  2030. os.makedirs(sub_directory)
  2031. sub_directory_file_1 = os.path.join(sub_directory, "neu")
  2032. with open(sub_directory_file_1, "w") as f:
  2033. f.write("new message\n")
  2034. sub_directory_file_2 = os.path.join(sub_directory, "gus")
  2035. with open(sub_directory_file_2, "w") as f:
  2036. f.write("alternative message\n")
  2037. porcelain.add(self.repo, paths=[sub_directory_file_1, sub_directory_file_2])
  2038. porcelain.commit(
  2039. self.repo,
  2040. message=b"add files neu and gus.",
  2041. committer=b"Jane <jane@example.com>",
  2042. author=b"John <john@example.com>",
  2043. )
  2044. status = list(porcelain.status(self.repo))
  2045. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2046. self.assertTrue(os.path.isdir(sub_directory))
  2047. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  2048. porcelain.checkout(self.repo, b"uni")
  2049. status = list(porcelain.status(self.repo))
  2050. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2051. self.assertFalse(os.path.isdir(sub_directory))
  2052. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  2053. def _commit_something_wrong(self):
  2054. with open(self._foo_path, "a") as f:
  2055. f.write("something wrong")
  2056. porcelain.add(self.repo, paths=[self._foo_path])
  2057. return porcelain.commit(
  2058. self.repo,
  2059. message=b"I may added something wrong",
  2060. committer=b"Jane <jane@example.com>",
  2061. author=b"John <john@example.com>",
  2062. )
  2063. def test_checkout_to_commit_sha(self) -> None:
  2064. self._commit_something_wrong()
  2065. porcelain.checkout(self.repo, self._sha)
  2066. self.assertEqual(self._sha, self.repo.head())
  2067. def test_checkout_to_head(self) -> None:
  2068. new_sha = self._commit_something_wrong()
  2069. porcelain.checkout(self.repo, b"HEAD")
  2070. self.assertEqual(new_sha, self.repo.head())
  2071. def _checkout_remote_branch(self):
  2072. errstream = BytesIO()
  2073. outstream = BytesIO()
  2074. porcelain.commit(
  2075. repo=self.repo.path,
  2076. message=b"init",
  2077. author=b"author <email>",
  2078. committer=b"committer <email>",
  2079. )
  2080. # Setup target repo cloned from temp test repo
  2081. clone_path = tempfile.mkdtemp()
  2082. self.addCleanup(shutil.rmtree, clone_path)
  2083. target_repo = porcelain.clone(
  2084. self.repo.path, target=clone_path, errstream=errstream
  2085. )
  2086. try:
  2087. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  2088. finally:
  2089. target_repo.close()
  2090. # create a second file to be pushed back to origin
  2091. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  2092. os.close(handle)
  2093. porcelain.add(repo=clone_path, paths=[fullpath])
  2094. porcelain.commit(
  2095. repo=clone_path,
  2096. message=b"push",
  2097. author=b"author <email>",
  2098. committer=b"committer <email>",
  2099. )
  2100. # Setup a non-checked out branch in the remote
  2101. refs_path = b"refs/heads/foo"
  2102. new_id = self.repo[b"HEAD"].id
  2103. self.assertNotEqual(new_id, ZERO_SHA)
  2104. self.repo.refs[refs_path] = new_id
  2105. # Push to the remote
  2106. porcelain.push(
  2107. clone_path,
  2108. "origin",
  2109. b"HEAD:" + refs_path,
  2110. outstream=outstream,
  2111. errstream=errstream,
  2112. )
  2113. self.assertEqual(
  2114. target_repo.refs[b"refs/remotes/origin/foo"],
  2115. target_repo.refs[b"HEAD"],
  2116. )
  2117. # The new checkout behavior treats origin/foo as a ref and creates detached HEAD
  2118. porcelain.checkout(target_repo, b"origin/foo")
  2119. original_id = target_repo[b"HEAD"].id
  2120. uni_id = target_repo[b"refs/remotes/origin/uni"].id
  2121. # Should be in detached HEAD state
  2122. with self.assertRaises((ValueError, IndexError)):
  2123. porcelain.active_branch(target_repo)
  2124. expected_refs = {
  2125. b"HEAD": original_id,
  2126. b"refs/heads/master": original_id,
  2127. # No local foo branch is created anymore
  2128. b"refs/remotes/origin/foo": original_id,
  2129. b"refs/remotes/origin/uni": uni_id,
  2130. b"refs/remotes/origin/HEAD": new_id,
  2131. b"refs/remotes/origin/master": new_id,
  2132. }
  2133. self.assertEqual(expected_refs, target_repo.get_refs())
  2134. return target_repo
  2135. def test_checkout_remote_branch(self) -> None:
  2136. repo = self._checkout_remote_branch()
  2137. repo.close()
  2138. def test_checkout_remote_branch_then_master_then_remote_branch_again(self) -> None:
  2139. target_repo = self._checkout_remote_branch()
  2140. # Should be in detached HEAD state
  2141. with self.assertRaises((ValueError, IndexError)):
  2142. porcelain.active_branch(target_repo)
  2143. # Save the commit SHA before adding bar
  2144. detached_commit_sha, _ = _commit_file_with_content(
  2145. target_repo, "bar", "something\n"
  2146. )
  2147. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  2148. porcelain.checkout(target_repo, b"master")
  2149. self.assertEqual(b"master", porcelain.active_branch(target_repo))
  2150. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  2151. # Going back to origin/foo won't have bar because the commit was made in detached state
  2152. porcelain.checkout(target_repo, b"origin/foo")
  2153. # Should be in detached HEAD state again
  2154. with self.assertRaises((ValueError, IndexError)):
  2155. porcelain.active_branch(target_repo)
  2156. # bar is NOT there because we're back at the original origin/foo commit
  2157. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  2158. # But we can checkout the specific commit to get bar back
  2159. porcelain.checkout(target_repo, detached_commit_sha.decode())
  2160. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  2161. target_repo.close()
  2162. class GeneralCheckoutTests(PorcelainTestCase):
  2163. """Tests for the general checkout function that handles branches, tags, and commits."""
  2164. def setUp(self) -> None:
  2165. super().setUp()
  2166. # Create initial commit
  2167. self._sha1, self._foo_path = _commit_file_with_content(
  2168. self.repo, "foo", "initial content\n"
  2169. )
  2170. # Create a branch
  2171. porcelain.branch_create(self.repo, "feature")
  2172. # Create another commit on master
  2173. self._sha2, self._bar_path = _commit_file_with_content(
  2174. self.repo, "bar", "bar content\n"
  2175. )
  2176. # Create a tag
  2177. porcelain.tag_create(self.repo, "v1.0", objectish=self._sha1)
  2178. def test_checkout_branch(self) -> None:
  2179. """Test checking out a branch."""
  2180. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2181. # Checkout feature branch
  2182. porcelain.checkout(self.repo, "feature")
  2183. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2184. # File 'bar' should not exist in feature branch
  2185. self.assertFalse(os.path.exists(self._bar_path))
  2186. # Go back to master
  2187. porcelain.checkout(self.repo, "master")
  2188. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2189. # File 'bar' should exist again
  2190. self.assertTrue(os.path.exists(self._bar_path))
  2191. def test_checkout_commit(self) -> None:
  2192. """Test checking out a specific commit (detached HEAD)."""
  2193. # Checkout first commit by SHA
  2194. porcelain.checkout(self.repo, self._sha1.decode("ascii"))
  2195. # Should be in detached HEAD state - active_branch raises IndexError
  2196. with self.assertRaises((ValueError, IndexError)):
  2197. porcelain.active_branch(self.repo)
  2198. # File 'bar' should not exist
  2199. self.assertFalse(os.path.exists(self._bar_path))
  2200. # HEAD should point to the commit
  2201. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  2202. def test_checkout_tag(self) -> None:
  2203. """Test checking out a tag (detached HEAD)."""
  2204. # Checkout tag
  2205. porcelain.checkout(self.repo, "v1.0")
  2206. # Should be in detached HEAD state - active_branch raises IndexError
  2207. with self.assertRaises((ValueError, IndexError)):
  2208. porcelain.active_branch(self.repo)
  2209. # File 'bar' should not exist (tag points to first commit)
  2210. self.assertFalse(os.path.exists(self._bar_path))
  2211. # HEAD should point to the tagged commit
  2212. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  2213. def test_checkout_new_branch(self) -> None:
  2214. """Test creating a new branch during checkout (like git checkout -b)."""
  2215. # Create and checkout new branch from current HEAD
  2216. porcelain.checkout(self.repo, "master", new_branch="new-feature")
  2217. self.assertEqual(b"new-feature", porcelain.active_branch(self.repo))
  2218. self.assertTrue(os.path.exists(self._bar_path))
  2219. # Create and checkout new branch from specific commit
  2220. porcelain.checkout(self.repo, self._sha1.decode("ascii"), new_branch="from-old")
  2221. self.assertEqual(b"from-old", porcelain.active_branch(self.repo))
  2222. self.assertFalse(os.path.exists(self._bar_path))
  2223. def test_checkout_with_uncommitted_changes(self) -> None:
  2224. """Test checkout behavior with uncommitted changes."""
  2225. # Modify a file
  2226. with open(self._foo_path, "w") as f:
  2227. f.write("modified content\n")
  2228. # Should raise error when trying to checkout
  2229. with self.assertRaises(porcelain.CheckoutError) as cm:
  2230. porcelain.checkout(self.repo, "feature")
  2231. self.assertIn("local changes", str(cm.exception))
  2232. self.assertIn("foo", str(cm.exception))
  2233. # Should still be on master
  2234. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2235. def test_checkout_force(self) -> None:
  2236. """Test forced checkout discards local changes."""
  2237. # Modify a file
  2238. with open(self._foo_path, "w") as f:
  2239. f.write("modified content\n")
  2240. # Force checkout should succeed
  2241. porcelain.checkout(self.repo, "feature", force=True)
  2242. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2243. # Local changes should be discarded
  2244. with open(self._foo_path) as f:
  2245. content = f.read()
  2246. self.assertEqual("initial content\n", content)
  2247. def test_checkout_nonexistent_ref(self) -> None:
  2248. """Test checkout of non-existent branch/commit."""
  2249. with self.assertRaises(KeyError):
  2250. porcelain.checkout(self.repo, "nonexistent")
  2251. def test_checkout_partial_sha(self) -> None:
  2252. """Test checkout with partial SHA."""
  2253. # Git typically allows checkout with partial SHA
  2254. partial_sha = self._sha1.decode("ascii")[:7]
  2255. porcelain.checkout(self.repo, partial_sha)
  2256. # Should be in detached HEAD state at the right commit
  2257. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  2258. def test_checkout_preserves_untracked_files(self) -> None:
  2259. """Test that checkout preserves untracked files."""
  2260. # Create an untracked file
  2261. untracked_path = os.path.join(self.repo.path, "untracked.txt")
  2262. with open(untracked_path, "w") as f:
  2263. f.write("untracked content\n")
  2264. # Checkout another branch
  2265. porcelain.checkout(self.repo, "feature")
  2266. # Untracked file should still exist
  2267. self.assertTrue(os.path.exists(untracked_path))
  2268. with open(untracked_path) as f:
  2269. content = f.read()
  2270. self.assertEqual("untracked content\n", content)
  2271. def test_checkout_full_ref_paths(self) -> None:
  2272. """Test checkout with full ref paths."""
  2273. # Test checkout with full branch ref path
  2274. porcelain.checkout(self.repo, "refs/heads/feature")
  2275. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2276. # Test checkout with full tag ref path
  2277. porcelain.checkout(self.repo, "refs/tags/v1.0")
  2278. # Should be in detached HEAD state
  2279. with self.assertRaises((ValueError, IndexError)):
  2280. porcelain.active_branch(self.repo)
  2281. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  2282. def test_checkout_bytes_vs_string_target(self) -> None:
  2283. """Test that checkout works with both bytes and string targets."""
  2284. # Test with string target
  2285. porcelain.checkout(self.repo, "feature")
  2286. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2287. # Test with bytes target
  2288. porcelain.checkout(self.repo, b"master")
  2289. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2290. def test_checkout_new_branch_from_commit(self) -> None:
  2291. """Test creating a new branch from a specific commit."""
  2292. # Create new branch from first commit
  2293. porcelain.checkout(self.repo, self._sha1.decode(), new_branch="from-commit")
  2294. self.assertEqual(b"from-commit", porcelain.active_branch(self.repo))
  2295. # Should be at the first commit (no bar file)
  2296. self.assertFalse(os.path.exists(self._bar_path))
  2297. def test_checkout_with_staged_addition(self) -> None:
  2298. """Test checkout behavior with staged file additions."""
  2299. # Create and stage a new file that doesn't exist in target branch
  2300. new_file_path = os.path.join(self.repo.path, "new.txt")
  2301. with open(new_file_path, "w") as f:
  2302. f.write("new file content\n")
  2303. porcelain.add(self.repo, [new_file_path])
  2304. # This should succeed because the file doesn't exist in target branch
  2305. porcelain.checkout(self.repo, "feature")
  2306. # Should be on feature branch
  2307. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2308. # The new file should still exist and be staged
  2309. self.assertTrue(os.path.exists(new_file_path))
  2310. status = porcelain.status(self.repo)
  2311. self.assertIn(b"new.txt", status.staged["add"])
  2312. def test_checkout_with_staged_modification_conflict(self) -> None:
  2313. """Test checkout behavior with staged modifications that would conflict."""
  2314. # Stage changes to a file that exists in both branches
  2315. with open(self._foo_path, "w") as f:
  2316. f.write("modified content\n")
  2317. porcelain.add(self.repo, [self._foo_path])
  2318. # Should prevent checkout due to staged changes to existing file
  2319. with self.assertRaises(porcelain.CheckoutError) as cm:
  2320. porcelain.checkout(self.repo, "feature")
  2321. self.assertIn("local changes", str(cm.exception))
  2322. self.assertIn("foo", str(cm.exception))
  2323. def test_checkout_head_reference(self) -> None:
  2324. """Test checkout of HEAD reference."""
  2325. # Move to feature branch first
  2326. porcelain.checkout(self.repo, "feature")
  2327. # Checkout HEAD creates detached HEAD state
  2328. porcelain.checkout(self.repo, "HEAD")
  2329. # Should be in detached HEAD state
  2330. with self.assertRaises((ValueError, IndexError)):
  2331. porcelain.active_branch(self.repo)
  2332. def test_checkout_error_messages(self) -> None:
  2333. """Test that checkout error messages are helpful."""
  2334. # Create uncommitted changes
  2335. with open(self._foo_path, "w") as f:
  2336. f.write("uncommitted changes\n")
  2337. # Try to checkout
  2338. with self.assertRaises(porcelain.CheckoutError) as cm:
  2339. porcelain.checkout(self.repo, "feature")
  2340. error_msg = str(cm.exception)
  2341. self.assertIn("local changes", error_msg)
  2342. self.assertIn("foo", error_msg)
  2343. self.assertIn("overwritten", error_msg)
  2344. self.assertIn("commit or stash", error_msg)
  2345. class SubmoduleTests(PorcelainTestCase):
  2346. def test_empty(self) -> None:
  2347. porcelain.commit(
  2348. repo=self.repo.path,
  2349. message=b"init",
  2350. author=b"author <email>",
  2351. committer=b"committer <email>",
  2352. )
  2353. self.assertEqual([], list(porcelain.submodule_list(self.repo)))
  2354. def test_add(self) -> None:
  2355. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  2356. with open(f"{self.repo.path}/.gitmodules") as f:
  2357. self.assertEqual(
  2358. """\
  2359. [submodule "bar"]
  2360. \turl = ../bar.git
  2361. \tpath = bar
  2362. """,
  2363. f.read(),
  2364. )
  2365. def test_init(self) -> None:
  2366. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  2367. porcelain.submodule_init(self.repo)
  2368. class PushTests(PorcelainTestCase):
  2369. def test_simple(self) -> None:
  2370. """Basic test of porcelain push where self.repo is the remote. First
  2371. clone the remote, commit a file to the clone, then push the changes
  2372. back to the remote.
  2373. """
  2374. outstream = BytesIO()
  2375. errstream = BytesIO()
  2376. porcelain.commit(
  2377. repo=self.repo.path,
  2378. message=b"init",
  2379. author=b"author <email>",
  2380. committer=b"committer <email>",
  2381. )
  2382. # Setup target repo cloned from temp test repo
  2383. clone_path = tempfile.mkdtemp()
  2384. self.addCleanup(shutil.rmtree, clone_path)
  2385. target_repo = porcelain.clone(
  2386. self.repo.path, target=clone_path, errstream=errstream
  2387. )
  2388. try:
  2389. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  2390. finally:
  2391. target_repo.close()
  2392. # create a second file to be pushed back to origin
  2393. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  2394. os.close(handle)
  2395. porcelain.add(repo=clone_path, paths=[fullpath])
  2396. porcelain.commit(
  2397. repo=clone_path,
  2398. message=b"push",
  2399. author=b"author <email>",
  2400. committer=b"committer <email>",
  2401. )
  2402. # Setup a non-checked out branch in the remote
  2403. refs_path = b"refs/heads/foo"
  2404. new_id = self.repo[b"HEAD"].id
  2405. self.assertNotEqual(new_id, ZERO_SHA)
  2406. self.repo.refs[refs_path] = new_id
  2407. # Push to the remote
  2408. porcelain.push(
  2409. clone_path,
  2410. "origin",
  2411. b"HEAD:" + refs_path,
  2412. outstream=outstream,
  2413. errstream=errstream,
  2414. )
  2415. self.assertEqual(
  2416. target_repo.refs[b"refs/remotes/origin/foo"],
  2417. target_repo.refs[b"HEAD"],
  2418. )
  2419. # Check that the target and source
  2420. with Repo(clone_path) as r_clone:
  2421. self.assertEqual(
  2422. {
  2423. b"HEAD": new_id,
  2424. b"refs/heads/foo": r_clone[b"HEAD"].id,
  2425. b"refs/heads/master": new_id,
  2426. },
  2427. self.repo.get_refs(),
  2428. )
  2429. self.assertEqual(r_clone[b"HEAD"].id, self.repo[refs_path].id)
  2430. # Get the change in the target repo corresponding to the add
  2431. # this will be in the foo branch.
  2432. change = next(
  2433. iter(
  2434. tree_changes(
  2435. self.repo,
  2436. self.repo[b"HEAD"].tree,
  2437. self.repo[b"refs/heads/foo"].tree,
  2438. )
  2439. )
  2440. )
  2441. self.assertEqual(
  2442. os.path.basename(fullpath), change.new.path.decode("ascii")
  2443. )
  2444. def test_local_missing(self) -> None:
  2445. """Pushing a new branch."""
  2446. outstream = BytesIO()
  2447. errstream = BytesIO()
  2448. # Setup target repo cloned from temp test repo
  2449. clone_path = tempfile.mkdtemp()
  2450. self.addCleanup(shutil.rmtree, clone_path)
  2451. target_repo = porcelain.init(clone_path)
  2452. target_repo.close()
  2453. self.assertRaises(
  2454. porcelain.Error,
  2455. porcelain.push,
  2456. self.repo,
  2457. clone_path,
  2458. b"HEAD:refs/heads/master",
  2459. outstream=outstream,
  2460. errstream=errstream,
  2461. )
  2462. def test_new(self) -> None:
  2463. """Pushing a new branch."""
  2464. outstream = BytesIO()
  2465. errstream = BytesIO()
  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.init(clone_path)
  2470. target_repo.close()
  2471. # create a second file to be pushed back to origin
  2472. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  2473. os.close(handle)
  2474. porcelain.add(repo=clone_path, paths=[fullpath])
  2475. new_id = porcelain.commit(
  2476. repo=self.repo,
  2477. message=b"push",
  2478. author=b"author <email>",
  2479. committer=b"committer <email>",
  2480. )
  2481. # Push to the remote
  2482. porcelain.push(
  2483. self.repo,
  2484. clone_path,
  2485. b"HEAD:refs/heads/master",
  2486. outstream=outstream,
  2487. errstream=errstream,
  2488. )
  2489. with Repo(clone_path) as r_clone:
  2490. self.assertEqual(
  2491. {
  2492. b"HEAD": new_id,
  2493. b"refs/heads/master": new_id,
  2494. },
  2495. r_clone.get_refs(),
  2496. )
  2497. def test_delete(self) -> None:
  2498. """Basic test of porcelain push, removing a branch."""
  2499. outstream = BytesIO()
  2500. errstream = BytesIO()
  2501. porcelain.commit(
  2502. repo=self.repo.path,
  2503. message=b"init",
  2504. author=b"author <email>",
  2505. committer=b"committer <email>",
  2506. )
  2507. # Setup target repo cloned from temp test repo
  2508. clone_path = tempfile.mkdtemp()
  2509. self.addCleanup(shutil.rmtree, clone_path)
  2510. target_repo = porcelain.clone(
  2511. self.repo.path, target=clone_path, errstream=errstream
  2512. )
  2513. target_repo.close()
  2514. # Setup a non-checked out branch in the remote
  2515. refs_path = b"refs/heads/foo"
  2516. new_id = self.repo[b"HEAD"].id
  2517. self.assertNotEqual(new_id, ZERO_SHA)
  2518. self.repo.refs[refs_path] = new_id
  2519. # Push to the remote
  2520. porcelain.push(
  2521. clone_path,
  2522. self.repo.path,
  2523. b":" + refs_path,
  2524. outstream=outstream,
  2525. errstream=errstream,
  2526. )
  2527. self.assertEqual(
  2528. {
  2529. b"HEAD": new_id,
  2530. b"refs/heads/master": new_id,
  2531. },
  2532. self.repo.get_refs(),
  2533. )
  2534. def test_diverged(self) -> None:
  2535. outstream = BytesIO()
  2536. errstream = BytesIO()
  2537. porcelain.commit(
  2538. repo=self.repo.path,
  2539. message=b"init",
  2540. author=b"author <email>",
  2541. committer=b"committer <email>",
  2542. )
  2543. # Setup target repo cloned from temp test repo
  2544. clone_path = tempfile.mkdtemp()
  2545. self.addCleanup(shutil.rmtree, clone_path)
  2546. target_repo = porcelain.clone(
  2547. self.repo.path, target=clone_path, errstream=errstream
  2548. )
  2549. target_repo.close()
  2550. remote_id = porcelain.commit(
  2551. repo=self.repo.path,
  2552. message=b"remote change",
  2553. author=b"author <email>",
  2554. committer=b"committer <email>",
  2555. )
  2556. local_id = porcelain.commit(
  2557. repo=clone_path,
  2558. message=b"local change",
  2559. author=b"author <email>",
  2560. committer=b"committer <email>",
  2561. )
  2562. outstream = BytesIO()
  2563. errstream = BytesIO()
  2564. # Push to the remote
  2565. self.assertRaises(
  2566. porcelain.DivergedBranches,
  2567. porcelain.push,
  2568. clone_path,
  2569. self.repo.path,
  2570. b"refs/heads/master",
  2571. outstream=outstream,
  2572. errstream=errstream,
  2573. )
  2574. self.assertEqual(
  2575. {
  2576. b"HEAD": remote_id,
  2577. b"refs/heads/master": remote_id,
  2578. },
  2579. self.repo.get_refs(),
  2580. )
  2581. self.assertEqual(b"", outstream.getvalue())
  2582. self.assertEqual(b"", errstream.getvalue())
  2583. outstream = BytesIO()
  2584. errstream = BytesIO()
  2585. # Push to the remote with --force
  2586. porcelain.push(
  2587. clone_path,
  2588. self.repo.path,
  2589. b"refs/heads/master",
  2590. outstream=outstream,
  2591. errstream=errstream,
  2592. force=True,
  2593. )
  2594. self.assertEqual(
  2595. {
  2596. b"HEAD": local_id,
  2597. b"refs/heads/master": local_id,
  2598. },
  2599. self.repo.get_refs(),
  2600. )
  2601. self.assertEqual(b"", outstream.getvalue())
  2602. self.assertTrue(re.match(b"Push to .* successful.\n", errstream.getvalue()))
  2603. class PullTests(PorcelainTestCase):
  2604. def setUp(self) -> None:
  2605. super().setUp()
  2606. # create a file for initial commit
  2607. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  2608. os.close(handle)
  2609. porcelain.add(repo=self.repo.path, paths=fullpath)
  2610. porcelain.commit(
  2611. repo=self.repo.path,
  2612. message=b"test",
  2613. author=b"test <email>",
  2614. committer=b"test <email>",
  2615. )
  2616. # Setup target repo
  2617. self.target_path = tempfile.mkdtemp()
  2618. self.addCleanup(shutil.rmtree, self.target_path)
  2619. target_repo = porcelain.clone(
  2620. self.repo.path, target=self.target_path, errstream=BytesIO()
  2621. )
  2622. target_repo.close()
  2623. # create a second file to be pushed
  2624. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  2625. os.close(handle)
  2626. porcelain.add(repo=self.repo.path, paths=fullpath)
  2627. porcelain.commit(
  2628. repo=self.repo.path,
  2629. message=b"test2",
  2630. author=b"test2 <email>",
  2631. committer=b"test2 <email>",
  2632. )
  2633. self.assertIn(b"refs/heads/master", self.repo.refs)
  2634. self.assertIn(b"refs/heads/master", target_repo.refs)
  2635. def test_simple(self) -> None:
  2636. outstream = BytesIO()
  2637. errstream = BytesIO()
  2638. # Pull changes into the cloned repo
  2639. porcelain.pull(
  2640. self.target_path,
  2641. self.repo.path,
  2642. b"refs/heads/master",
  2643. outstream=outstream,
  2644. errstream=errstream,
  2645. )
  2646. # Check the target repo for pushed changes
  2647. with Repo(self.target_path) as r:
  2648. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  2649. def test_diverged(self) -> None:
  2650. outstream = BytesIO()
  2651. errstream = BytesIO()
  2652. c3a = porcelain.commit(
  2653. repo=self.target_path,
  2654. message=b"test3a",
  2655. author=b"test2 <email>",
  2656. committer=b"test2 <email>",
  2657. )
  2658. porcelain.commit(
  2659. repo=self.repo.path,
  2660. message=b"test3b",
  2661. author=b"test2 <email>",
  2662. committer=b"test2 <email>",
  2663. )
  2664. # Pull changes into the cloned repo
  2665. self.assertRaises(
  2666. porcelain.DivergedBranches,
  2667. porcelain.pull,
  2668. self.target_path,
  2669. self.repo.path,
  2670. b"refs/heads/master",
  2671. outstream=outstream,
  2672. errstream=errstream,
  2673. )
  2674. # Check the target repo for pushed changes
  2675. with Repo(self.target_path) as r:
  2676. self.assertEqual(r[b"refs/heads/master"].id, c3a)
  2677. # Pull with merge should now work
  2678. porcelain.pull(
  2679. self.target_path,
  2680. self.repo.path,
  2681. b"refs/heads/master",
  2682. outstream=outstream,
  2683. errstream=errstream,
  2684. fast_forward=False,
  2685. )
  2686. # Check the target repo for merged changes
  2687. with Repo(self.target_path) as r:
  2688. # HEAD should now be a merge commit
  2689. head = r[b"HEAD"]
  2690. # It should have two parents
  2691. self.assertEqual(len(head.parents), 2)
  2692. # One parent should be the previous HEAD (c3a)
  2693. self.assertIn(c3a, head.parents)
  2694. # The other parent should be from the source repo
  2695. self.assertIn(self.repo[b"HEAD"].id, head.parents)
  2696. def test_no_refspec(self) -> None:
  2697. outstream = BytesIO()
  2698. errstream = BytesIO()
  2699. # Pull changes into the cloned repo
  2700. porcelain.pull(
  2701. self.target_path,
  2702. self.repo.path,
  2703. outstream=outstream,
  2704. errstream=errstream,
  2705. )
  2706. # Check the target repo for pushed changes
  2707. with Repo(self.target_path) as r:
  2708. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  2709. def test_no_remote_location(self) -> None:
  2710. outstream = BytesIO()
  2711. errstream = BytesIO()
  2712. # Pull changes into the cloned repo
  2713. porcelain.pull(
  2714. self.target_path,
  2715. refspecs=b"refs/heads/master",
  2716. outstream=outstream,
  2717. errstream=errstream,
  2718. )
  2719. # Check the target repo for pushed changes
  2720. with Repo(self.target_path) as r:
  2721. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  2722. def test_pull_updates_working_tree(self) -> None:
  2723. """Test that pull updates the working tree with new files."""
  2724. outstream = BytesIO()
  2725. errstream = BytesIO()
  2726. # Create a new file with content in the source repo
  2727. new_file = os.path.join(self.repo.path, "newfile.txt")
  2728. with open(new_file, "w") as f:
  2729. f.write("This is new content")
  2730. porcelain.add(repo=self.repo.path, paths=[new_file])
  2731. porcelain.commit(
  2732. repo=self.repo.path,
  2733. message=b"Add new file",
  2734. author=b"test <email>",
  2735. committer=b"test <email>",
  2736. )
  2737. # Before pull, the file should not exist in target
  2738. target_file = os.path.join(self.target_path, "newfile.txt")
  2739. self.assertFalse(os.path.exists(target_file))
  2740. # Pull changes into the cloned repo
  2741. porcelain.pull(
  2742. self.target_path,
  2743. self.repo.path,
  2744. b"refs/heads/master",
  2745. outstream=outstream,
  2746. errstream=errstream,
  2747. )
  2748. # After pull, the file should exist with correct content
  2749. self.assertTrue(os.path.exists(target_file))
  2750. with open(target_file) as f:
  2751. self.assertEqual(f.read(), "This is new content")
  2752. # Check the HEAD is updated too
  2753. with Repo(self.target_path) as r:
  2754. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  2755. class StatusTests(PorcelainTestCase):
  2756. def test_empty(self) -> None:
  2757. results = porcelain.status(self.repo)
  2758. self.assertEqual({"add": [], "delete": [], "modify": []}, results.staged)
  2759. self.assertEqual([], results.unstaged)
  2760. def test_status_base(self) -> None:
  2761. """Integration test for `status` functionality."""
  2762. # Commit a dummy file then modify it
  2763. fullpath = os.path.join(self.repo.path, "foo")
  2764. with open(fullpath, "w") as f:
  2765. f.write("origstuff")
  2766. porcelain.add(repo=self.repo.path, paths=[fullpath])
  2767. porcelain.commit(
  2768. repo=self.repo.path,
  2769. message=b"test status",
  2770. author=b"author <email>",
  2771. committer=b"committer <email>",
  2772. )
  2773. # modify access and modify time of path
  2774. os.utime(fullpath, (0, 0))
  2775. with open(fullpath, "wb") as f:
  2776. f.write(b"stuff")
  2777. # Make a dummy file and stage it
  2778. filename_add = "bar"
  2779. fullpath = os.path.join(self.repo.path, filename_add)
  2780. with open(fullpath, "w") as f:
  2781. f.write("stuff")
  2782. porcelain.add(repo=self.repo.path, paths=fullpath)
  2783. results = porcelain.status(self.repo)
  2784. self.assertEqual(results.staged["add"][0], filename_add.encode("ascii"))
  2785. self.assertEqual(results.unstaged, [b"foo"])
  2786. def test_status_all(self) -> None:
  2787. del_path = os.path.join(self.repo.path, "foo")
  2788. mod_path = os.path.join(self.repo.path, "bar")
  2789. add_path = os.path.join(self.repo.path, "baz")
  2790. us_path = os.path.join(self.repo.path, "blye")
  2791. ut_path = os.path.join(self.repo.path, "blyat")
  2792. with open(del_path, "w") as f:
  2793. f.write("origstuff")
  2794. with open(mod_path, "w") as f:
  2795. f.write("origstuff")
  2796. with open(us_path, "w") as f:
  2797. f.write("origstuff")
  2798. porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path])
  2799. porcelain.commit(
  2800. repo=self.repo.path,
  2801. message=b"test status",
  2802. author=b"author <email>",
  2803. committer=b"committer <email>",
  2804. )
  2805. porcelain.remove(self.repo.path, [del_path])
  2806. with open(add_path, "w") as f:
  2807. f.write("origstuff")
  2808. with open(mod_path, "w") as f:
  2809. f.write("more_origstuff")
  2810. with open(us_path, "w") as f:
  2811. f.write("more_origstuff")
  2812. porcelain.add(repo=self.repo.path, paths=[add_path, mod_path])
  2813. with open(us_path, "w") as f:
  2814. f.write("\norigstuff")
  2815. with open(ut_path, "w") as f:
  2816. f.write("origstuff")
  2817. results = porcelain.status(self.repo.path)
  2818. self.assertDictEqual(
  2819. {"add": [b"baz"], "delete": [b"foo"], "modify": [b"bar"]},
  2820. results.staged,
  2821. )
  2822. self.assertListEqual(results.unstaged, [b"blye"])
  2823. results_no_untracked = porcelain.status(self.repo.path, untracked_files="no")
  2824. self.assertListEqual(results_no_untracked.untracked, [])
  2825. def test_status_wrong_untracked_files_value(self) -> None:
  2826. with self.assertRaises(ValueError):
  2827. porcelain.status(self.repo.path, untracked_files="antani")
  2828. def test_status_untracked_path(self) -> None:
  2829. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  2830. os.mkdir(untracked_dir)
  2831. untracked_file = os.path.join(untracked_dir, "untracked_file")
  2832. with open(untracked_file, "w") as fh:
  2833. fh.write("untracked")
  2834. _, _, untracked = porcelain.status(self.repo.path, untracked_files="all")
  2835. self.assertEqual(untracked, ["untracked_dir/untracked_file"])
  2836. def test_status_crlf_mismatch(self) -> None:
  2837. # First make a commit as if the file has been added on a Linux system
  2838. # or with core.autocrlf=True
  2839. file_path = os.path.join(self.repo.path, "crlf")
  2840. with open(file_path, "wb") as f:
  2841. f.write(b"line1\nline2")
  2842. porcelain.add(repo=self.repo.path, paths=[file_path])
  2843. porcelain.commit(
  2844. repo=self.repo.path,
  2845. message=b"test status",
  2846. author=b"author <email>",
  2847. committer=b"committer <email>",
  2848. )
  2849. # Then update the file as if it was created by CGit on a Windows
  2850. # system with core.autocrlf=true
  2851. with open(file_path, "wb") as f:
  2852. f.write(b"line1\r\nline2")
  2853. results = porcelain.status(self.repo)
  2854. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  2855. self.assertListEqual(results.unstaged, [b"crlf"])
  2856. self.assertListEqual(results.untracked, [])
  2857. def test_status_autocrlf_true(self) -> None:
  2858. # First make a commit as if the file has been added on a Linux system
  2859. # or with core.autocrlf=True
  2860. file_path = os.path.join(self.repo.path, "crlf")
  2861. with open(file_path, "wb") as f:
  2862. f.write(b"line1\nline2")
  2863. porcelain.add(repo=self.repo.path, paths=[file_path])
  2864. porcelain.commit(
  2865. repo=self.repo.path,
  2866. message=b"test status",
  2867. author=b"author <email>",
  2868. committer=b"committer <email>",
  2869. )
  2870. # Then update the file as if it was created by CGit on a Windows
  2871. # system with core.autocrlf=true
  2872. with open(file_path, "wb") as f:
  2873. f.write(b"line1\r\nline2")
  2874. # TODO: It should be set automatically by looking at the configuration
  2875. c = self.repo.get_config()
  2876. c.set("core", "autocrlf", True)
  2877. c.write_to_path()
  2878. results = porcelain.status(self.repo)
  2879. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  2880. self.assertListEqual(results.unstaged, [])
  2881. self.assertListEqual(results.untracked, [])
  2882. def test_status_autocrlf_input(self) -> None:
  2883. # Commit existing file with CRLF
  2884. file_path = os.path.join(self.repo.path, "crlf-exists")
  2885. with open(file_path, "wb") as f:
  2886. f.write(b"line1\r\nline2")
  2887. porcelain.add(repo=self.repo.path, paths=[file_path])
  2888. porcelain.commit(
  2889. repo=self.repo.path,
  2890. message=b"test status",
  2891. author=b"author <email>",
  2892. committer=b"committer <email>",
  2893. )
  2894. c = self.repo.get_config()
  2895. c.set("core", "autocrlf", "input")
  2896. c.write_to_path()
  2897. # Add new (untracked) file
  2898. file_path = os.path.join(self.repo.path, "crlf-new")
  2899. with open(file_path, "wb") as f:
  2900. f.write(b"line1\r\nline2")
  2901. porcelain.add(repo=self.repo.path, paths=[file_path])
  2902. results = porcelain.status(self.repo)
  2903. self.assertDictEqual(
  2904. {"add": [b"crlf-new"], "delete": [], "modify": []}, results.staged
  2905. )
  2906. self.assertListEqual(results.unstaged, [])
  2907. self.assertListEqual(results.untracked, [])
  2908. def test_get_tree_changes_add(self) -> None:
  2909. """Unit test for get_tree_changes add."""
  2910. # Make a dummy file, stage
  2911. filename = "bar"
  2912. fullpath = os.path.join(self.repo.path, filename)
  2913. with open(fullpath, "w") as f:
  2914. f.write("stuff")
  2915. porcelain.add(repo=self.repo.path, paths=fullpath)
  2916. porcelain.commit(
  2917. repo=self.repo.path,
  2918. message=b"test status",
  2919. author=b"author <email>",
  2920. committer=b"committer <email>",
  2921. )
  2922. filename = "foo"
  2923. fullpath = os.path.join(self.repo.path, filename)
  2924. with open(fullpath, "w") as f:
  2925. f.write("stuff")
  2926. porcelain.add(repo=self.repo.path, paths=fullpath)
  2927. changes = porcelain.get_tree_changes(self.repo.path)
  2928. self.assertEqual(changes["add"][0], filename.encode("ascii"))
  2929. self.assertEqual(len(changes["add"]), 1)
  2930. self.assertEqual(len(changes["modify"]), 0)
  2931. self.assertEqual(len(changes["delete"]), 0)
  2932. def test_get_tree_changes_modify(self) -> None:
  2933. """Unit test for get_tree_changes modify."""
  2934. # Make a dummy file, stage, commit, modify
  2935. filename = "foo"
  2936. fullpath = os.path.join(self.repo.path, filename)
  2937. with open(fullpath, "w") as f:
  2938. f.write("stuff")
  2939. porcelain.add(repo=self.repo.path, paths=fullpath)
  2940. porcelain.commit(
  2941. repo=self.repo.path,
  2942. message=b"test status",
  2943. author=b"author <email>",
  2944. committer=b"committer <email>",
  2945. )
  2946. with open(fullpath, "w") as f:
  2947. f.write("otherstuff")
  2948. porcelain.add(repo=self.repo.path, paths=fullpath)
  2949. changes = porcelain.get_tree_changes(self.repo.path)
  2950. self.assertEqual(changes["modify"][0], filename.encode("ascii"))
  2951. self.assertEqual(len(changes["add"]), 0)
  2952. self.assertEqual(len(changes["modify"]), 1)
  2953. self.assertEqual(len(changes["delete"]), 0)
  2954. def test_get_tree_changes_delete(self) -> None:
  2955. """Unit test for get_tree_changes delete."""
  2956. # Make a dummy file, stage, commit, remove
  2957. filename = "foo"
  2958. fullpath = os.path.join(self.repo.path, filename)
  2959. with open(fullpath, "w") as f:
  2960. f.write("stuff")
  2961. porcelain.add(repo=self.repo.path, paths=fullpath)
  2962. porcelain.commit(
  2963. repo=self.repo.path,
  2964. message=b"test status",
  2965. author=b"author <email>",
  2966. committer=b"committer <email>",
  2967. )
  2968. cwd = os.getcwd()
  2969. try:
  2970. os.chdir(self.repo.path)
  2971. porcelain.remove(repo=self.repo.path, paths=[filename])
  2972. finally:
  2973. os.chdir(cwd)
  2974. changes = porcelain.get_tree_changes(self.repo.path)
  2975. self.assertEqual(changes["delete"][0], filename.encode("ascii"))
  2976. self.assertEqual(len(changes["add"]), 0)
  2977. self.assertEqual(len(changes["modify"]), 0)
  2978. self.assertEqual(len(changes["delete"]), 1)
  2979. def test_get_untracked_paths(self) -> None:
  2980. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  2981. f.write("ignored\n")
  2982. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  2983. f.write("blah\n")
  2984. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  2985. f.write("blah\n")
  2986. os.symlink(
  2987. os.path.join(self.repo.path, os.pardir, "external_target"),
  2988. os.path.join(self.repo.path, "link"),
  2989. )
  2990. self.assertEqual(
  2991. {"ignored", "notignored", ".gitignore", "link"},
  2992. set(
  2993. porcelain.get_untracked_paths(
  2994. self.repo.path, self.repo.path, self.repo.open_index()
  2995. )
  2996. ),
  2997. )
  2998. self.assertEqual(
  2999. {".gitignore", "notignored", "link"},
  3000. set(porcelain.status(self.repo).untracked),
  3001. )
  3002. self.assertEqual(
  3003. {".gitignore", "notignored", "ignored", "link"},
  3004. set(porcelain.status(self.repo, ignored=True).untracked),
  3005. )
  3006. def test_get_untracked_paths_subrepo(self) -> None:
  3007. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3008. f.write("nested/\n")
  3009. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  3010. f.write("blah\n")
  3011. subrepo = Repo.init(os.path.join(self.repo.path, "nested"), mkdir=True)
  3012. with open(os.path.join(subrepo.path, "ignored"), "w") as f:
  3013. f.write("bleep\n")
  3014. with open(os.path.join(subrepo.path, "with"), "w") as f:
  3015. f.write("bloop\n")
  3016. with open(os.path.join(subrepo.path, "manager"), "w") as f:
  3017. f.write("blop\n")
  3018. self.assertEqual(
  3019. {".gitignore", "notignored", os.path.join("nested", "")},
  3020. set(
  3021. porcelain.get_untracked_paths(
  3022. self.repo.path, self.repo.path, self.repo.open_index()
  3023. )
  3024. ),
  3025. )
  3026. self.assertEqual(
  3027. {".gitignore", "notignored"},
  3028. set(
  3029. porcelain.get_untracked_paths(
  3030. self.repo.path,
  3031. self.repo.path,
  3032. self.repo.open_index(),
  3033. exclude_ignored=True,
  3034. )
  3035. ),
  3036. )
  3037. self.assertEqual(
  3038. {"ignored", "with", "manager"},
  3039. set(
  3040. porcelain.get_untracked_paths(
  3041. subrepo.path, subrepo.path, subrepo.open_index()
  3042. )
  3043. ),
  3044. )
  3045. self.assertEqual(
  3046. set(),
  3047. set(
  3048. porcelain.get_untracked_paths(
  3049. subrepo.path,
  3050. self.repo.path,
  3051. self.repo.open_index(),
  3052. )
  3053. ),
  3054. )
  3055. self.assertEqual(
  3056. {
  3057. os.path.join("nested", "ignored"),
  3058. os.path.join("nested", "with"),
  3059. os.path.join("nested", "manager"),
  3060. },
  3061. set(
  3062. porcelain.get_untracked_paths(
  3063. self.repo.path,
  3064. subrepo.path,
  3065. self.repo.open_index(),
  3066. )
  3067. ),
  3068. )
  3069. def test_get_untracked_paths_subdir(self) -> None:
  3070. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3071. f.write("subdir/\nignored")
  3072. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  3073. f.write("blah\n")
  3074. os.mkdir(os.path.join(self.repo.path, "subdir"))
  3075. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  3076. f.write("foo")
  3077. with open(os.path.join(self.repo.path, "subdir", "ignored"), "w") as f:
  3078. f.write("foo")
  3079. self.assertEqual(
  3080. {
  3081. ".gitignore",
  3082. "notignored",
  3083. "ignored",
  3084. os.path.join("subdir", ""),
  3085. },
  3086. set(
  3087. porcelain.get_untracked_paths(
  3088. self.repo.path,
  3089. self.repo.path,
  3090. self.repo.open_index(),
  3091. )
  3092. ),
  3093. )
  3094. self.assertEqual(
  3095. {".gitignore", "notignored"},
  3096. set(
  3097. porcelain.get_untracked_paths(
  3098. self.repo.path,
  3099. self.repo.path,
  3100. self.repo.open_index(),
  3101. exclude_ignored=True,
  3102. )
  3103. ),
  3104. )
  3105. def test_get_untracked_paths_invalid_untracked_files(self) -> None:
  3106. with self.assertRaises(ValueError):
  3107. list(
  3108. porcelain.get_untracked_paths(
  3109. self.repo.path,
  3110. self.repo.path,
  3111. self.repo.open_index(),
  3112. untracked_files="invalid_value",
  3113. )
  3114. )
  3115. def test_get_untracked_paths_normal(self) -> None:
  3116. with self.assertRaises(NotImplementedError):
  3117. _, _, _ = porcelain.status(repo=self.repo.path, untracked_files="normal")
  3118. # TODO(jelmer): Add test for dulwich.porcelain.daemon
  3119. class UploadPackTests(PorcelainTestCase):
  3120. """Tests for upload_pack."""
  3121. def test_upload_pack(self) -> None:
  3122. outf = BytesIO()
  3123. exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf)
  3124. outlines = outf.getvalue().splitlines()
  3125. self.assertEqual([b"0000"], outlines)
  3126. self.assertEqual(0, exitcode)
  3127. class ReceivePackTests(PorcelainTestCase):
  3128. """Tests for receive_pack."""
  3129. def test_receive_pack(self) -> None:
  3130. filename = "foo"
  3131. fullpath = os.path.join(self.repo.path, filename)
  3132. with open(fullpath, "w") as f:
  3133. f.write("stuff")
  3134. porcelain.add(repo=self.repo.path, paths=fullpath)
  3135. self.repo.do_commit(
  3136. message=b"test status",
  3137. author=b"author <email>",
  3138. committer=b"committer <email>",
  3139. author_timestamp=1402354300,
  3140. commit_timestamp=1402354300,
  3141. author_timezone=0,
  3142. commit_timezone=0,
  3143. )
  3144. outf = BytesIO()
  3145. exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf)
  3146. outlines = outf.getvalue().splitlines()
  3147. self.assertEqual(
  3148. [
  3149. b"0091319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status "
  3150. b"delete-refs quiet ofs-delta side-band-64k "
  3151. b"no-done symref=HEAD:refs/heads/master",
  3152. b"003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master",
  3153. b"0000",
  3154. ],
  3155. outlines,
  3156. )
  3157. self.assertEqual(0, exitcode)
  3158. class BranchListTests(PorcelainTestCase):
  3159. def test_standard(self) -> None:
  3160. self.assertEqual(set(), set(porcelain.branch_list(self.repo)))
  3161. def test_new_branch(self) -> None:
  3162. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3163. self.repo[b"HEAD"] = c1.id
  3164. porcelain.branch_create(self.repo, b"foo")
  3165. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  3166. class BranchCreateTests(PorcelainTestCase):
  3167. def test_branch_exists(self) -> None:
  3168. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3169. self.repo[b"HEAD"] = c1.id
  3170. porcelain.branch_create(self.repo, b"foo")
  3171. self.assertRaises(porcelain.Error, porcelain.branch_create, self.repo, b"foo")
  3172. porcelain.branch_create(self.repo, b"foo", force=True)
  3173. def test_new_branch(self) -> None:
  3174. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3175. self.repo[b"HEAD"] = c1.id
  3176. porcelain.branch_create(self.repo, b"foo")
  3177. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  3178. class BranchDeleteTests(PorcelainTestCase):
  3179. def test_simple(self) -> None:
  3180. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3181. self.repo[b"HEAD"] = c1.id
  3182. porcelain.branch_create(self.repo, b"foo")
  3183. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  3184. porcelain.branch_delete(self.repo, b"foo")
  3185. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  3186. def test_simple_unicode(self) -> None:
  3187. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3188. self.repo[b"HEAD"] = c1.id
  3189. porcelain.branch_create(self.repo, "foo")
  3190. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  3191. porcelain.branch_delete(self.repo, "foo")
  3192. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  3193. class FetchTests(PorcelainTestCase):
  3194. def test_simple(self) -> None:
  3195. outstream = BytesIO()
  3196. errstream = BytesIO()
  3197. # create a file for initial commit
  3198. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3199. os.close(handle)
  3200. porcelain.add(repo=self.repo.path, paths=fullpath)
  3201. porcelain.commit(
  3202. repo=self.repo.path,
  3203. message=b"test",
  3204. author=b"test <email>",
  3205. committer=b"test <email>",
  3206. )
  3207. # Setup target repo
  3208. target_path = tempfile.mkdtemp()
  3209. self.addCleanup(shutil.rmtree, target_path)
  3210. target_repo = porcelain.clone(
  3211. self.repo.path, target=target_path, errstream=errstream
  3212. )
  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_repo.close()
  3225. # Fetch changes into the cloned repo
  3226. porcelain.fetch(target_path, "origin", outstream=outstream, errstream=errstream)
  3227. # Assert that fetch updated the local image of the remote
  3228. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  3229. # Check the target repo for pushed changes
  3230. with Repo(target_path) as r:
  3231. self.assertIn(self.repo[b"HEAD"].id, r)
  3232. def test_with_remote_name(self) -> None:
  3233. remote_name = "origin"
  3234. outstream = BytesIO()
  3235. errstream = BytesIO()
  3236. # create a file for initial commit
  3237. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3238. os.close(handle)
  3239. porcelain.add(repo=self.repo.path, paths=fullpath)
  3240. porcelain.commit(
  3241. repo=self.repo.path,
  3242. message=b"test",
  3243. author=b"test <email>",
  3244. committer=b"test <email>",
  3245. )
  3246. # Setup target repo
  3247. target_path = tempfile.mkdtemp()
  3248. self.addCleanup(shutil.rmtree, target_path)
  3249. target_repo = porcelain.clone(
  3250. self.repo.path, target=target_path, errstream=errstream
  3251. )
  3252. # Capture current refs
  3253. target_refs = target_repo.get_refs()
  3254. # create a second file to be pushed
  3255. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3256. os.close(handle)
  3257. porcelain.add(repo=self.repo.path, paths=fullpath)
  3258. porcelain.commit(
  3259. repo=self.repo.path,
  3260. message=b"test2",
  3261. author=b"test2 <email>",
  3262. committer=b"test2 <email>",
  3263. )
  3264. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  3265. target_config = target_repo.get_config()
  3266. target_config.set(
  3267. (b"remote", remote_name.encode()), b"url", self.repo.path.encode()
  3268. )
  3269. target_repo.close()
  3270. # Fetch changes into the cloned repo
  3271. porcelain.fetch(
  3272. target_path, remote_name, outstream=outstream, errstream=errstream
  3273. )
  3274. # Assert that fetch updated the local image of the remote
  3275. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  3276. # Check the target repo for pushed changes, as well as updates
  3277. # for the refs
  3278. with Repo(target_path) as r:
  3279. self.assertIn(self.repo[b"HEAD"].id, r)
  3280. self.assertNotEqual(self.repo.get_refs(), target_refs)
  3281. def assert_correct_remote_refs(
  3282. self, local_refs, remote_refs, remote_name=b"origin"
  3283. ) -> None:
  3284. """Assert that known remote refs corresponds to actual remote refs."""
  3285. local_ref_prefix = b"refs/heads"
  3286. remote_ref_prefix = b"refs/remotes/" + remote_name
  3287. locally_known_remote_refs = {
  3288. k[len(remote_ref_prefix) + 1 :]: v
  3289. for k, v in local_refs.items()
  3290. if k.startswith(remote_ref_prefix)
  3291. }
  3292. normalized_remote_refs = {
  3293. k[len(local_ref_prefix) + 1 :]: v
  3294. for k, v in remote_refs.items()
  3295. if k.startswith(local_ref_prefix)
  3296. }
  3297. if b"HEAD" in locally_known_remote_refs and b"HEAD" in remote_refs:
  3298. normalized_remote_refs[b"HEAD"] = remote_refs[b"HEAD"]
  3299. self.assertEqual(locally_known_remote_refs, normalized_remote_refs)
  3300. class RepackTests(PorcelainTestCase):
  3301. def test_empty(self) -> None:
  3302. porcelain.repack(self.repo)
  3303. def test_simple(self) -> None:
  3304. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3305. os.close(handle)
  3306. porcelain.add(repo=self.repo.path, paths=fullpath)
  3307. porcelain.repack(self.repo)
  3308. class LsTreeTests(PorcelainTestCase):
  3309. def test_empty(self) -> None:
  3310. porcelain.commit(
  3311. repo=self.repo.path,
  3312. message=b"test status",
  3313. author=b"author <email>",
  3314. committer=b"committer <email>",
  3315. )
  3316. f = StringIO()
  3317. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  3318. self.assertEqual(f.getvalue(), "")
  3319. def test_simple(self) -> None:
  3320. # Commit a dummy file then modify it
  3321. fullpath = os.path.join(self.repo.path, "foo")
  3322. with open(fullpath, "w") as f:
  3323. f.write("origstuff")
  3324. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3325. porcelain.commit(
  3326. repo=self.repo.path,
  3327. message=b"test status",
  3328. author=b"author <email>",
  3329. committer=b"committer <email>",
  3330. )
  3331. f = StringIO()
  3332. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  3333. self.assertEqual(
  3334. f.getvalue(),
  3335. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n",
  3336. )
  3337. def test_recursive(self) -> None:
  3338. # Create a directory then write a dummy file in it
  3339. dirpath = os.path.join(self.repo.path, "adir")
  3340. filepath = os.path.join(dirpath, "afile")
  3341. os.mkdir(dirpath)
  3342. with open(filepath, "w") as f:
  3343. f.write("origstuff")
  3344. porcelain.add(repo=self.repo.path, paths=[filepath])
  3345. porcelain.commit(
  3346. repo=self.repo.path,
  3347. message=b"test status",
  3348. author=b"author <email>",
  3349. committer=b"committer <email>",
  3350. )
  3351. f = StringIO()
  3352. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  3353. self.assertEqual(
  3354. f.getvalue(),
  3355. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n",
  3356. )
  3357. f = StringIO()
  3358. porcelain.ls_tree(self.repo, b"HEAD", outstream=f, recursive=True)
  3359. self.assertEqual(
  3360. f.getvalue(),
  3361. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n"
  3362. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir"
  3363. "/afile\n",
  3364. )
  3365. class LsRemoteTests(PorcelainTestCase):
  3366. def test_empty(self) -> None:
  3367. self.assertEqual({}, porcelain.ls_remote(self.repo.path))
  3368. def test_some(self) -> None:
  3369. cid = porcelain.commit(
  3370. repo=self.repo.path,
  3371. message=b"test status",
  3372. author=b"author <email>",
  3373. committer=b"committer <email>",
  3374. )
  3375. self.assertEqual(
  3376. {b"refs/heads/master": cid, b"HEAD": cid},
  3377. porcelain.ls_remote(self.repo.path),
  3378. )
  3379. class LsFilesTests(PorcelainTestCase):
  3380. def test_empty(self) -> None:
  3381. self.assertEqual([], list(porcelain.ls_files(self.repo)))
  3382. def test_simple(self) -> None:
  3383. # Commit a dummy file then modify it
  3384. fullpath = os.path.join(self.repo.path, "foo")
  3385. with open(fullpath, "w") as f:
  3386. f.write("origstuff")
  3387. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3388. self.assertEqual([b"foo"], list(porcelain.ls_files(self.repo)))
  3389. class RemoteAddTests(PorcelainTestCase):
  3390. def test_new(self) -> None:
  3391. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  3392. c = self.repo.get_config()
  3393. self.assertEqual(
  3394. c.get((b"remote", b"jelmer"), b"url"),
  3395. b"git://jelmer.uk/code/dulwich",
  3396. )
  3397. def test_exists(self) -> None:
  3398. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  3399. self.assertRaises(
  3400. porcelain.RemoteExists,
  3401. porcelain.remote_add,
  3402. self.repo,
  3403. "jelmer",
  3404. "git://jelmer.uk/code/dulwich",
  3405. )
  3406. class RemoteRemoveTests(PorcelainTestCase):
  3407. def test_remove(self) -> None:
  3408. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  3409. c = self.repo.get_config()
  3410. self.assertEqual(
  3411. c.get((b"remote", b"jelmer"), b"url"),
  3412. b"git://jelmer.uk/code/dulwich",
  3413. )
  3414. porcelain.remote_remove(self.repo, "jelmer")
  3415. self.assertRaises(KeyError, porcelain.remote_remove, self.repo, "jelmer")
  3416. c = self.repo.get_config()
  3417. self.assertRaises(KeyError, c.get, (b"remote", b"jelmer"), b"url")
  3418. class CheckIgnoreTests(PorcelainTestCase):
  3419. def test_check_ignored(self) -> None:
  3420. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3421. f.write("foo")
  3422. foo_path = os.path.join(self.repo.path, "foo")
  3423. with open(foo_path, "w") as f:
  3424. f.write("BAR")
  3425. bar_path = os.path.join(self.repo.path, "bar")
  3426. with open(bar_path, "w") as f:
  3427. f.write("BAR")
  3428. self.assertEqual(["foo"], list(porcelain.check_ignore(self.repo, [foo_path])))
  3429. self.assertEqual([], list(porcelain.check_ignore(self.repo, [bar_path])))
  3430. def test_check_added_abs(self) -> None:
  3431. path = os.path.join(self.repo.path, "foo")
  3432. with open(path, "w") as f:
  3433. f.write("BAR")
  3434. self.repo.stage(["foo"])
  3435. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3436. f.write("foo\n")
  3437. self.assertEqual([], list(porcelain.check_ignore(self.repo, [path])))
  3438. self.assertEqual(
  3439. ["foo"],
  3440. list(porcelain.check_ignore(self.repo, [path], no_index=True)),
  3441. )
  3442. def test_check_added_rel(self) -> None:
  3443. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  3444. f.write("BAR")
  3445. self.repo.stage(["foo"])
  3446. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3447. f.write("foo\n")
  3448. cwd = os.getcwd()
  3449. os.mkdir(os.path.join(self.repo.path, "bar"))
  3450. os.chdir(os.path.join(self.repo.path, "bar"))
  3451. try:
  3452. self.assertEqual(list(porcelain.check_ignore(self.repo, ["../foo"])), [])
  3453. self.assertEqual(
  3454. ["../foo"],
  3455. list(porcelain.check_ignore(self.repo, ["../foo"], no_index=True)),
  3456. )
  3457. finally:
  3458. os.chdir(cwd)
  3459. class UpdateHeadTests(PorcelainTestCase):
  3460. def test_set_to_branch(self) -> None:
  3461. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3462. self.repo.refs[b"refs/heads/blah"] = c1.id
  3463. porcelain.update_head(self.repo, "blah")
  3464. self.assertEqual(c1.id, self.repo.head())
  3465. self.assertEqual(b"ref: refs/heads/blah", self.repo.refs.read_ref(b"HEAD"))
  3466. def test_set_to_branch_detached(self) -> None:
  3467. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3468. self.repo.refs[b"refs/heads/blah"] = c1.id
  3469. porcelain.update_head(self.repo, "blah", detached=True)
  3470. self.assertEqual(c1.id, self.repo.head())
  3471. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  3472. def test_set_to_commit_detached(self) -> None:
  3473. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3474. self.repo.refs[b"refs/heads/blah"] = c1.id
  3475. porcelain.update_head(self.repo, c1.id, detached=True)
  3476. self.assertEqual(c1.id, self.repo.head())
  3477. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  3478. def test_set_new_branch(self) -> None:
  3479. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3480. self.repo.refs[b"refs/heads/blah"] = c1.id
  3481. porcelain.update_head(self.repo, "blah", new_branch="bar")
  3482. self.assertEqual(c1.id, self.repo.head())
  3483. self.assertEqual(b"ref: refs/heads/bar", self.repo.refs.read_ref(b"HEAD"))
  3484. class MailmapTests(PorcelainTestCase):
  3485. def test_no_mailmap(self) -> None:
  3486. self.assertEqual(
  3487. b"Jelmer Vernooij <jelmer@samba.org>",
  3488. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  3489. )
  3490. def test_mailmap_lookup(self) -> None:
  3491. with open(os.path.join(self.repo.path, ".mailmap"), "wb") as f:
  3492. f.write(
  3493. b"""\
  3494. Jelmer Vernooij <jelmer@debian.org>
  3495. """
  3496. )
  3497. self.assertEqual(
  3498. b"Jelmer Vernooij <jelmer@debian.org>",
  3499. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  3500. )
  3501. class FsckTests(PorcelainTestCase):
  3502. def test_none(self) -> None:
  3503. self.assertEqual([], list(porcelain.fsck(self.repo)))
  3504. def test_git_dir(self) -> None:
  3505. obj = Tree()
  3506. a = Blob()
  3507. a.data = b"foo"
  3508. obj.add(b".git", 0o100644, a.id)
  3509. self.repo.object_store.add_objects([(a, None), (obj, None)])
  3510. self.assertEqual(
  3511. [(obj.id, "invalid name .git")],
  3512. [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)],
  3513. )
  3514. class DescribeTests(PorcelainTestCase):
  3515. def test_no_commits(self) -> None:
  3516. self.assertRaises(KeyError, porcelain.describe, self.repo.path)
  3517. def test_single_commit(self) -> None:
  3518. fullpath = os.path.join(self.repo.path, "foo")
  3519. with open(fullpath, "w") as f:
  3520. f.write("BAR")
  3521. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3522. sha = porcelain.commit(
  3523. self.repo.path,
  3524. message=b"Some message",
  3525. author=b"Joe <joe@example.com>",
  3526. committer=b"Bob <bob@example.com>",
  3527. )
  3528. self.assertEqual(
  3529. "g{}".format(sha[:7].decode("ascii")),
  3530. porcelain.describe(self.repo.path),
  3531. )
  3532. def test_tag(self) -> None:
  3533. fullpath = os.path.join(self.repo.path, "foo")
  3534. with open(fullpath, "w") as f:
  3535. f.write("BAR")
  3536. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3537. porcelain.commit(
  3538. self.repo.path,
  3539. message=b"Some message",
  3540. author=b"Joe <joe@example.com>",
  3541. committer=b"Bob <bob@example.com>",
  3542. )
  3543. porcelain.tag_create(
  3544. self.repo.path,
  3545. b"tryme",
  3546. b"foo <foo@bar.com>",
  3547. b"bar",
  3548. annotated=True,
  3549. )
  3550. self.assertEqual("tryme", porcelain.describe(self.repo.path))
  3551. def test_tag_and_commit(self) -> None:
  3552. fullpath = os.path.join(self.repo.path, "foo")
  3553. with open(fullpath, "w") as f:
  3554. f.write("BAR")
  3555. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3556. porcelain.commit(
  3557. self.repo.path,
  3558. message=b"Some message",
  3559. author=b"Joe <joe@example.com>",
  3560. committer=b"Bob <bob@example.com>",
  3561. )
  3562. porcelain.tag_create(
  3563. self.repo.path,
  3564. b"tryme",
  3565. b"foo <foo@bar.com>",
  3566. b"bar",
  3567. annotated=True,
  3568. )
  3569. with open(fullpath, "w") as f:
  3570. f.write("BAR2")
  3571. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3572. sha = porcelain.commit(
  3573. self.repo.path,
  3574. message=b"Some message",
  3575. author=b"Joe <joe@example.com>",
  3576. committer=b"Bob <bob@example.com>",
  3577. )
  3578. self.assertEqual(
  3579. "tryme-1-g{}".format(sha[:7].decode("ascii")),
  3580. porcelain.describe(self.repo.path),
  3581. )
  3582. def test_tag_and_commit_full(self) -> None:
  3583. fullpath = os.path.join(self.repo.path, "foo")
  3584. with open(fullpath, "w") as f:
  3585. f.write("BAR")
  3586. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3587. porcelain.commit(
  3588. self.repo.path,
  3589. message=b"Some message",
  3590. author=b"Joe <joe@example.com>",
  3591. committer=b"Bob <bob@example.com>",
  3592. )
  3593. porcelain.tag_create(
  3594. self.repo.path,
  3595. b"tryme",
  3596. b"foo <foo@bar.com>",
  3597. b"bar",
  3598. annotated=True,
  3599. )
  3600. with open(fullpath, "w") as f:
  3601. f.write("BAR2")
  3602. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3603. sha = porcelain.commit(
  3604. self.repo.path,
  3605. message=b"Some message",
  3606. author=b"Joe <joe@example.com>",
  3607. committer=b"Bob <bob@example.com>",
  3608. )
  3609. self.assertEqual(
  3610. "tryme-1-g{}".format(sha.decode("ascii")),
  3611. porcelain.describe(self.repo.path, abbrev=40),
  3612. )
  3613. def test_untagged_commit_abbreviation(self) -> None:
  3614. _, _, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]])
  3615. self.repo.refs[b"HEAD"] = c3.id
  3616. brief_description, complete_description = (
  3617. porcelain.describe(self.repo),
  3618. porcelain.describe(self.repo, abbrev=40),
  3619. )
  3620. self.assertTrue(complete_description.startswith(brief_description))
  3621. self.assertEqual(
  3622. "g{}".format(c3.id.decode("ascii")),
  3623. complete_description,
  3624. )
  3625. class PathToTreeTests(PorcelainTestCase):
  3626. def setUp(self) -> None:
  3627. super().setUp()
  3628. self.fp = os.path.join(self.test_dir, "bar")
  3629. with open(self.fp, "w") as f:
  3630. f.write("something")
  3631. oldcwd = os.getcwd()
  3632. self.addCleanup(os.chdir, oldcwd)
  3633. os.chdir(self.test_dir)
  3634. def test_path_to_tree_path_base(self) -> None:
  3635. self.assertEqual(b"bar", porcelain.path_to_tree_path(self.test_dir, self.fp))
  3636. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  3637. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "bar"))
  3638. cwd = os.getcwd()
  3639. self.assertEqual(
  3640. b"bar", porcelain.path_to_tree_path(".", os.path.join(cwd, "bar"))
  3641. )
  3642. self.assertEqual(b"bar", porcelain.path_to_tree_path(cwd, "bar"))
  3643. def test_path_to_tree_path_syntax(self) -> None:
  3644. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  3645. def test_path_to_tree_path_error(self) -> None:
  3646. with self.assertRaises(ValueError):
  3647. with tempfile.TemporaryDirectory() as od:
  3648. porcelain.path_to_tree_path(od, self.fp)
  3649. def test_path_to_tree_path_rel(self) -> None:
  3650. cwd = os.getcwd()
  3651. os.mkdir(os.path.join(self.repo.path, "foo"))
  3652. os.mkdir(os.path.join(self.repo.path, "foo/bar"))
  3653. try:
  3654. os.chdir(os.path.join(self.repo.path, "foo/bar"))
  3655. with open("baz", "w") as f:
  3656. f.write("contents")
  3657. self.assertEqual(b"bar/baz", porcelain.path_to_tree_path("..", "baz"))
  3658. self.assertEqual(
  3659. b"bar/baz",
  3660. porcelain.path_to_tree_path(
  3661. os.path.join(os.getcwd(), ".."),
  3662. os.path.join(os.getcwd(), "baz"),
  3663. ),
  3664. )
  3665. self.assertEqual(
  3666. b"bar/baz",
  3667. porcelain.path_to_tree_path("..", os.path.join(os.getcwd(), "baz")),
  3668. )
  3669. self.assertEqual(
  3670. b"bar/baz",
  3671. porcelain.path_to_tree_path(os.path.join(os.getcwd(), ".."), "baz"),
  3672. )
  3673. finally:
  3674. os.chdir(cwd)
  3675. class GetObjectByPathTests(PorcelainTestCase):
  3676. def test_simple(self) -> None:
  3677. fullpath = os.path.join(self.repo.path, "foo")
  3678. with open(fullpath, "w") as f:
  3679. f.write("BAR")
  3680. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3681. porcelain.commit(
  3682. self.repo.path,
  3683. message=b"Some message",
  3684. author=b"Joe <joe@example.com>",
  3685. committer=b"Bob <bob@example.com>",
  3686. )
  3687. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  3688. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  3689. def test_encoding(self) -> None:
  3690. fullpath = os.path.join(self.repo.path, "foo")
  3691. with open(fullpath, "w") as f:
  3692. f.write("BAR")
  3693. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3694. porcelain.commit(
  3695. self.repo.path,
  3696. message=b"Some message",
  3697. author=b"Joe <joe@example.com>",
  3698. committer=b"Bob <bob@example.com>",
  3699. encoding=b"utf-8",
  3700. )
  3701. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  3702. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  3703. def test_missing(self) -> None:
  3704. self.assertRaises(KeyError, porcelain.get_object_by_path, self.repo, "foo")
  3705. class WriteTreeTests(PorcelainTestCase):
  3706. def test_simple(self) -> None:
  3707. fullpath = os.path.join(self.repo.path, "foo")
  3708. with open(fullpath, "w") as f:
  3709. f.write("BAR")
  3710. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3711. self.assertEqual(
  3712. b"d2092c8a9f311f0311083bf8d177f2ca0ab5b241",
  3713. porcelain.write_tree(self.repo),
  3714. )
  3715. class ActiveBranchTests(PorcelainTestCase):
  3716. def test_simple(self) -> None:
  3717. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  3718. class FindUniqueAbbrevTests(PorcelainTestCase):
  3719. def test_simple(self) -> None:
  3720. c1, c2, c3 = build_commit_graph(
  3721. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  3722. )
  3723. self.repo.refs[b"HEAD"] = c3.id
  3724. self.assertEqual(
  3725. c1.id.decode("ascii")[:7],
  3726. porcelain.find_unique_abbrev(self.repo.object_store, c1.id),
  3727. )
  3728. class PackRefsTests(PorcelainTestCase):
  3729. def test_all(self) -> None:
  3730. c1, c2, c3 = build_commit_graph(
  3731. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  3732. )
  3733. self.repo.refs[b"HEAD"] = c3.id
  3734. self.repo.refs[b"refs/heads/master"] = c2.id
  3735. self.repo.refs[b"refs/tags/foo"] = c1.id
  3736. porcelain.pack_refs(self.repo, all=True)
  3737. self.assertEqual(
  3738. self.repo.refs.get_packed_refs(),
  3739. {
  3740. b"refs/heads/master": c2.id,
  3741. b"refs/tags/foo": c1.id,
  3742. },
  3743. )
  3744. def test_not_all(self) -> None:
  3745. c1, c2, c3 = build_commit_graph(
  3746. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  3747. )
  3748. self.repo.refs[b"HEAD"] = c3.id
  3749. self.repo.refs[b"refs/heads/master"] = c2.id
  3750. self.repo.refs[b"refs/tags/foo"] = c1.id
  3751. porcelain.pack_refs(self.repo)
  3752. self.assertEqual(
  3753. self.repo.refs.get_packed_refs(),
  3754. {
  3755. b"refs/tags/foo": c1.id,
  3756. },
  3757. )
  3758. class ServerTests(PorcelainTestCase):
  3759. @contextlib.contextmanager
  3760. def _serving(self):
  3761. with make_server("localhost", 0, self.app) as server:
  3762. thread = threading.Thread(target=server.serve_forever, daemon=True)
  3763. thread.start()
  3764. try:
  3765. yield f"http://localhost:{server.server_port}"
  3766. finally:
  3767. server.shutdown()
  3768. thread.join(10)
  3769. def setUp(self) -> None:
  3770. super().setUp()
  3771. self.served_repo_path = os.path.join(self.test_dir, "served_repo.git")
  3772. self.served_repo = Repo.init_bare(self.served_repo_path, mkdir=True)
  3773. self.addCleanup(self.served_repo.close)
  3774. backend = DictBackend({"/": self.served_repo})
  3775. self.app = make_wsgi_chain(backend)
  3776. def test_pull(self) -> None:
  3777. (c1,) = build_commit_graph(self.served_repo.object_store, [[1]])
  3778. self.served_repo.refs[b"refs/heads/master"] = c1.id
  3779. with self._serving() as url:
  3780. porcelain.pull(self.repo, url, "master")
  3781. def test_push(self) -> None:
  3782. (c1,) = build_commit_graph(self.repo.object_store, [[1]])
  3783. self.repo.refs[b"refs/heads/master"] = c1.id
  3784. with self._serving() as url:
  3785. porcelain.push(self.repo, url, "master")
  3786. class ForEachTests(PorcelainTestCase):
  3787. def setUp(self) -> None:
  3788. super().setUp()
  3789. c1, c2, c3, c4 = build_commit_graph(
  3790. self.repo.object_store, [[1], [2, 1], [3, 1, 2], [4]]
  3791. )
  3792. porcelain.tag_create(
  3793. self.repo.path,
  3794. b"v0.1",
  3795. objectish=c1.id,
  3796. annotated=True,
  3797. message=b"0.1",
  3798. )
  3799. porcelain.tag_create(
  3800. self.repo.path,
  3801. b"v1.0",
  3802. objectish=c2.id,
  3803. annotated=True,
  3804. message=b"1.0",
  3805. )
  3806. porcelain.tag_create(self.repo.path, b"simple-tag", objectish=c3.id)
  3807. porcelain.tag_create(
  3808. self.repo.path,
  3809. b"v1.1",
  3810. objectish=c4.id,
  3811. annotated=True,
  3812. message=b"1.1",
  3813. )
  3814. porcelain.branch_create(
  3815. self.repo.path, b"feat", objectish=c2.id.decode("ascii")
  3816. )
  3817. self.repo.refs[b"HEAD"] = c4.id
  3818. def test_for_each_ref(self) -> None:
  3819. refs = porcelain.for_each_ref(self.repo)
  3820. self.assertEqual(
  3821. [(object_type, tag) for _, object_type, tag in refs],
  3822. [
  3823. (b"commit", b"refs/heads/feat"),
  3824. (b"commit", b"refs/heads/master"),
  3825. (b"commit", b"refs/tags/simple-tag"),
  3826. (b"tag", b"refs/tags/v0.1"),
  3827. (b"tag", b"refs/tags/v1.0"),
  3828. (b"tag", b"refs/tags/v1.1"),
  3829. ],
  3830. )
  3831. def test_for_each_ref_pattern(self) -> None:
  3832. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v*")
  3833. self.assertEqual(
  3834. [(object_type, tag) for _, object_type, tag in versions],
  3835. [
  3836. (b"tag", b"refs/tags/v0.1"),
  3837. (b"tag", b"refs/tags/v1.0"),
  3838. (b"tag", b"refs/tags/v1.1"),
  3839. ],
  3840. )
  3841. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v1.?")
  3842. self.assertEqual(
  3843. [(object_type, tag) for _, object_type, tag in versions],
  3844. [
  3845. (b"tag", b"refs/tags/v1.0"),
  3846. (b"tag", b"refs/tags/v1.1"),
  3847. ],
  3848. )
  3849. class SparseCheckoutTests(PorcelainTestCase):
  3850. """Integration tests for Dulwich's sparse checkout feature."""
  3851. # NOTE: We do NOT override `setUp()` here because the parent class
  3852. # (PorcelainTestCase) already:
  3853. # 1) Creates self.test_dir = a unique temp dir
  3854. # 2) Creates a subdir named "repo"
  3855. # 3) Calls Repo.init() on that path
  3856. # Re-initializing again caused FileExistsError.
  3857. #
  3858. # Utility/Placeholder
  3859. #
  3860. def sparse_checkout(self, repo, patterns, force=False):
  3861. """Wrapper around the actual porcelain.sparse_checkout function
  3862. to handle any test-specific setup or logging.
  3863. """
  3864. return porcelain.sparse_checkout(repo, patterns, force=force)
  3865. def _write_file(self, rel_path, content):
  3866. """Helper to write a file in the repository working tree."""
  3867. abs_path = os.path.join(self.repo_path, rel_path)
  3868. os.makedirs(os.path.dirname(abs_path), exist_ok=True)
  3869. with open(abs_path, "w") as f:
  3870. f.write(content)
  3871. return abs_path
  3872. def _commit_file(self, rel_path, content):
  3873. """Helper to write, add, and commit a file."""
  3874. abs_path = self._write_file(rel_path, content)
  3875. add(self.repo_path, paths=[abs_path])
  3876. commit(self.repo_path, message=b"Added " + rel_path.encode("utf-8"))
  3877. def _list_wtree_files(self):
  3878. """Return a set of all files (not dirs) present
  3879. in the working tree, ignoring .git/.
  3880. """
  3881. found_files = set()
  3882. for root, dirs, files in os.walk(self.repo_path):
  3883. # Skip .git in the walk
  3884. if ".git" in dirs:
  3885. dirs.remove(".git")
  3886. for filename in files:
  3887. file_rel = os.path.relpath(os.path.join(root, filename), self.repo_path)
  3888. found_files.add(file_rel)
  3889. return found_files
  3890. def test_only_included_paths_appear_in_wtree(self):
  3891. """Only included paths remain in the working tree, excluded paths are removed.
  3892. Commits two files, "keep_me.txt" and "exclude_me.txt". Then applies a
  3893. sparse-checkout pattern containing only "keep_me.txt". Ensures that
  3894. the latter remains in the working tree, while "exclude_me.txt" is
  3895. removed. This verifies correct application of sparse-checkout patterns
  3896. to remove files not listed.
  3897. """
  3898. self._commit_file("keep_me.txt", "I'll stay\n")
  3899. self._commit_file("exclude_me.txt", "I'll be excluded\n")
  3900. patterns = ["keep_me.txt"]
  3901. self.sparse_checkout(self.repo, patterns)
  3902. actual_files = self._list_wtree_files()
  3903. expected_files = {"keep_me.txt"}
  3904. self.assertEqual(
  3905. expected_files,
  3906. actual_files,
  3907. f"Expected only {expected_files}, but found {actual_files}",
  3908. )
  3909. def test_previously_included_paths_become_excluded(self):
  3910. """Previously included files become excluded after pattern changes.
  3911. Verifies that files initially brought into the working tree (e.g.,
  3912. by including `data/`) can later be excluded by narrowing the
  3913. sparse-checkout pattern to just `data/included_1.txt`. Confirms that
  3914. the file `data/included_2.txt` remains in the index with
  3915. skip-worktree set (rather than being removed entirely), ensuring
  3916. data is not lost and Dulwich correctly updates the index flags.
  3917. """
  3918. self._commit_file("data/included_1.txt", "some content\n")
  3919. self._commit_file("data/included_2.txt", "other content\n")
  3920. initial_patterns = ["data/"]
  3921. self.sparse_checkout(self.repo, initial_patterns)
  3922. updated_patterns = ["data/included_1.txt"]
  3923. self.sparse_checkout(self.repo, updated_patterns)
  3924. actual_files = self._list_wtree_files()
  3925. expected_files = {os.path.join("data", "included_1.txt")}
  3926. self.assertEqual(expected_files, actual_files)
  3927. idx = self.repo.open_index()
  3928. self.assertIn(b"data/included_2.txt", idx)
  3929. entry = idx[b"data/included_2.txt"]
  3930. self.assertTrue(entry.skip_worktree)
  3931. def test_force_removes_local_changes_for_excluded_paths(self):
  3932. """Forced sparse checkout removes local modifications for newly excluded paths.
  3933. Verifies that specifying force=True allows destructive operations
  3934. which discard uncommitted changes. First, we commit "file1.txt" and
  3935. then modify it. Next, we apply a pattern that excludes the file,
  3936. using force=True. The local modifications (and the file) should
  3937. be removed, leaving the working tree empty.
  3938. """
  3939. self._commit_file("file1.txt", "original content\n")
  3940. file1_path = os.path.join(self.repo_path, "file1.txt")
  3941. with open(file1_path, "a") as f:
  3942. f.write("local changes!\n")
  3943. new_patterns = ["some_other_file.txt"]
  3944. self.sparse_checkout(self.repo, new_patterns, force=True)
  3945. actual_files = self._list_wtree_files()
  3946. self.assertEqual(
  3947. set(),
  3948. actual_files,
  3949. "Force-sparse-checkout did not remove file with local changes.",
  3950. )
  3951. def test_destructive_refuse_uncommitted_changes_without_force(self):
  3952. """Fail on uncommitted changes for newly excluded paths without force.
  3953. Ensures that a sparse checkout is blocked if it would remove local
  3954. modifications from the working tree. We commit 'config.yaml', then
  3955. modify it, and finally attempt to exclude it via new patterns without
  3956. using force=True. This should raise a CheckoutError rather than
  3957. discarding the local changes.
  3958. """
  3959. self._commit_file("config.yaml", "initial\n")
  3960. cfg_path = os.path.join(self.repo_path, "config.yaml")
  3961. with open(cfg_path, "a") as f:
  3962. f.write("local modifications\n")
  3963. exclude_patterns = ["docs/"]
  3964. with self.assertRaises(CheckoutError):
  3965. self.sparse_checkout(self.repo, exclude_patterns, force=False)
  3966. def test_fnmatch_gitignore_pattern_expansion(self):
  3967. """Reading/writing patterns align with gitignore/fnmatch expansions.
  3968. Ensures that `sparse_checkout` interprets wildcard patterns (like `*.py`)
  3969. in the same way Git's sparse-checkout would. Multiple files are committed
  3970. to `src/` (e.g. `foo.py`, `foo_test.py`, `foo_helper.py`) and to `docs/`.
  3971. Then the pattern `src/foo*.py` is applied, confirming that only the
  3972. matching Python files remain in the working tree while the Markdown file
  3973. under `docs/` is excluded.
  3974. Finally, verifies that the `.git/info/sparse-checkout` file contains the
  3975. specified wildcard pattern (`src/foo*.py`), ensuring correct round-trip
  3976. of user-supplied patterns.
  3977. """
  3978. self._commit_file("src/foo.py", "print('hello')\n")
  3979. self._commit_file("src/foo_test.py", "print('test')\n")
  3980. self._commit_file("docs/readme.md", "# docs\n")
  3981. self._commit_file("src/foo_helper.py", "print('helper')\n")
  3982. patterns = ["src/foo*.py"]
  3983. self.sparse_checkout(self.repo, patterns)
  3984. actual_files = self._list_wtree_files()
  3985. expected_files = {
  3986. os.path.join("src", "foo.py"),
  3987. os.path.join("src", "foo_test.py"),
  3988. os.path.join("src", "foo_helper.py"),
  3989. }
  3990. self.assertEqual(
  3991. expected_files,
  3992. actual_files,
  3993. "Wildcard pattern not matched as expected. Either too strict or too broad.",
  3994. )
  3995. sc_file = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  3996. self.assertTrue(os.path.isfile(sc_file))
  3997. with open(sc_file) as f:
  3998. lines = f.read().strip().split()
  3999. self.assertIn("src/foo*.py", lines)
  4000. class ConeModeTests(PorcelainTestCase):
  4001. """Provide integration tests for Dulwich's cone mode sparse checkout.
  4002. This test suite verifies the expected behavior for:
  4003. * cone_mode_init
  4004. * cone_mode_set
  4005. * cone_mode_add
  4006. Although Dulwich does not yet implement cone mode, these tests are
  4007. prepared in advance to guide future development.
  4008. """
  4009. def setUp(self):
  4010. """Set up a fresh repository for each test.
  4011. This method creates a new empty repo_path and Repo object
  4012. as provided by the PorcelainTestCase base class.
  4013. """
  4014. super().setUp()
  4015. def _commit_file(self, rel_path, content=b"contents"):
  4016. """Add a file at the given relative path and commit it.
  4017. Creates necessary directories, writes the file content,
  4018. stages, and commits. The commit message and author/committer
  4019. are also provided.
  4020. """
  4021. full_path = os.path.join(self.repo_path, rel_path)
  4022. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  4023. with open(full_path, "wb") as f:
  4024. f.write(content)
  4025. porcelain.add(self.repo_path, paths=[full_path])
  4026. porcelain.commit(
  4027. self.repo_path,
  4028. message=b"Adding " + rel_path.encode("utf-8"),
  4029. author=b"Test Author <author@example.com>",
  4030. committer=b"Test Committer <committer@example.com>",
  4031. )
  4032. def _list_wtree_files(self):
  4033. """Return a set of all file paths relative to the repository root.
  4034. Walks the working tree, skipping the .git directory.
  4035. """
  4036. found_files = set()
  4037. for root, dirs, files in os.walk(self.repo_path):
  4038. if ".git" in dirs:
  4039. dirs.remove(".git")
  4040. for fn in files:
  4041. relp = os.path.relpath(os.path.join(root, fn), self.repo_path)
  4042. found_files.add(relp)
  4043. return found_files
  4044. def test_init_excludes_everything(self):
  4045. """Verify that cone_mode_init writes minimal patterns and empties the working tree.
  4046. Make some dummy files, commit them, then call cone_mode_init. Confirm
  4047. that the working tree is empty, the sparse-checkout file has the
  4048. minimal patterns (/*, !/*/), and the relevant config values are set.
  4049. """
  4050. self._commit_file("docs/readme.md", b"# doc\n")
  4051. self._commit_file("src/main.py", b"print('hello')\n")
  4052. porcelain.cone_mode_init(self.repo)
  4053. actual_files = self._list_wtree_files()
  4054. self.assertEqual(
  4055. set(),
  4056. actual_files,
  4057. "cone_mode_init did not exclude all files from the working tree.",
  4058. )
  4059. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  4060. with open(sp_path) as f:
  4061. lines = [ln.strip() for ln in f if ln.strip()]
  4062. self.assertIn("/*", lines)
  4063. self.assertIn("!/*/", lines)
  4064. config = self.repo.get_config()
  4065. self.assertEqual(config.get((b"core",), b"sparseCheckout"), b"true")
  4066. self.assertEqual(config.get((b"core",), b"sparseCheckoutCone"), b"true")
  4067. def test_set_specific_dirs(self):
  4068. """Verify that cone_mode_set overwrites the included directories to only the specified ones.
  4069. Initializes cone mode, commits some files, then calls cone_mode_set with
  4070. a list of directories. Expects that only those directories remain in the
  4071. working tree.
  4072. """
  4073. porcelain.cone_mode_init(self.repo)
  4074. self._commit_file("docs/readme.md", b"# doc\n")
  4075. self._commit_file("src/main.py", b"print('hello')\n")
  4076. self._commit_file("tests/test_foo.py", b"# tests\n")
  4077. # Everything is still excluded initially by init.
  4078. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  4079. actual_files = self._list_wtree_files()
  4080. expected_files = {
  4081. os.path.join("docs", "readme.md"),
  4082. os.path.join("src", "main.py"),
  4083. }
  4084. self.assertEqual(
  4085. expected_files,
  4086. actual_files,
  4087. "Did not see only the 'docs/' and 'src/' dirs in the working tree.",
  4088. )
  4089. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  4090. with open(sp_path) as f:
  4091. lines = [ln.strip() for ln in f if ln.strip()]
  4092. # For standard cone mode, we'd expect lines like:
  4093. # /* (include top-level files)
  4094. # !/*/ (exclude subdirectories)
  4095. # !/docs/ (re-include docs)
  4096. # !/src/ (re-include src)
  4097. # Instead of the wildcard-based lines the old test used.
  4098. self.assertIn("/*", lines)
  4099. self.assertIn("!/*/", lines)
  4100. self.assertIn("/docs/", lines)
  4101. self.assertIn("/src/", lines)
  4102. self.assertNotIn("/tests/", lines)
  4103. def test_set_overwrites_old_dirs(self):
  4104. """Ensure that calling cone_mode_set again overwrites old includes.
  4105. Initializes cone mode, includes two directories, then calls
  4106. cone_mode_set again with a different directory to confirm the
  4107. new set of includes replaces the old.
  4108. """
  4109. porcelain.cone_mode_init(self.repo)
  4110. self._commit_file("docs/readme.md")
  4111. self._commit_file("src/main.py")
  4112. self._commit_file("tests/test_bar.py")
  4113. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  4114. self.assertEqual(
  4115. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  4116. self._list_wtree_files(),
  4117. )
  4118. # Overwrite includes, now only 'tests'
  4119. porcelain.cone_mode_set(self.repo, dirs=["tests"], force=True)
  4120. actual_files = self._list_wtree_files()
  4121. expected_files = {os.path.join("tests", "test_bar.py")}
  4122. self.assertEqual(expected_files, actual_files)
  4123. def test_force_removal_of_local_mods(self):
  4124. """Confirm that force=True removes local changes in excluded paths.
  4125. cone_mode_init and cone_mode_set are called, a file is locally modified,
  4126. and then cone_mode_set is called again with force=True to exclude that path.
  4127. The excluded file should be removed with no CheckoutError.
  4128. """
  4129. porcelain.cone_mode_init(self.repo)
  4130. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  4131. self._commit_file("docs/readme.md", b"Docs stuff\n")
  4132. self._commit_file("src/main.py", b"print('hello')\n")
  4133. # Modify src/main.py
  4134. with open(os.path.join(self.repo_path, "src/main.py"), "ab") as f:
  4135. f.write(b"extra line\n")
  4136. # Exclude src/ with force=True
  4137. porcelain.cone_mode_set(self.repo, dirs=["docs"], force=True)
  4138. actual_files = self._list_wtree_files()
  4139. expected_files = {os.path.join("docs", "readme.md")}
  4140. self.assertEqual(expected_files, actual_files)
  4141. def test_add_and_merge_dirs(self):
  4142. """Verify that cone_mode_add merges new directories instead of overwriting them.
  4143. After initializing cone mode and including a single directory, call
  4144. cone_mode_add with a new directory. Confirm that both directories
  4145. remain included. Repeat for an additional directory to ensure it
  4146. is merged, not overwritten.
  4147. """
  4148. porcelain.cone_mode_init(self.repo)
  4149. self._commit_file("docs/readme.md", b"# doc\n")
  4150. self._commit_file("src/main.py", b"print('hello')\n")
  4151. self._commit_file("tests/test_bar.py", b"# tests\n")
  4152. # Include "docs" only
  4153. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  4154. self.assertEqual({os.path.join("docs", "readme.md")}, self._list_wtree_files())
  4155. # Add "src"
  4156. porcelain.cone_mode_add(self.repo, dirs=["src"])
  4157. actual_files = self._list_wtree_files()
  4158. self.assertEqual(
  4159. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  4160. actual_files,
  4161. )
  4162. # Add "tests" as well
  4163. porcelain.cone_mode_add(self.repo, dirs=["tests"])
  4164. actual_files = self._list_wtree_files()
  4165. expected_files = {
  4166. os.path.join("docs", "readme.md"),
  4167. os.path.join("src", "main.py"),
  4168. os.path.join("tests", "test_bar.py"),
  4169. }
  4170. self.assertEqual(expected_files, actual_files)
  4171. # Check .git/info/sparse-checkout
  4172. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  4173. with open(sp_path) as f:
  4174. lines = [ln.strip() for ln in f if ln.strip()]
  4175. # Standard cone mode lines:
  4176. # "/*" -> include top-level
  4177. # "!/*/" -> exclude subdirectories
  4178. # "!/docs/", "!/src/", "!/tests/" -> re-include the directories we added
  4179. self.assertIn("/*", lines)
  4180. self.assertIn("!/*/", lines)
  4181. self.assertIn("/docs/", lines)
  4182. self.assertIn("/src/", lines)
  4183. self.assertIn("/tests/", lines)