2
0

test_porcelain.py 185 KB

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