test_porcelain.py 200 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504
  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. def test_hard_commit_short_hash(self) -> None:
  1825. fullpath = os.path.join(self.repo.path, "foo")
  1826. with open(fullpath, "w") as f:
  1827. f.write("BAR")
  1828. porcelain.add(self.repo.path, paths=[fullpath])
  1829. sha = porcelain.commit(
  1830. self.repo.path,
  1831. message=b"Some message",
  1832. committer=b"Jane <jane@example.com>",
  1833. author=b"John <john@example.com>",
  1834. )
  1835. with open(fullpath, "wb") as f:
  1836. f.write(b"BAZ")
  1837. porcelain.add(self.repo.path, paths=[fullpath])
  1838. porcelain.commit(
  1839. self.repo.path,
  1840. message=b"Some other message",
  1841. committer=b"Jane <jane@example.com>",
  1842. author=b"John <john@example.com>",
  1843. )
  1844. # Test with short hash (7 characters)
  1845. short_sha = sha[:7].decode("ascii")
  1846. porcelain.reset(self.repo, "hard", short_sha)
  1847. index = self.repo.open_index()
  1848. changes = list(
  1849. tree_changes(
  1850. self.repo,
  1851. index.commit(self.repo.object_store),
  1852. self.repo[sha].tree,
  1853. )
  1854. )
  1855. self.assertEqual([], changes)
  1856. def test_hard_deletes_untracked_files(self) -> None:
  1857. """Test that reset --hard deletes files that don't exist in target tree."""
  1858. # Create and commit a file
  1859. fullpath = os.path.join(self.repo.path, "foo")
  1860. with open(fullpath, "w") as f:
  1861. f.write("BAR")
  1862. porcelain.add(self.repo.path, paths=[fullpath])
  1863. sha1 = porcelain.commit(
  1864. self.repo.path,
  1865. message=b"First commit",
  1866. committer=b"Jane <jane@example.com>",
  1867. author=b"John <john@example.com>",
  1868. )
  1869. # Create another file and commit
  1870. fullpath2 = os.path.join(self.repo.path, "bar")
  1871. with open(fullpath2, "w") as f:
  1872. f.write("BAZ")
  1873. porcelain.add(self.repo.path, paths=[fullpath2])
  1874. porcelain.commit(
  1875. self.repo.path,
  1876. message=b"Second commit",
  1877. committer=b"Jane <jane@example.com>",
  1878. author=b"John <john@example.com>",
  1879. )
  1880. # Reset hard to first commit - this should delete 'bar'
  1881. porcelain.reset(self.repo, "hard", sha1)
  1882. # Check that 'foo' still exists and 'bar' is deleted
  1883. self.assertTrue(os.path.exists(fullpath))
  1884. self.assertFalse(os.path.exists(fullpath2))
  1885. # Check index matches first commit
  1886. index = self.repo.open_index()
  1887. self.assertIn(b"foo", index)
  1888. self.assertNotIn(b"bar", index)
  1889. def test_hard_deletes_files_in_subdirs(self) -> None:
  1890. """Test that reset --hard deletes files in subdirectories."""
  1891. # Create and commit files in subdirectory
  1892. subdir = os.path.join(self.repo.path, "subdir")
  1893. os.makedirs(subdir)
  1894. file1 = os.path.join(subdir, "file1")
  1895. file2 = os.path.join(subdir, "file2")
  1896. with open(file1, "w") as f:
  1897. f.write("content1")
  1898. with open(file2, "w") as f:
  1899. f.write("content2")
  1900. porcelain.add(self.repo.path, paths=[file1, file2])
  1901. porcelain.commit(
  1902. self.repo.path,
  1903. message=b"First commit",
  1904. committer=b"Jane <jane@example.com>",
  1905. author=b"John <john@example.com>",
  1906. )
  1907. # Remove one file from subdirectory and commit
  1908. porcelain.rm(self.repo.path, paths=[file2])
  1909. sha2 = porcelain.commit(
  1910. self.repo.path,
  1911. message=b"Remove file2",
  1912. committer=b"Jane <jane@example.com>",
  1913. author=b"John <john@example.com>",
  1914. )
  1915. # Create file2 again (untracked)
  1916. with open(file2, "w") as f:
  1917. f.write("new content")
  1918. # Reset to commit that has file2 removed - should delete untracked file2
  1919. porcelain.reset(self.repo, "hard", sha2)
  1920. self.assertTrue(os.path.exists(file1))
  1921. self.assertFalse(os.path.exists(file2))
  1922. def test_hard_reset_to_remote_branch(self) -> None:
  1923. """Test reset --hard to remote branch deletes local files not in remote."""
  1924. # Create a file and commit
  1925. file1 = os.path.join(self.repo.path, "file1")
  1926. with open(file1, "w") as f:
  1927. f.write("content1")
  1928. porcelain.add(self.repo.path, paths=[file1])
  1929. sha1 = porcelain.commit(
  1930. self.repo.path,
  1931. message=b"Initial commit",
  1932. committer=b"Jane <jane@example.com>",
  1933. author=b"John <john@example.com>",
  1934. )
  1935. # Create a "remote" ref that doesn't have additional files
  1936. self.repo.refs[b"refs/remotes/origin/master"] = sha1
  1937. # Add another file locally and commit
  1938. file2 = os.path.join(self.repo.path, "file2")
  1939. with open(file2, "w") as f:
  1940. f.write("content2")
  1941. porcelain.add(self.repo.path, paths=[file2])
  1942. porcelain.commit(
  1943. self.repo.path,
  1944. message=b"Add file2",
  1945. committer=b"Jane <jane@example.com>",
  1946. author=b"John <john@example.com>",
  1947. )
  1948. # Both files should exist
  1949. self.assertTrue(os.path.exists(file1))
  1950. self.assertTrue(os.path.exists(file2))
  1951. # Reset to remote branch - should delete file2
  1952. porcelain.reset(self.repo, "hard", b"refs/remotes/origin/master")
  1953. # file1 should exist, file2 should be deleted
  1954. self.assertTrue(os.path.exists(file1))
  1955. self.assertFalse(os.path.exists(file2))
  1956. class ResetFileTests(PorcelainTestCase):
  1957. def test_reset_modify_file_to_commit(self) -> None:
  1958. file = "foo"
  1959. full_path = os.path.join(self.repo.path, file)
  1960. with open(full_path, "w") as f:
  1961. f.write("hello")
  1962. porcelain.add(self.repo, paths=[full_path])
  1963. sha = porcelain.commit(
  1964. self.repo,
  1965. message=b"unitest",
  1966. committer=b"Jane <jane@example.com>",
  1967. author=b"John <john@example.com>",
  1968. )
  1969. with open(full_path, "a") as f:
  1970. f.write("something new")
  1971. porcelain.reset_file(self.repo, file, target=sha)
  1972. with open(full_path) as f:
  1973. self.assertEqual("hello", f.read())
  1974. def test_reset_remove_file_to_commit(self) -> None:
  1975. file = "foo"
  1976. full_path = os.path.join(self.repo.path, file)
  1977. with open(full_path, "w") as f:
  1978. f.write("hello")
  1979. porcelain.add(self.repo, paths=[full_path])
  1980. sha = porcelain.commit(
  1981. self.repo,
  1982. message=b"unitest",
  1983. committer=b"Jane <jane@example.com>",
  1984. author=b"John <john@example.com>",
  1985. )
  1986. os.remove(full_path)
  1987. porcelain.reset_file(self.repo, file, target=sha)
  1988. with open(full_path) as f:
  1989. self.assertEqual("hello", f.read())
  1990. def test_resetfile_with_dir(self) -> None:
  1991. os.mkdir(os.path.join(self.repo.path, "new_dir"))
  1992. full_path = os.path.join(self.repo.path, "new_dir", "foo")
  1993. with open(full_path, "w") as f:
  1994. f.write("hello")
  1995. porcelain.add(self.repo, paths=[full_path])
  1996. sha = porcelain.commit(
  1997. self.repo,
  1998. message=b"unitest",
  1999. committer=b"Jane <jane@example.com>",
  2000. author=b"John <john@example.com>",
  2001. )
  2002. with open(full_path, "a") as f:
  2003. f.write("something new")
  2004. porcelain.commit(
  2005. self.repo,
  2006. message=b"unitest 2",
  2007. committer=b"Jane <jane@example.com>",
  2008. author=b"John <john@example.com>",
  2009. )
  2010. porcelain.reset_file(self.repo, os.path.join("new_dir", "foo"), target=sha)
  2011. with open(full_path) as f:
  2012. self.assertEqual("hello", f.read())
  2013. def _commit_file_with_content(repo, filename, content):
  2014. file_path = os.path.join(repo.path, filename)
  2015. with open(file_path, "w") as f:
  2016. f.write(content)
  2017. porcelain.add(repo, paths=[file_path])
  2018. sha = porcelain.commit(
  2019. repo,
  2020. message=b"add " + filename.encode(),
  2021. committer=b"Jane <jane@example.com>",
  2022. author=b"John <john@example.com>",
  2023. )
  2024. return sha, file_path
  2025. class RevertTests(PorcelainTestCase):
  2026. def test_revert_simple(self) -> None:
  2027. # Create initial commit
  2028. fullpath = os.path.join(self.repo.path, "foo")
  2029. with open(fullpath, "w") as f:
  2030. f.write("initial content\n")
  2031. porcelain.add(self.repo.path, paths=[fullpath])
  2032. porcelain.commit(
  2033. self.repo.path,
  2034. message=b"Initial commit",
  2035. committer=b"Jane <jane@example.com>",
  2036. author=b"John <john@example.com>",
  2037. )
  2038. # Make a change
  2039. with open(fullpath, "w") as f:
  2040. f.write("modified content\n")
  2041. porcelain.add(self.repo.path, paths=[fullpath])
  2042. change_sha = porcelain.commit(
  2043. self.repo.path,
  2044. message=b"Change content",
  2045. committer=b"Jane <jane@example.com>",
  2046. author=b"John <john@example.com>",
  2047. )
  2048. # Revert the change
  2049. revert_sha = porcelain.revert(self.repo.path, commits=[change_sha])
  2050. # Check the file content is back to initial
  2051. with open(fullpath) as f:
  2052. self.assertEqual("initial content\n", f.read())
  2053. # Check the revert commit message
  2054. revert_commit = self.repo[revert_sha]
  2055. self.assertIn(b'Revert "Change content"', revert_commit.message)
  2056. self.assertIn(change_sha[:7], revert_commit.message)
  2057. def test_revert_multiple(self) -> None:
  2058. # Create initial commit
  2059. fullpath = os.path.join(self.repo.path, "foo")
  2060. with open(fullpath, "w") as f:
  2061. f.write("line1\n")
  2062. porcelain.add(self.repo.path, paths=[fullpath])
  2063. porcelain.commit(
  2064. self.repo.path,
  2065. message=b"Initial commit",
  2066. committer=b"Jane <jane@example.com>",
  2067. author=b"John <john@example.com>",
  2068. )
  2069. # Add line2
  2070. with open(fullpath, "a") as f:
  2071. f.write("line2\n")
  2072. porcelain.add(self.repo.path, paths=[fullpath])
  2073. commit1 = porcelain.commit(
  2074. self.repo.path,
  2075. message=b"Add line2",
  2076. committer=b"Jane <jane@example.com>",
  2077. author=b"John <john@example.com>",
  2078. )
  2079. # Add line3
  2080. with open(fullpath, "a") as f:
  2081. f.write("line3\n")
  2082. porcelain.add(self.repo.path, paths=[fullpath])
  2083. commit2 = porcelain.commit(
  2084. self.repo.path,
  2085. message=b"Add line3",
  2086. committer=b"Jane <jane@example.com>",
  2087. author=b"John <john@example.com>",
  2088. )
  2089. # Revert both commits (in reverse order)
  2090. porcelain.revert(self.repo.path, commits=[commit2, commit1])
  2091. # Check file is back to initial state
  2092. with open(fullpath) as f:
  2093. self.assertEqual("line1\n", f.read())
  2094. def test_revert_no_commit(self) -> None:
  2095. # Create initial commit
  2096. fullpath = os.path.join(self.repo.path, "foo")
  2097. with open(fullpath, "w") as f:
  2098. f.write("initial\n")
  2099. porcelain.add(self.repo.path, paths=[fullpath])
  2100. porcelain.commit(
  2101. self.repo.path,
  2102. message=b"Initial",
  2103. committer=b"Jane <jane@example.com>",
  2104. author=b"John <john@example.com>",
  2105. )
  2106. # Make a change
  2107. with open(fullpath, "w") as f:
  2108. f.write("changed\n")
  2109. porcelain.add(self.repo.path, paths=[fullpath])
  2110. change_sha = porcelain.commit(
  2111. self.repo.path,
  2112. message=b"Change",
  2113. committer=b"Jane <jane@example.com>",
  2114. author=b"John <john@example.com>",
  2115. )
  2116. # Revert with no_commit
  2117. result = porcelain.revert(self.repo.path, commits=[change_sha], no_commit=True)
  2118. # Should return None
  2119. self.assertIsNone(result)
  2120. # File should be reverted
  2121. with open(fullpath) as f:
  2122. self.assertEqual("initial\n", f.read())
  2123. # HEAD should still point to the change commit
  2124. self.assertEqual(self.repo.refs[b"HEAD"], change_sha)
  2125. def test_revert_custom_message(self) -> None:
  2126. # Create commits
  2127. fullpath = os.path.join(self.repo.path, "foo")
  2128. with open(fullpath, "w") as f:
  2129. f.write("initial\n")
  2130. porcelain.add(self.repo.path, paths=[fullpath])
  2131. porcelain.commit(
  2132. self.repo.path,
  2133. message=b"Initial",
  2134. committer=b"Jane <jane@example.com>",
  2135. author=b"John <john@example.com>",
  2136. )
  2137. with open(fullpath, "w") as f:
  2138. f.write("changed\n")
  2139. porcelain.add(self.repo.path, paths=[fullpath])
  2140. change_sha = porcelain.commit(
  2141. self.repo.path,
  2142. message=b"Change",
  2143. committer=b"Jane <jane@example.com>",
  2144. author=b"John <john@example.com>",
  2145. )
  2146. # Revert with custom message
  2147. custom_msg = "Custom revert message"
  2148. revert_sha = porcelain.revert(
  2149. self.repo.path, commits=[change_sha], message=custom_msg
  2150. )
  2151. # Check the message
  2152. revert_commit = self.repo[revert_sha]
  2153. self.assertEqual(custom_msg.encode("utf-8"), revert_commit.message)
  2154. def test_revert_no_parent(self) -> None:
  2155. # Try to revert the initial commit (no parent)
  2156. fullpath = os.path.join(self.repo.path, "foo")
  2157. with open(fullpath, "w") as f:
  2158. f.write("content\n")
  2159. porcelain.add(self.repo.path, paths=[fullpath])
  2160. initial_sha = porcelain.commit(
  2161. self.repo.path,
  2162. message=b"Initial",
  2163. committer=b"Jane <jane@example.com>",
  2164. author=b"John <john@example.com>",
  2165. )
  2166. # Should raise an error
  2167. with self.assertRaises(porcelain.Error) as cm:
  2168. porcelain.revert(self.repo.path, commits=[initial_sha])
  2169. self.assertIn("no parents", str(cm.exception))
  2170. class CheckoutTests(PorcelainTestCase):
  2171. def setUp(self) -> None:
  2172. super().setUp()
  2173. self._sha, self._foo_path = _commit_file_with_content(
  2174. self.repo, "foo", "hello\n"
  2175. )
  2176. porcelain.branch_create(self.repo, "uni")
  2177. def test_checkout_to_existing_branch(self) -> None:
  2178. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2179. porcelain.checkout(self.repo, b"uni")
  2180. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2181. def test_checkout_to_non_existing_branch(self) -> None:
  2182. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2183. with self.assertRaises(KeyError):
  2184. porcelain.checkout(self.repo, b"bob")
  2185. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2186. def test_checkout_to_branch_with_modified_files(self) -> None:
  2187. with open(self._foo_path, "a") as f:
  2188. f.write("new message\n")
  2189. porcelain.add(self.repo, paths=[self._foo_path])
  2190. status = list(porcelain.status(self.repo))
  2191. self.assertEqual(
  2192. [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status
  2193. )
  2194. # The new checkout behavior prevents switching with staged changes
  2195. with self.assertRaises(porcelain.CheckoutError):
  2196. porcelain.checkout(self.repo, b"uni")
  2197. # Should still be on master
  2198. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2199. # Force checkout should work
  2200. porcelain.checkout(self.repo, b"uni", force=True)
  2201. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2202. def test_checkout_with_deleted_files(self) -> None:
  2203. porcelain.remove(self.repo.path, [os.path.join(self.repo.path, "foo")])
  2204. status = list(porcelain.status(self.repo))
  2205. self.assertEqual(
  2206. [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status
  2207. )
  2208. # The new checkout behavior prevents switching with staged deletions
  2209. with self.assertRaises(porcelain.CheckoutError):
  2210. porcelain.checkout(self.repo, b"uni")
  2211. # Should still be on master
  2212. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2213. # Force checkout should work
  2214. porcelain.checkout(self.repo, b"uni", force=True)
  2215. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2216. def test_checkout_to_branch_with_added_files(self) -> None:
  2217. file_path = os.path.join(self.repo.path, "bar")
  2218. with open(file_path, "w") as f:
  2219. f.write("bar content\n")
  2220. porcelain.add(self.repo, paths=[file_path])
  2221. status = list(porcelain.status(self.repo))
  2222. self.assertEqual(
  2223. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  2224. )
  2225. # Both branches have file 'foo' checkout should be fine.
  2226. porcelain.checkout(self.repo, b"uni")
  2227. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2228. status = list(porcelain.status(self.repo))
  2229. self.assertEqual(
  2230. [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status
  2231. )
  2232. def test_checkout_to_branch_with_modified_file_not_present(self) -> None:
  2233. # Commit a new file that the other branch doesn't have.
  2234. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  2235. # Modify the file the other branch doesn't have.
  2236. with open(nee_path, "a") as f:
  2237. f.write("bar content\n")
  2238. porcelain.add(self.repo, paths=[nee_path])
  2239. status = list(porcelain.status(self.repo))
  2240. self.assertEqual(
  2241. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  2242. )
  2243. # The new checkout behavior allows switching if the file doesn't exist in target branch
  2244. # (changes can be preserved)
  2245. porcelain.checkout(self.repo, b"uni")
  2246. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2247. # The staged changes are lost and the file is removed from working tree
  2248. # because it doesn't exist in the target branch
  2249. status = list(porcelain.status(self.repo))
  2250. # File 'nee' is gone completely
  2251. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2252. self.assertFalse(os.path.exists(nee_path))
  2253. def test_checkout_to_branch_with_modified_file_not_present_forced(self) -> None:
  2254. # Commit a new file that the other branch doesn't have.
  2255. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n")
  2256. # Modify the file the other branch doesn't have.
  2257. with open(nee_path, "a") as f:
  2258. f.write("bar content\n")
  2259. porcelain.add(self.repo, paths=[nee_path])
  2260. status = list(porcelain.status(self.repo))
  2261. self.assertEqual(
  2262. [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status
  2263. )
  2264. # 'uni' branch doesn't have 'nee' and it has been modified, but we force to reset the entire index.
  2265. porcelain.checkout(self.repo, b"uni", force=True)
  2266. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2267. status = list(porcelain.status(self.repo))
  2268. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2269. def test_checkout_to_branch_with_unstaged_files(self) -> None:
  2270. # Edit `foo`.
  2271. with open(self._foo_path, "a") as f:
  2272. f.write("new message")
  2273. status = list(porcelain.status(self.repo))
  2274. self.assertEqual(
  2275. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  2276. )
  2277. # The new checkout behavior prevents switching with unstaged changes
  2278. with self.assertRaises(porcelain.CheckoutError):
  2279. porcelain.checkout(self.repo, b"uni")
  2280. # Should still be on master
  2281. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2282. # Force checkout should work
  2283. porcelain.checkout(self.repo, b"uni", force=True)
  2284. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2285. def test_checkout_to_branch_with_untracked_files(self) -> None:
  2286. with open(os.path.join(self.repo.path, "neu"), "a") as f:
  2287. f.write("new message\n")
  2288. status = list(porcelain.status(self.repo))
  2289. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  2290. porcelain.checkout(self.repo, b"uni")
  2291. status = list(porcelain.status(self.repo))
  2292. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status)
  2293. def test_checkout_to_branch_with_new_files(self) -> None:
  2294. porcelain.checkout(self.repo, b"uni")
  2295. sub_directory = os.path.join(self.repo.path, "sub1")
  2296. os.mkdir(sub_directory)
  2297. for index in range(5):
  2298. _commit_file_with_content(
  2299. self.repo, "new_file_" + str(index + 1), "Some content\n"
  2300. )
  2301. _commit_file_with_content(
  2302. self.repo,
  2303. os.path.join("sub1", "new_file_" + str(index + 10)),
  2304. "Good content\n",
  2305. )
  2306. status = list(porcelain.status(self.repo))
  2307. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2308. porcelain.checkout(self.repo, b"master")
  2309. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2310. status = list(porcelain.status(self.repo))
  2311. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2312. porcelain.checkout(self.repo, b"uni")
  2313. self.assertEqual(b"uni", porcelain.active_branch(self.repo))
  2314. status = list(porcelain.status(self.repo))
  2315. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2316. def test_checkout_to_branch_with_file_in_sub_directory(self) -> None:
  2317. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  2318. os.makedirs(sub_directory)
  2319. sub_directory_file = os.path.join(sub_directory, "neu")
  2320. with open(sub_directory_file, "w") as f:
  2321. f.write("new message\n")
  2322. porcelain.add(self.repo, paths=[sub_directory_file])
  2323. porcelain.commit(
  2324. self.repo,
  2325. message=b"add " + sub_directory_file.encode(),
  2326. committer=b"Jane <jane@example.com>",
  2327. author=b"John <john@example.com>",
  2328. )
  2329. status = list(porcelain.status(self.repo))
  2330. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2331. self.assertTrue(os.path.isdir(sub_directory))
  2332. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  2333. porcelain.checkout(self.repo, b"uni")
  2334. status = list(porcelain.status(self.repo))
  2335. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2336. self.assertFalse(os.path.isdir(sub_directory))
  2337. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  2338. porcelain.checkout(self.repo, b"master")
  2339. self.assertTrue(os.path.isdir(sub_directory))
  2340. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  2341. def test_checkout_to_branch_with_multiple_files_in_sub_directory(self) -> None:
  2342. sub_directory = os.path.join(self.repo.path, "sub1", "sub2")
  2343. os.makedirs(sub_directory)
  2344. sub_directory_file_1 = os.path.join(sub_directory, "neu")
  2345. with open(sub_directory_file_1, "w") as f:
  2346. f.write("new message\n")
  2347. sub_directory_file_2 = os.path.join(sub_directory, "gus")
  2348. with open(sub_directory_file_2, "w") as f:
  2349. f.write("alternative message\n")
  2350. porcelain.add(self.repo, paths=[sub_directory_file_1, sub_directory_file_2])
  2351. porcelain.commit(
  2352. self.repo,
  2353. message=b"add files neu and gus.",
  2354. committer=b"Jane <jane@example.com>",
  2355. author=b"John <john@example.com>",
  2356. )
  2357. status = list(porcelain.status(self.repo))
  2358. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2359. self.assertTrue(os.path.isdir(sub_directory))
  2360. self.assertTrue(os.path.isdir(os.path.dirname(sub_directory)))
  2361. porcelain.checkout(self.repo, b"uni")
  2362. status = list(porcelain.status(self.repo))
  2363. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status)
  2364. self.assertFalse(os.path.isdir(sub_directory))
  2365. self.assertFalse(os.path.isdir(os.path.dirname(sub_directory)))
  2366. def _commit_something_wrong(self):
  2367. with open(self._foo_path, "a") as f:
  2368. f.write("something wrong")
  2369. porcelain.add(self.repo, paths=[self._foo_path])
  2370. return porcelain.commit(
  2371. self.repo,
  2372. message=b"I may added something wrong",
  2373. committer=b"Jane <jane@example.com>",
  2374. author=b"John <john@example.com>",
  2375. )
  2376. def test_checkout_to_commit_sha(self) -> None:
  2377. self._commit_something_wrong()
  2378. porcelain.checkout(self.repo, self._sha)
  2379. self.assertEqual(self._sha, self.repo.head())
  2380. def test_checkout_to_head(self) -> None:
  2381. new_sha = self._commit_something_wrong()
  2382. porcelain.checkout(self.repo, b"HEAD")
  2383. self.assertEqual(new_sha, self.repo.head())
  2384. def _checkout_remote_branch(self):
  2385. errstream = BytesIO()
  2386. outstream = BytesIO()
  2387. porcelain.commit(
  2388. repo=self.repo.path,
  2389. message=b"init",
  2390. author=b"author <email>",
  2391. committer=b"committer <email>",
  2392. )
  2393. # Setup target repo cloned from temp test repo
  2394. clone_path = tempfile.mkdtemp()
  2395. self.addCleanup(shutil.rmtree, clone_path)
  2396. target_repo = porcelain.clone(
  2397. self.repo.path, target=clone_path, errstream=errstream
  2398. )
  2399. try:
  2400. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  2401. finally:
  2402. target_repo.close()
  2403. # create a second file to be pushed back to origin
  2404. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  2405. os.close(handle)
  2406. porcelain.add(repo=clone_path, paths=[fullpath])
  2407. porcelain.commit(
  2408. repo=clone_path,
  2409. message=b"push",
  2410. author=b"author <email>",
  2411. committer=b"committer <email>",
  2412. )
  2413. # Setup a non-checked out branch in the remote
  2414. refs_path = b"refs/heads/foo"
  2415. new_id = self.repo[b"HEAD"].id
  2416. self.assertNotEqual(new_id, ZERO_SHA)
  2417. self.repo.refs[refs_path] = new_id
  2418. # Push to the remote
  2419. porcelain.push(
  2420. clone_path,
  2421. "origin",
  2422. b"HEAD:" + refs_path,
  2423. outstream=outstream,
  2424. errstream=errstream,
  2425. )
  2426. self.assertEqual(
  2427. target_repo.refs[b"refs/remotes/origin/foo"],
  2428. target_repo.refs[b"HEAD"],
  2429. )
  2430. # The new checkout behavior treats origin/foo as a ref and creates detached HEAD
  2431. porcelain.checkout(target_repo, b"origin/foo")
  2432. original_id = target_repo[b"HEAD"].id
  2433. uni_id = target_repo[b"refs/remotes/origin/uni"].id
  2434. # Should be in detached HEAD state
  2435. with self.assertRaises((ValueError, IndexError)):
  2436. porcelain.active_branch(target_repo)
  2437. expected_refs = {
  2438. b"HEAD": original_id,
  2439. b"refs/heads/master": original_id,
  2440. # No local foo branch is created anymore
  2441. b"refs/remotes/origin/foo": original_id,
  2442. b"refs/remotes/origin/uni": uni_id,
  2443. b"refs/remotes/origin/HEAD": new_id,
  2444. b"refs/remotes/origin/master": new_id,
  2445. }
  2446. self.assertEqual(expected_refs, target_repo.get_refs())
  2447. return target_repo
  2448. def test_checkout_remote_branch(self) -> None:
  2449. repo = self._checkout_remote_branch()
  2450. repo.close()
  2451. def test_checkout_remote_branch_then_master_then_remote_branch_again(self) -> None:
  2452. target_repo = self._checkout_remote_branch()
  2453. # Should be in detached HEAD state
  2454. with self.assertRaises((ValueError, IndexError)):
  2455. porcelain.active_branch(target_repo)
  2456. # Save the commit SHA before adding bar
  2457. detached_commit_sha, _ = _commit_file_with_content(
  2458. target_repo, "bar", "something\n"
  2459. )
  2460. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  2461. porcelain.checkout(target_repo, b"master")
  2462. self.assertEqual(b"master", porcelain.active_branch(target_repo))
  2463. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  2464. # Going back to origin/foo won't have bar because the commit was made in detached state
  2465. porcelain.checkout(target_repo, b"origin/foo")
  2466. # Should be in detached HEAD state again
  2467. with self.assertRaises((ValueError, IndexError)):
  2468. porcelain.active_branch(target_repo)
  2469. # bar is NOT there because we're back at the original origin/foo commit
  2470. self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar")))
  2471. # But we can checkout the specific commit to get bar back
  2472. porcelain.checkout(target_repo, detached_commit_sha.decode())
  2473. self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar")))
  2474. target_repo.close()
  2475. class GeneralCheckoutTests(PorcelainTestCase):
  2476. """Tests for the general checkout function that handles branches, tags, and commits."""
  2477. def setUp(self) -> None:
  2478. super().setUp()
  2479. # Create initial commit
  2480. self._sha1, self._foo_path = _commit_file_with_content(
  2481. self.repo, "foo", "initial content\n"
  2482. )
  2483. # Create a branch
  2484. porcelain.branch_create(self.repo, "feature")
  2485. # Create another commit on master
  2486. self._sha2, self._bar_path = _commit_file_with_content(
  2487. self.repo, "bar", "bar content\n"
  2488. )
  2489. # Create a tag
  2490. porcelain.tag_create(self.repo, "v1.0", objectish=self._sha1)
  2491. def test_checkout_branch(self) -> None:
  2492. """Test checking out a branch."""
  2493. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2494. # Checkout feature branch
  2495. porcelain.checkout(self.repo, "feature")
  2496. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2497. # File 'bar' should not exist in feature branch
  2498. self.assertFalse(os.path.exists(self._bar_path))
  2499. # Go back to master
  2500. porcelain.checkout(self.repo, "master")
  2501. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2502. # File 'bar' should exist again
  2503. self.assertTrue(os.path.exists(self._bar_path))
  2504. def test_checkout_commit(self) -> None:
  2505. """Test checking out a specific commit (detached HEAD)."""
  2506. # Checkout first commit by SHA
  2507. porcelain.checkout(self.repo, self._sha1.decode("ascii"))
  2508. # Should be in detached HEAD state - active_branch raises IndexError
  2509. with self.assertRaises((ValueError, IndexError)):
  2510. porcelain.active_branch(self.repo)
  2511. # File 'bar' should not exist
  2512. self.assertFalse(os.path.exists(self._bar_path))
  2513. # HEAD should point to the commit
  2514. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  2515. def test_checkout_tag(self) -> None:
  2516. """Test checking out a tag (detached HEAD)."""
  2517. # Checkout tag
  2518. porcelain.checkout(self.repo, "v1.0")
  2519. # Should be in detached HEAD state - active_branch raises IndexError
  2520. with self.assertRaises((ValueError, IndexError)):
  2521. porcelain.active_branch(self.repo)
  2522. # File 'bar' should not exist (tag points to first commit)
  2523. self.assertFalse(os.path.exists(self._bar_path))
  2524. # HEAD should point to the tagged commit
  2525. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  2526. def test_checkout_new_branch(self) -> None:
  2527. """Test creating a new branch during checkout (like git checkout -b)."""
  2528. # Create and checkout new branch from current HEAD
  2529. porcelain.checkout(self.repo, "master", new_branch="new-feature")
  2530. self.assertEqual(b"new-feature", porcelain.active_branch(self.repo))
  2531. self.assertTrue(os.path.exists(self._bar_path))
  2532. # Create and checkout new branch from specific commit
  2533. porcelain.checkout(self.repo, self._sha1.decode("ascii"), new_branch="from-old")
  2534. self.assertEqual(b"from-old", porcelain.active_branch(self.repo))
  2535. self.assertFalse(os.path.exists(self._bar_path))
  2536. def test_checkout_with_uncommitted_changes(self) -> None:
  2537. """Test checkout behavior with uncommitted changes."""
  2538. # Modify a file
  2539. with open(self._foo_path, "w") as f:
  2540. f.write("modified content\n")
  2541. # Should raise error when trying to checkout
  2542. with self.assertRaises(porcelain.CheckoutError) as cm:
  2543. porcelain.checkout(self.repo, "feature")
  2544. self.assertIn("local changes", str(cm.exception))
  2545. self.assertIn("foo", str(cm.exception))
  2546. # Should still be on master
  2547. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2548. def test_checkout_force(self) -> None:
  2549. """Test forced checkout discards local changes."""
  2550. # Modify a file
  2551. with open(self._foo_path, "w") as f:
  2552. f.write("modified content\n")
  2553. # Force checkout should succeed
  2554. porcelain.checkout(self.repo, "feature", force=True)
  2555. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2556. # Local changes should be discarded
  2557. with open(self._foo_path) as f:
  2558. content = f.read()
  2559. self.assertEqual("initial content\n", content)
  2560. def test_checkout_nonexistent_ref(self) -> None:
  2561. """Test checkout of non-existent branch/commit."""
  2562. with self.assertRaises(KeyError):
  2563. porcelain.checkout(self.repo, "nonexistent")
  2564. def test_checkout_partial_sha(self) -> None:
  2565. """Test checkout with partial SHA."""
  2566. # Git typically allows checkout with partial SHA
  2567. partial_sha = self._sha1.decode("ascii")[:7]
  2568. porcelain.checkout(self.repo, partial_sha)
  2569. # Should be in detached HEAD state at the right commit
  2570. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  2571. def test_checkout_preserves_untracked_files(self) -> None:
  2572. """Test that checkout preserves untracked files."""
  2573. # Create an untracked file
  2574. untracked_path = os.path.join(self.repo.path, "untracked.txt")
  2575. with open(untracked_path, "w") as f:
  2576. f.write("untracked content\n")
  2577. # Checkout another branch
  2578. porcelain.checkout(self.repo, "feature")
  2579. # Untracked file should still exist
  2580. self.assertTrue(os.path.exists(untracked_path))
  2581. with open(untracked_path) as f:
  2582. content = f.read()
  2583. self.assertEqual("untracked content\n", content)
  2584. def test_checkout_full_ref_paths(self) -> None:
  2585. """Test checkout with full ref paths."""
  2586. # Test checkout with full branch ref path
  2587. porcelain.checkout(self.repo, "refs/heads/feature")
  2588. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2589. # Test checkout with full tag ref path
  2590. porcelain.checkout(self.repo, "refs/tags/v1.0")
  2591. # Should be in detached HEAD state
  2592. with self.assertRaises((ValueError, IndexError)):
  2593. porcelain.active_branch(self.repo)
  2594. self.assertEqual(self._sha1, self.repo.refs[b"HEAD"])
  2595. def test_checkout_bytes_vs_string_target(self) -> None:
  2596. """Test that checkout works with both bytes and string targets."""
  2597. # Test with string target
  2598. porcelain.checkout(self.repo, "feature")
  2599. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2600. # Test with bytes target
  2601. porcelain.checkout(self.repo, b"master")
  2602. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  2603. def test_checkout_new_branch_from_commit(self) -> None:
  2604. """Test creating a new branch from a specific commit."""
  2605. # Create new branch from first commit
  2606. porcelain.checkout(self.repo, self._sha1.decode(), new_branch="from-commit")
  2607. self.assertEqual(b"from-commit", porcelain.active_branch(self.repo))
  2608. # Should be at the first commit (no bar file)
  2609. self.assertFalse(os.path.exists(self._bar_path))
  2610. def test_checkout_with_staged_addition(self) -> None:
  2611. """Test checkout behavior with staged file additions."""
  2612. # Create and stage a new file that doesn't exist in target branch
  2613. new_file_path = os.path.join(self.repo.path, "new.txt")
  2614. with open(new_file_path, "w") as f:
  2615. f.write("new file content\n")
  2616. porcelain.add(self.repo, [new_file_path])
  2617. # This should succeed because the file doesn't exist in target branch
  2618. porcelain.checkout(self.repo, "feature")
  2619. # Should be on feature branch
  2620. self.assertEqual(b"feature", porcelain.active_branch(self.repo))
  2621. # The new file should still exist and be staged
  2622. self.assertTrue(os.path.exists(new_file_path))
  2623. status = porcelain.status(self.repo)
  2624. self.assertIn(b"new.txt", status.staged["add"])
  2625. def test_checkout_with_staged_modification_conflict(self) -> None:
  2626. """Test checkout behavior with staged modifications that would conflict."""
  2627. # Stage changes to a file that exists in both branches
  2628. with open(self._foo_path, "w") as f:
  2629. f.write("modified content\n")
  2630. porcelain.add(self.repo, [self._foo_path])
  2631. # Should prevent checkout due to staged changes to existing file
  2632. with self.assertRaises(porcelain.CheckoutError) as cm:
  2633. porcelain.checkout(self.repo, "feature")
  2634. self.assertIn("local changes", str(cm.exception))
  2635. self.assertIn("foo", str(cm.exception))
  2636. def test_checkout_head_reference(self) -> None:
  2637. """Test checkout of HEAD reference."""
  2638. # Move to feature branch first
  2639. porcelain.checkout(self.repo, "feature")
  2640. # Checkout HEAD creates detached HEAD state
  2641. porcelain.checkout(self.repo, "HEAD")
  2642. # Should be in detached HEAD state
  2643. with self.assertRaises((ValueError, IndexError)):
  2644. porcelain.active_branch(self.repo)
  2645. def test_checkout_error_messages(self) -> None:
  2646. """Test that checkout error messages are helpful."""
  2647. # Create uncommitted changes
  2648. with open(self._foo_path, "w") as f:
  2649. f.write("uncommitted changes\n")
  2650. # Try to checkout
  2651. with self.assertRaises(porcelain.CheckoutError) as cm:
  2652. porcelain.checkout(self.repo, "feature")
  2653. error_msg = str(cm.exception)
  2654. self.assertIn("local changes", error_msg)
  2655. self.assertIn("foo", error_msg)
  2656. self.assertIn("overwritten", error_msg)
  2657. self.assertIn("commit or stash", error_msg)
  2658. class SubmoduleTests(PorcelainTestCase):
  2659. def test_empty(self) -> None:
  2660. porcelain.commit(
  2661. repo=self.repo.path,
  2662. message=b"init",
  2663. author=b"author <email>",
  2664. committer=b"committer <email>",
  2665. )
  2666. self.assertEqual([], list(porcelain.submodule_list(self.repo)))
  2667. def test_add(self) -> None:
  2668. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  2669. with open(f"{self.repo.path}/.gitmodules") as f:
  2670. self.assertEqual(
  2671. """\
  2672. [submodule "bar"]
  2673. \turl = ../bar.git
  2674. \tpath = bar
  2675. """,
  2676. f.read(),
  2677. )
  2678. def test_init(self) -> None:
  2679. porcelain.submodule_add(self.repo, "../bar.git", "bar")
  2680. porcelain.submodule_init(self.repo)
  2681. class PushTests(PorcelainTestCase):
  2682. def test_simple(self) -> None:
  2683. """Basic test of porcelain push where self.repo is the remote. First
  2684. clone the remote, commit a file to the clone, then push the changes
  2685. back to the remote.
  2686. """
  2687. outstream = BytesIO()
  2688. errstream = BytesIO()
  2689. porcelain.commit(
  2690. repo=self.repo.path,
  2691. message=b"init",
  2692. author=b"author <email>",
  2693. committer=b"committer <email>",
  2694. )
  2695. # Setup target repo cloned from temp test repo
  2696. clone_path = tempfile.mkdtemp()
  2697. self.addCleanup(shutil.rmtree, clone_path)
  2698. target_repo = porcelain.clone(
  2699. self.repo.path, target=clone_path, errstream=errstream
  2700. )
  2701. try:
  2702. self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"])
  2703. finally:
  2704. target_repo.close()
  2705. # create a second file to be pushed back to origin
  2706. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  2707. os.close(handle)
  2708. porcelain.add(repo=clone_path, paths=[fullpath])
  2709. porcelain.commit(
  2710. repo=clone_path,
  2711. message=b"push",
  2712. author=b"author <email>",
  2713. committer=b"committer <email>",
  2714. )
  2715. # Setup a non-checked out branch in the remote
  2716. refs_path = b"refs/heads/foo"
  2717. new_id = self.repo[b"HEAD"].id
  2718. self.assertNotEqual(new_id, ZERO_SHA)
  2719. self.repo.refs[refs_path] = new_id
  2720. # Push to the remote
  2721. porcelain.push(
  2722. clone_path,
  2723. "origin",
  2724. b"HEAD:" + refs_path,
  2725. outstream=outstream,
  2726. errstream=errstream,
  2727. )
  2728. self.assertEqual(
  2729. target_repo.refs[b"refs/remotes/origin/foo"],
  2730. target_repo.refs[b"HEAD"],
  2731. )
  2732. # Check that the target and source
  2733. with Repo(clone_path) as r_clone:
  2734. self.assertEqual(
  2735. {
  2736. b"HEAD": new_id,
  2737. b"refs/heads/foo": r_clone[b"HEAD"].id,
  2738. b"refs/heads/master": new_id,
  2739. },
  2740. self.repo.get_refs(),
  2741. )
  2742. self.assertEqual(r_clone[b"HEAD"].id, self.repo[refs_path].id)
  2743. # Get the change in the target repo corresponding to the add
  2744. # this will be in the foo branch.
  2745. change = next(
  2746. iter(
  2747. tree_changes(
  2748. self.repo,
  2749. self.repo[b"HEAD"].tree,
  2750. self.repo[b"refs/heads/foo"].tree,
  2751. )
  2752. )
  2753. )
  2754. self.assertEqual(
  2755. os.path.basename(fullpath), change.new.path.decode("ascii")
  2756. )
  2757. def test_local_missing(self) -> None:
  2758. """Pushing a new branch."""
  2759. outstream = BytesIO()
  2760. errstream = BytesIO()
  2761. # Setup target repo cloned from temp test repo
  2762. clone_path = tempfile.mkdtemp()
  2763. self.addCleanup(shutil.rmtree, clone_path)
  2764. target_repo = porcelain.init(clone_path)
  2765. target_repo.close()
  2766. self.assertRaises(
  2767. porcelain.Error,
  2768. porcelain.push,
  2769. self.repo,
  2770. clone_path,
  2771. b"HEAD:refs/heads/master",
  2772. outstream=outstream,
  2773. errstream=errstream,
  2774. )
  2775. def test_new(self) -> None:
  2776. """Pushing a new branch."""
  2777. outstream = BytesIO()
  2778. errstream = BytesIO()
  2779. # Setup target repo cloned from temp test repo
  2780. clone_path = tempfile.mkdtemp()
  2781. self.addCleanup(shutil.rmtree, clone_path)
  2782. target_repo = porcelain.init(clone_path)
  2783. target_repo.close()
  2784. # create a second file to be pushed back to origin
  2785. handle, fullpath = tempfile.mkstemp(dir=clone_path)
  2786. os.close(handle)
  2787. porcelain.add(repo=clone_path, paths=[fullpath])
  2788. new_id = porcelain.commit(
  2789. repo=self.repo,
  2790. message=b"push",
  2791. author=b"author <email>",
  2792. committer=b"committer <email>",
  2793. )
  2794. # Push to the remote
  2795. porcelain.push(
  2796. self.repo,
  2797. clone_path,
  2798. b"HEAD:refs/heads/master",
  2799. outstream=outstream,
  2800. errstream=errstream,
  2801. )
  2802. with Repo(clone_path) as r_clone:
  2803. self.assertEqual(
  2804. {
  2805. b"HEAD": new_id,
  2806. b"refs/heads/master": new_id,
  2807. },
  2808. r_clone.get_refs(),
  2809. )
  2810. def test_delete(self) -> None:
  2811. """Basic test of porcelain push, removing a branch."""
  2812. outstream = BytesIO()
  2813. errstream = BytesIO()
  2814. porcelain.commit(
  2815. repo=self.repo.path,
  2816. message=b"init",
  2817. author=b"author <email>",
  2818. committer=b"committer <email>",
  2819. )
  2820. # Setup target repo cloned from temp test repo
  2821. clone_path = tempfile.mkdtemp()
  2822. self.addCleanup(shutil.rmtree, clone_path)
  2823. target_repo = porcelain.clone(
  2824. self.repo.path, target=clone_path, errstream=errstream
  2825. )
  2826. target_repo.close()
  2827. # Setup a non-checked out branch in the remote
  2828. refs_path = b"refs/heads/foo"
  2829. new_id = self.repo[b"HEAD"].id
  2830. self.assertNotEqual(new_id, ZERO_SHA)
  2831. self.repo.refs[refs_path] = new_id
  2832. # Push to the remote
  2833. porcelain.push(
  2834. clone_path,
  2835. self.repo.path,
  2836. b":" + refs_path,
  2837. outstream=outstream,
  2838. errstream=errstream,
  2839. )
  2840. self.assertEqual(
  2841. {
  2842. b"HEAD": new_id,
  2843. b"refs/heads/master": new_id,
  2844. },
  2845. self.repo.get_refs(),
  2846. )
  2847. def test_diverged(self) -> None:
  2848. outstream = BytesIO()
  2849. errstream = BytesIO()
  2850. porcelain.commit(
  2851. repo=self.repo.path,
  2852. message=b"init",
  2853. author=b"author <email>",
  2854. committer=b"committer <email>",
  2855. )
  2856. # Setup target repo cloned from temp test repo
  2857. clone_path = tempfile.mkdtemp()
  2858. self.addCleanup(shutil.rmtree, clone_path)
  2859. target_repo = porcelain.clone(
  2860. self.repo.path, target=clone_path, errstream=errstream
  2861. )
  2862. target_repo.close()
  2863. remote_id = porcelain.commit(
  2864. repo=self.repo.path,
  2865. message=b"remote change",
  2866. author=b"author <email>",
  2867. committer=b"committer <email>",
  2868. )
  2869. local_id = porcelain.commit(
  2870. repo=clone_path,
  2871. message=b"local change",
  2872. author=b"author <email>",
  2873. committer=b"committer <email>",
  2874. )
  2875. outstream = BytesIO()
  2876. errstream = BytesIO()
  2877. # Push to the remote
  2878. self.assertRaises(
  2879. porcelain.DivergedBranches,
  2880. porcelain.push,
  2881. clone_path,
  2882. self.repo.path,
  2883. b"refs/heads/master",
  2884. outstream=outstream,
  2885. errstream=errstream,
  2886. )
  2887. self.assertEqual(
  2888. {
  2889. b"HEAD": remote_id,
  2890. b"refs/heads/master": remote_id,
  2891. },
  2892. self.repo.get_refs(),
  2893. )
  2894. self.assertEqual(b"", outstream.getvalue())
  2895. self.assertEqual(b"", errstream.getvalue())
  2896. outstream = BytesIO()
  2897. errstream = BytesIO()
  2898. # Push to the remote with --force
  2899. porcelain.push(
  2900. clone_path,
  2901. self.repo.path,
  2902. b"refs/heads/master",
  2903. outstream=outstream,
  2904. errstream=errstream,
  2905. force=True,
  2906. )
  2907. self.assertEqual(
  2908. {
  2909. b"HEAD": local_id,
  2910. b"refs/heads/master": local_id,
  2911. },
  2912. self.repo.get_refs(),
  2913. )
  2914. self.assertEqual(b"", outstream.getvalue())
  2915. self.assertTrue(re.match(b"Push to .* successful.\n", errstream.getvalue()))
  2916. class PullTests(PorcelainTestCase):
  2917. def setUp(self) -> None:
  2918. super().setUp()
  2919. # create a file for initial commit
  2920. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  2921. os.close(handle)
  2922. porcelain.add(repo=self.repo.path, paths=fullpath)
  2923. porcelain.commit(
  2924. repo=self.repo.path,
  2925. message=b"test",
  2926. author=b"test <email>",
  2927. committer=b"test <email>",
  2928. )
  2929. # Setup target repo
  2930. self.target_path = tempfile.mkdtemp()
  2931. self.addCleanup(shutil.rmtree, self.target_path)
  2932. target_repo = porcelain.clone(
  2933. self.repo.path, target=self.target_path, errstream=BytesIO()
  2934. )
  2935. target_repo.close()
  2936. # create a second file to be pushed
  2937. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  2938. os.close(handle)
  2939. porcelain.add(repo=self.repo.path, paths=fullpath)
  2940. porcelain.commit(
  2941. repo=self.repo.path,
  2942. message=b"test2",
  2943. author=b"test2 <email>",
  2944. committer=b"test2 <email>",
  2945. )
  2946. self.assertIn(b"refs/heads/master", self.repo.refs)
  2947. self.assertIn(b"refs/heads/master", target_repo.refs)
  2948. def test_simple(self) -> None:
  2949. outstream = BytesIO()
  2950. errstream = BytesIO()
  2951. # Pull changes into the cloned repo
  2952. porcelain.pull(
  2953. self.target_path,
  2954. self.repo.path,
  2955. b"refs/heads/master",
  2956. outstream=outstream,
  2957. errstream=errstream,
  2958. )
  2959. # Check the target repo for pushed changes
  2960. with Repo(self.target_path) as r:
  2961. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  2962. def test_diverged(self) -> None:
  2963. outstream = BytesIO()
  2964. errstream = BytesIO()
  2965. c3a = porcelain.commit(
  2966. repo=self.target_path,
  2967. message=b"test3a",
  2968. author=b"test2 <email>",
  2969. committer=b"test2 <email>",
  2970. )
  2971. porcelain.commit(
  2972. repo=self.repo.path,
  2973. message=b"test3b",
  2974. author=b"test2 <email>",
  2975. committer=b"test2 <email>",
  2976. )
  2977. # Pull changes into the cloned repo
  2978. self.assertRaises(
  2979. porcelain.DivergedBranches,
  2980. porcelain.pull,
  2981. self.target_path,
  2982. self.repo.path,
  2983. b"refs/heads/master",
  2984. outstream=outstream,
  2985. errstream=errstream,
  2986. )
  2987. # Check the target repo for pushed changes
  2988. with Repo(self.target_path) as r:
  2989. self.assertEqual(r[b"refs/heads/master"].id, c3a)
  2990. # Pull with merge should now work
  2991. porcelain.pull(
  2992. self.target_path,
  2993. self.repo.path,
  2994. b"refs/heads/master",
  2995. outstream=outstream,
  2996. errstream=errstream,
  2997. fast_forward=False,
  2998. )
  2999. # Check the target repo for merged changes
  3000. with Repo(self.target_path) as r:
  3001. # HEAD should now be a merge commit
  3002. head = r[b"HEAD"]
  3003. # It should have two parents
  3004. self.assertEqual(len(head.parents), 2)
  3005. # One parent should be the previous HEAD (c3a)
  3006. self.assertIn(c3a, head.parents)
  3007. # The other parent should be from the source repo
  3008. self.assertIn(self.repo[b"HEAD"].id, head.parents)
  3009. def test_no_refspec(self) -> None:
  3010. outstream = BytesIO()
  3011. errstream = BytesIO()
  3012. # Pull changes into the cloned repo
  3013. porcelain.pull(
  3014. self.target_path,
  3015. self.repo.path,
  3016. outstream=outstream,
  3017. errstream=errstream,
  3018. )
  3019. # Check the target repo for pushed changes
  3020. with Repo(self.target_path) as r:
  3021. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  3022. def test_no_remote_location(self) -> None:
  3023. outstream = BytesIO()
  3024. errstream = BytesIO()
  3025. # Pull changes into the cloned repo
  3026. porcelain.pull(
  3027. self.target_path,
  3028. refspecs=b"refs/heads/master",
  3029. outstream=outstream,
  3030. errstream=errstream,
  3031. )
  3032. # Check the target repo for pushed changes
  3033. with Repo(self.target_path) as r:
  3034. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  3035. def test_pull_updates_working_tree(self) -> None:
  3036. """Test that pull updates the working tree with new files."""
  3037. outstream = BytesIO()
  3038. errstream = BytesIO()
  3039. # Create a new file with content in the source repo
  3040. new_file = os.path.join(self.repo.path, "newfile.txt")
  3041. with open(new_file, "w") as f:
  3042. f.write("This is new content")
  3043. porcelain.add(repo=self.repo.path, paths=[new_file])
  3044. porcelain.commit(
  3045. repo=self.repo.path,
  3046. message=b"Add new file",
  3047. author=b"test <email>",
  3048. committer=b"test <email>",
  3049. )
  3050. # Before pull, the file should not exist in target
  3051. target_file = os.path.join(self.target_path, "newfile.txt")
  3052. self.assertFalse(os.path.exists(target_file))
  3053. # Pull changes into the cloned repo
  3054. porcelain.pull(
  3055. self.target_path,
  3056. self.repo.path,
  3057. b"refs/heads/master",
  3058. outstream=outstream,
  3059. errstream=errstream,
  3060. )
  3061. # After pull, the file should exist with correct content
  3062. self.assertTrue(os.path.exists(target_file))
  3063. with open(target_file) as f:
  3064. self.assertEqual(f.read(), "This is new content")
  3065. # Check the HEAD is updated too
  3066. with Repo(self.target_path) as r:
  3067. self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id)
  3068. class StatusTests(PorcelainTestCase):
  3069. def test_empty(self) -> None:
  3070. results = porcelain.status(self.repo)
  3071. self.assertEqual({"add": [], "delete": [], "modify": []}, results.staged)
  3072. self.assertEqual([], results.unstaged)
  3073. def test_status_base(self) -> None:
  3074. """Integration test for `status` functionality."""
  3075. # Commit a dummy file then modify it
  3076. fullpath = os.path.join(self.repo.path, "foo")
  3077. with open(fullpath, "w") as f:
  3078. f.write("origstuff")
  3079. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3080. porcelain.commit(
  3081. repo=self.repo.path,
  3082. message=b"test status",
  3083. author=b"author <email>",
  3084. committer=b"committer <email>",
  3085. )
  3086. # modify access and modify time of path
  3087. os.utime(fullpath, (0, 0))
  3088. with open(fullpath, "wb") as f:
  3089. f.write(b"stuff")
  3090. # Make a dummy file and stage it
  3091. filename_add = "bar"
  3092. fullpath = os.path.join(self.repo.path, filename_add)
  3093. with open(fullpath, "w") as f:
  3094. f.write("stuff")
  3095. porcelain.add(repo=self.repo.path, paths=fullpath)
  3096. results = porcelain.status(self.repo)
  3097. self.assertEqual(results.staged["add"][0], filename_add.encode("ascii"))
  3098. self.assertEqual(results.unstaged, [b"foo"])
  3099. def test_status_all(self) -> None:
  3100. del_path = os.path.join(self.repo.path, "foo")
  3101. mod_path = os.path.join(self.repo.path, "bar")
  3102. add_path = os.path.join(self.repo.path, "baz")
  3103. us_path = os.path.join(self.repo.path, "blye")
  3104. ut_path = os.path.join(self.repo.path, "blyat")
  3105. with open(del_path, "w") as f:
  3106. f.write("origstuff")
  3107. with open(mod_path, "w") as f:
  3108. f.write("origstuff")
  3109. with open(us_path, "w") as f:
  3110. f.write("origstuff")
  3111. porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path])
  3112. porcelain.commit(
  3113. repo=self.repo.path,
  3114. message=b"test status",
  3115. author=b"author <email>",
  3116. committer=b"committer <email>",
  3117. )
  3118. porcelain.remove(self.repo.path, [del_path])
  3119. with open(add_path, "w") as f:
  3120. f.write("origstuff")
  3121. with open(mod_path, "w") as f:
  3122. f.write("more_origstuff")
  3123. with open(us_path, "w") as f:
  3124. f.write("more_origstuff")
  3125. porcelain.add(repo=self.repo.path, paths=[add_path, mod_path])
  3126. with open(us_path, "w") as f:
  3127. f.write("\norigstuff")
  3128. with open(ut_path, "w") as f:
  3129. f.write("origstuff")
  3130. results = porcelain.status(self.repo.path)
  3131. self.assertDictEqual(
  3132. {"add": [b"baz"], "delete": [b"foo"], "modify": [b"bar"]},
  3133. results.staged,
  3134. )
  3135. self.assertListEqual(results.unstaged, [b"blye"])
  3136. results_no_untracked = porcelain.status(self.repo.path, untracked_files="no")
  3137. self.assertListEqual(results_no_untracked.untracked, [])
  3138. def test_status_wrong_untracked_files_value(self) -> None:
  3139. with self.assertRaises(ValueError):
  3140. porcelain.status(self.repo.path, untracked_files="antani")
  3141. def test_status_untracked_path(self) -> None:
  3142. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  3143. os.mkdir(untracked_dir)
  3144. untracked_file = os.path.join(untracked_dir, "untracked_file")
  3145. with open(untracked_file, "w") as fh:
  3146. fh.write("untracked")
  3147. _, _, untracked = porcelain.status(self.repo.path, untracked_files="all")
  3148. self.assertEqual(untracked, ["untracked_dir/untracked_file"])
  3149. def test_status_untracked_path_normal(self) -> None:
  3150. # Create an untracked directory with multiple files
  3151. untracked_dir = os.path.join(self.repo_path, "untracked_dir")
  3152. os.mkdir(untracked_dir)
  3153. untracked_file1 = os.path.join(untracked_dir, "file1")
  3154. untracked_file2 = os.path.join(untracked_dir, "file2")
  3155. with open(untracked_file1, "w") as fh:
  3156. fh.write("untracked1")
  3157. with open(untracked_file2, "w") as fh:
  3158. fh.write("untracked2")
  3159. # Create a nested untracked directory
  3160. nested_dir = os.path.join(untracked_dir, "nested")
  3161. os.mkdir(nested_dir)
  3162. nested_file = os.path.join(nested_dir, "file3")
  3163. with open(nested_file, "w") as fh:
  3164. fh.write("untracked3")
  3165. # Test "normal" mode - should only show the directory, not individual files
  3166. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  3167. self.assertEqual(untracked, ["untracked_dir/"])
  3168. # Test "all" mode - should show all files
  3169. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  3170. self.assertEqual(
  3171. sorted(untracked_all),
  3172. [
  3173. "untracked_dir/file1",
  3174. "untracked_dir/file2",
  3175. "untracked_dir/nested/file3",
  3176. ],
  3177. )
  3178. def test_status_mixed_tracked_untracked(self) -> None:
  3179. # Create a directory with both tracked and untracked files
  3180. mixed_dir = os.path.join(self.repo_path, "mixed_dir")
  3181. os.mkdir(mixed_dir)
  3182. # Add a tracked file
  3183. tracked_file = os.path.join(mixed_dir, "tracked.txt")
  3184. with open(tracked_file, "w") as fh:
  3185. fh.write("tracked content")
  3186. porcelain.add(self.repo.path, paths=[tracked_file])
  3187. porcelain.commit(
  3188. repo=self.repo.path,
  3189. message=b"add tracked file",
  3190. author=b"author <email>",
  3191. committer=b"committer <email>",
  3192. )
  3193. # Add untracked files to the same directory
  3194. untracked_file = os.path.join(mixed_dir, "untracked.txt")
  3195. with open(untracked_file, "w") as fh:
  3196. fh.write("untracked content")
  3197. # In "normal" mode, should show individual untracked files in mixed dirs
  3198. _, _, untracked = porcelain.status(self.repo.path, untracked_files="normal")
  3199. self.assertEqual(untracked, ["mixed_dir/untracked.txt"])
  3200. # In "all" mode, should be the same for mixed directories
  3201. _, _, untracked_all = porcelain.status(self.repo.path, untracked_files="all")
  3202. self.assertEqual(untracked_all, ["mixed_dir/untracked.txt"])
  3203. def test_status_crlf_mismatch(self) -> None:
  3204. # First make a commit as if the file has been added on a Linux system
  3205. # or with core.autocrlf=True
  3206. file_path = os.path.join(self.repo.path, "crlf")
  3207. with open(file_path, "wb") as f:
  3208. f.write(b"line1\nline2")
  3209. porcelain.add(repo=self.repo.path, paths=[file_path])
  3210. porcelain.commit(
  3211. repo=self.repo.path,
  3212. message=b"test status",
  3213. author=b"author <email>",
  3214. committer=b"committer <email>",
  3215. )
  3216. # Then update the file as if it was created by CGit on a Windows
  3217. # system with core.autocrlf=true
  3218. with open(file_path, "wb") as f:
  3219. f.write(b"line1\r\nline2")
  3220. results = porcelain.status(self.repo)
  3221. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  3222. self.assertListEqual(results.unstaged, [b"crlf"])
  3223. self.assertListEqual(results.untracked, [])
  3224. def test_status_autocrlf_true(self) -> None:
  3225. # First make a commit as if the file has been added on a Linux system
  3226. # or with core.autocrlf=True
  3227. file_path = os.path.join(self.repo.path, "crlf")
  3228. with open(file_path, "wb") as f:
  3229. f.write(b"line1\nline2")
  3230. porcelain.add(repo=self.repo.path, paths=[file_path])
  3231. porcelain.commit(
  3232. repo=self.repo.path,
  3233. message=b"test status",
  3234. author=b"author <email>",
  3235. committer=b"committer <email>",
  3236. )
  3237. # Then update the file as if it was created by CGit on a Windows
  3238. # system with core.autocrlf=true
  3239. with open(file_path, "wb") as f:
  3240. f.write(b"line1\r\nline2")
  3241. # TODO: It should be set automatically by looking at the configuration
  3242. c = self.repo.get_config()
  3243. c.set("core", "autocrlf", True)
  3244. c.write_to_path()
  3245. results = porcelain.status(self.repo)
  3246. self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged)
  3247. self.assertListEqual(results.unstaged, [])
  3248. self.assertListEqual(results.untracked, [])
  3249. def test_status_autocrlf_input(self) -> None:
  3250. # Commit existing file with CRLF
  3251. file_path = os.path.join(self.repo.path, "crlf-exists")
  3252. with open(file_path, "wb") as f:
  3253. f.write(b"line1\r\nline2")
  3254. porcelain.add(repo=self.repo.path, paths=[file_path])
  3255. porcelain.commit(
  3256. repo=self.repo.path,
  3257. message=b"test status",
  3258. author=b"author <email>",
  3259. committer=b"committer <email>",
  3260. )
  3261. c = self.repo.get_config()
  3262. c.set("core", "autocrlf", "input")
  3263. c.write_to_path()
  3264. # Add new (untracked) file
  3265. file_path = os.path.join(self.repo.path, "crlf-new")
  3266. with open(file_path, "wb") as f:
  3267. f.write(b"line1\r\nline2")
  3268. porcelain.add(repo=self.repo.path, paths=[file_path])
  3269. results = porcelain.status(self.repo)
  3270. self.assertDictEqual(
  3271. {"add": [b"crlf-new"], "delete": [], "modify": []}, results.staged
  3272. )
  3273. self.assertListEqual(results.unstaged, [])
  3274. self.assertListEqual(results.untracked, [])
  3275. def test_get_tree_changes_add(self) -> None:
  3276. """Unit test for get_tree_changes add."""
  3277. # Make a dummy file, stage
  3278. filename = "bar"
  3279. fullpath = os.path.join(self.repo.path, filename)
  3280. with open(fullpath, "w") as f:
  3281. f.write("stuff")
  3282. porcelain.add(repo=self.repo.path, paths=fullpath)
  3283. porcelain.commit(
  3284. repo=self.repo.path,
  3285. message=b"test status",
  3286. author=b"author <email>",
  3287. committer=b"committer <email>",
  3288. )
  3289. filename = "foo"
  3290. fullpath = os.path.join(self.repo.path, filename)
  3291. with open(fullpath, "w") as f:
  3292. f.write("stuff")
  3293. porcelain.add(repo=self.repo.path, paths=fullpath)
  3294. changes = porcelain.get_tree_changes(self.repo.path)
  3295. self.assertEqual(changes["add"][0], filename.encode("ascii"))
  3296. self.assertEqual(len(changes["add"]), 1)
  3297. self.assertEqual(len(changes["modify"]), 0)
  3298. self.assertEqual(len(changes["delete"]), 0)
  3299. def test_get_tree_changes_modify(self) -> None:
  3300. """Unit test for get_tree_changes modify."""
  3301. # Make a dummy file, stage, commit, modify
  3302. filename = "foo"
  3303. fullpath = os.path.join(self.repo.path, filename)
  3304. with open(fullpath, "w") as f:
  3305. f.write("stuff")
  3306. porcelain.add(repo=self.repo.path, paths=fullpath)
  3307. porcelain.commit(
  3308. repo=self.repo.path,
  3309. message=b"test status",
  3310. author=b"author <email>",
  3311. committer=b"committer <email>",
  3312. )
  3313. with open(fullpath, "w") as f:
  3314. f.write("otherstuff")
  3315. porcelain.add(repo=self.repo.path, paths=fullpath)
  3316. changes = porcelain.get_tree_changes(self.repo.path)
  3317. self.assertEqual(changes["modify"][0], filename.encode("ascii"))
  3318. self.assertEqual(len(changes["add"]), 0)
  3319. self.assertEqual(len(changes["modify"]), 1)
  3320. self.assertEqual(len(changes["delete"]), 0)
  3321. def test_get_tree_changes_delete(self) -> None:
  3322. """Unit test for get_tree_changes delete."""
  3323. # Make a dummy file, stage, commit, remove
  3324. filename = "foo"
  3325. fullpath = os.path.join(self.repo.path, filename)
  3326. with open(fullpath, "w") as f:
  3327. f.write("stuff")
  3328. porcelain.add(repo=self.repo.path, paths=fullpath)
  3329. porcelain.commit(
  3330. repo=self.repo.path,
  3331. message=b"test status",
  3332. author=b"author <email>",
  3333. committer=b"committer <email>",
  3334. )
  3335. cwd = os.getcwd()
  3336. try:
  3337. os.chdir(self.repo.path)
  3338. porcelain.remove(repo=self.repo.path, paths=[filename])
  3339. finally:
  3340. os.chdir(cwd)
  3341. changes = porcelain.get_tree_changes(self.repo.path)
  3342. self.assertEqual(changes["delete"][0], filename.encode("ascii"))
  3343. self.assertEqual(len(changes["add"]), 0)
  3344. self.assertEqual(len(changes["modify"]), 0)
  3345. self.assertEqual(len(changes["delete"]), 1)
  3346. def test_get_untracked_paths(self) -> None:
  3347. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3348. f.write("ignored\n")
  3349. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  3350. f.write("blah\n")
  3351. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  3352. f.write("blah\n")
  3353. os.symlink(
  3354. os.path.join(self.repo.path, os.pardir, "external_target"),
  3355. os.path.join(self.repo.path, "link"),
  3356. )
  3357. self.assertEqual(
  3358. {"ignored", "notignored", ".gitignore", "link"},
  3359. set(
  3360. porcelain.get_untracked_paths(
  3361. self.repo.path, self.repo.path, self.repo.open_index()
  3362. )
  3363. ),
  3364. )
  3365. self.assertEqual(
  3366. {".gitignore", "notignored", "link"},
  3367. set(porcelain.status(self.repo).untracked),
  3368. )
  3369. self.assertEqual(
  3370. {".gitignore", "notignored", "ignored", "link"},
  3371. set(porcelain.status(self.repo, ignored=True).untracked),
  3372. )
  3373. def test_get_untracked_paths_subrepo(self) -> None:
  3374. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3375. f.write("nested/\n")
  3376. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  3377. f.write("blah\n")
  3378. subrepo = Repo.init(os.path.join(self.repo.path, "nested"), mkdir=True)
  3379. with open(os.path.join(subrepo.path, "ignored"), "w") as f:
  3380. f.write("bleep\n")
  3381. with open(os.path.join(subrepo.path, "with"), "w") as f:
  3382. f.write("bloop\n")
  3383. with open(os.path.join(subrepo.path, "manager"), "w") as f:
  3384. f.write("blop\n")
  3385. self.assertEqual(
  3386. {".gitignore", "notignored", os.path.join("nested", "")},
  3387. set(
  3388. porcelain.get_untracked_paths(
  3389. self.repo.path, self.repo.path, self.repo.open_index()
  3390. )
  3391. ),
  3392. )
  3393. self.assertEqual(
  3394. {".gitignore", "notignored"},
  3395. set(
  3396. porcelain.get_untracked_paths(
  3397. self.repo.path,
  3398. self.repo.path,
  3399. self.repo.open_index(),
  3400. exclude_ignored=True,
  3401. )
  3402. ),
  3403. )
  3404. self.assertEqual(
  3405. {"ignored", "with", "manager"},
  3406. set(
  3407. porcelain.get_untracked_paths(
  3408. subrepo.path, subrepo.path, subrepo.open_index()
  3409. )
  3410. ),
  3411. )
  3412. self.assertEqual(
  3413. set(),
  3414. set(
  3415. porcelain.get_untracked_paths(
  3416. subrepo.path,
  3417. self.repo.path,
  3418. self.repo.open_index(),
  3419. )
  3420. ),
  3421. )
  3422. self.assertEqual(
  3423. {
  3424. os.path.join("nested", "ignored"),
  3425. os.path.join("nested", "with"),
  3426. os.path.join("nested", "manager"),
  3427. },
  3428. set(
  3429. porcelain.get_untracked_paths(
  3430. self.repo.path,
  3431. subrepo.path,
  3432. self.repo.open_index(),
  3433. )
  3434. ),
  3435. )
  3436. def test_get_untracked_paths_subdir(self) -> None:
  3437. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3438. f.write("subdir/\nignored")
  3439. with open(os.path.join(self.repo.path, "notignored"), "w") as f:
  3440. f.write("blah\n")
  3441. os.mkdir(os.path.join(self.repo.path, "subdir"))
  3442. with open(os.path.join(self.repo.path, "ignored"), "w") as f:
  3443. f.write("foo")
  3444. with open(os.path.join(self.repo.path, "subdir", "ignored"), "w") as f:
  3445. f.write("foo")
  3446. self.assertEqual(
  3447. {
  3448. ".gitignore",
  3449. "notignored",
  3450. "ignored",
  3451. os.path.join("subdir", ""),
  3452. },
  3453. set(
  3454. porcelain.get_untracked_paths(
  3455. self.repo.path,
  3456. self.repo.path,
  3457. self.repo.open_index(),
  3458. )
  3459. ),
  3460. )
  3461. self.assertEqual(
  3462. {".gitignore", "notignored"},
  3463. set(
  3464. porcelain.get_untracked_paths(
  3465. self.repo.path,
  3466. self.repo.path,
  3467. self.repo.open_index(),
  3468. exclude_ignored=True,
  3469. )
  3470. ),
  3471. )
  3472. def test_get_untracked_paths_invalid_untracked_files(self) -> None:
  3473. with self.assertRaises(ValueError):
  3474. list(
  3475. porcelain.get_untracked_paths(
  3476. self.repo.path,
  3477. self.repo.path,
  3478. self.repo.open_index(),
  3479. untracked_files="invalid_value",
  3480. )
  3481. )
  3482. def test_get_untracked_paths_normal(self) -> None:
  3483. # Create an untracked directory with files
  3484. untracked_dir = os.path.join(self.repo.path, "untracked_dir")
  3485. os.mkdir(untracked_dir)
  3486. with open(os.path.join(untracked_dir, "file1.txt"), "w") as f:
  3487. f.write("untracked content")
  3488. with open(os.path.join(untracked_dir, "file2.txt"), "w") as f:
  3489. f.write("more untracked content")
  3490. # Test that "normal" mode works and returns only the directory
  3491. _, _, untracked = porcelain.status(
  3492. repo=self.repo.path, untracked_files="normal"
  3493. )
  3494. self.assertEqual(untracked, ["untracked_dir/"])
  3495. def test_get_untracked_paths_top_level_issue_1247(self) -> None:
  3496. """Test for issue #1247: ensure top-level untracked files are detected."""
  3497. # Create a single top-level untracked file
  3498. with open(os.path.join(self.repo.path, "sample.txt"), "w") as f:
  3499. f.write("test content")
  3500. # Test get_untracked_paths directly
  3501. untracked = list(
  3502. porcelain.get_untracked_paths(
  3503. self.repo.path, self.repo.path, self.repo.open_index()
  3504. )
  3505. )
  3506. self.assertIn(
  3507. "sample.txt",
  3508. untracked,
  3509. "Top-level file 'sample.txt' should be in untracked list",
  3510. )
  3511. # Test via status
  3512. status = porcelain.status(self.repo)
  3513. self.assertIn(
  3514. "sample.txt",
  3515. status.untracked,
  3516. "Top-level file 'sample.txt' should be in status.untracked",
  3517. )
  3518. # TODO(jelmer): Add test for dulwich.porcelain.daemon
  3519. class UploadPackTests(PorcelainTestCase):
  3520. """Tests for upload_pack."""
  3521. def test_upload_pack(self) -> None:
  3522. outf = BytesIO()
  3523. exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf)
  3524. outlines = outf.getvalue().splitlines()
  3525. self.assertEqual([b"0000"], outlines)
  3526. self.assertEqual(0, exitcode)
  3527. class ReceivePackTests(PorcelainTestCase):
  3528. """Tests for receive_pack."""
  3529. def test_receive_pack(self) -> None:
  3530. filename = "foo"
  3531. fullpath = os.path.join(self.repo.path, filename)
  3532. with open(fullpath, "w") as f:
  3533. f.write("stuff")
  3534. porcelain.add(repo=self.repo.path, paths=fullpath)
  3535. self.repo.do_commit(
  3536. message=b"test status",
  3537. author=b"author <email>",
  3538. committer=b"committer <email>",
  3539. author_timestamp=1402354300,
  3540. commit_timestamp=1402354300,
  3541. author_timezone=0,
  3542. commit_timezone=0,
  3543. )
  3544. outf = BytesIO()
  3545. exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf)
  3546. outlines = outf.getvalue().splitlines()
  3547. self.assertEqual(
  3548. [
  3549. b"0091319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status "
  3550. b"delete-refs quiet ofs-delta side-band-64k "
  3551. b"no-done symref=HEAD:refs/heads/master",
  3552. b"003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master",
  3553. b"0000",
  3554. ],
  3555. outlines,
  3556. )
  3557. self.assertEqual(0, exitcode)
  3558. class BranchListTests(PorcelainTestCase):
  3559. def test_standard(self) -> None:
  3560. self.assertEqual(set(), set(porcelain.branch_list(self.repo)))
  3561. def test_new_branch(self) -> None:
  3562. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3563. self.repo[b"HEAD"] = c1.id
  3564. porcelain.branch_create(self.repo, b"foo")
  3565. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  3566. class BranchCreateTests(PorcelainTestCase):
  3567. def test_branch_exists(self) -> None:
  3568. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3569. self.repo[b"HEAD"] = c1.id
  3570. porcelain.branch_create(self.repo, b"foo")
  3571. self.assertRaises(porcelain.Error, porcelain.branch_create, self.repo, b"foo")
  3572. porcelain.branch_create(self.repo, b"foo", force=True)
  3573. def test_new_branch(self) -> None:
  3574. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3575. self.repo[b"HEAD"] = c1.id
  3576. porcelain.branch_create(self.repo, b"foo")
  3577. self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo)))
  3578. class BranchDeleteTests(PorcelainTestCase):
  3579. def test_simple(self) -> None:
  3580. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3581. self.repo[b"HEAD"] = c1.id
  3582. porcelain.branch_create(self.repo, b"foo")
  3583. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  3584. porcelain.branch_delete(self.repo, b"foo")
  3585. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  3586. def test_simple_unicode(self) -> None:
  3587. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3588. self.repo[b"HEAD"] = c1.id
  3589. porcelain.branch_create(self.repo, "foo")
  3590. self.assertIn(b"foo", porcelain.branch_list(self.repo))
  3591. porcelain.branch_delete(self.repo, "foo")
  3592. self.assertNotIn(b"foo", porcelain.branch_list(self.repo))
  3593. class FetchTests(PorcelainTestCase):
  3594. def test_simple(self) -> None:
  3595. outstream = BytesIO()
  3596. errstream = BytesIO()
  3597. # create a file for initial commit
  3598. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3599. os.close(handle)
  3600. porcelain.add(repo=self.repo.path, paths=fullpath)
  3601. porcelain.commit(
  3602. repo=self.repo.path,
  3603. message=b"test",
  3604. author=b"test <email>",
  3605. committer=b"test <email>",
  3606. )
  3607. # Setup target repo
  3608. target_path = tempfile.mkdtemp()
  3609. self.addCleanup(shutil.rmtree, target_path)
  3610. target_repo = porcelain.clone(
  3611. self.repo.path, target=target_path, errstream=errstream
  3612. )
  3613. # create a second file to be pushed
  3614. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3615. os.close(handle)
  3616. porcelain.add(repo=self.repo.path, paths=fullpath)
  3617. porcelain.commit(
  3618. repo=self.repo.path,
  3619. message=b"test2",
  3620. author=b"test2 <email>",
  3621. committer=b"test2 <email>",
  3622. )
  3623. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  3624. target_repo.close()
  3625. # Fetch changes into the cloned repo
  3626. porcelain.fetch(target_path, "origin", outstream=outstream, errstream=errstream)
  3627. # Assert that fetch updated the local image of the remote
  3628. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  3629. # Check the target repo for pushed changes
  3630. with Repo(target_path) as r:
  3631. self.assertIn(self.repo[b"HEAD"].id, r)
  3632. def test_with_remote_name(self) -> None:
  3633. remote_name = "origin"
  3634. outstream = BytesIO()
  3635. errstream = BytesIO()
  3636. # create a file for initial commit
  3637. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3638. os.close(handle)
  3639. porcelain.add(repo=self.repo.path, paths=fullpath)
  3640. porcelain.commit(
  3641. repo=self.repo.path,
  3642. message=b"test",
  3643. author=b"test <email>",
  3644. committer=b"test <email>",
  3645. )
  3646. # Setup target repo
  3647. target_path = tempfile.mkdtemp()
  3648. self.addCleanup(shutil.rmtree, target_path)
  3649. target_repo = porcelain.clone(
  3650. self.repo.path, target=target_path, errstream=errstream
  3651. )
  3652. # Capture current refs
  3653. target_refs = target_repo.get_refs()
  3654. # create a second file to be pushed
  3655. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3656. os.close(handle)
  3657. porcelain.add(repo=self.repo.path, paths=fullpath)
  3658. porcelain.commit(
  3659. repo=self.repo.path,
  3660. message=b"test2",
  3661. author=b"test2 <email>",
  3662. committer=b"test2 <email>",
  3663. )
  3664. self.assertNotIn(self.repo[b"HEAD"].id, target_repo)
  3665. target_config = target_repo.get_config()
  3666. target_config.set(
  3667. (b"remote", remote_name.encode()), b"url", self.repo.path.encode()
  3668. )
  3669. target_repo.close()
  3670. # Fetch changes into the cloned repo
  3671. porcelain.fetch(
  3672. target_path, remote_name, outstream=outstream, errstream=errstream
  3673. )
  3674. # Assert that fetch updated the local image of the remote
  3675. self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs())
  3676. # Check the target repo for pushed changes, as well as updates
  3677. # for the refs
  3678. with Repo(target_path) as r:
  3679. self.assertIn(self.repo[b"HEAD"].id, r)
  3680. self.assertNotEqual(self.repo.get_refs(), target_refs)
  3681. def assert_correct_remote_refs(
  3682. self, local_refs, remote_refs, remote_name=b"origin"
  3683. ) -> None:
  3684. """Assert that known remote refs corresponds to actual remote refs."""
  3685. local_ref_prefix = b"refs/heads"
  3686. remote_ref_prefix = b"refs/remotes/" + remote_name
  3687. locally_known_remote_refs = {
  3688. k[len(remote_ref_prefix) + 1 :]: v
  3689. for k, v in local_refs.items()
  3690. if k.startswith(remote_ref_prefix)
  3691. }
  3692. normalized_remote_refs = {
  3693. k[len(local_ref_prefix) + 1 :]: v
  3694. for k, v in remote_refs.items()
  3695. if k.startswith(local_ref_prefix)
  3696. }
  3697. if b"HEAD" in locally_known_remote_refs and b"HEAD" in remote_refs:
  3698. normalized_remote_refs[b"HEAD"] = remote_refs[b"HEAD"]
  3699. self.assertEqual(locally_known_remote_refs, normalized_remote_refs)
  3700. class RepackTests(PorcelainTestCase):
  3701. def test_empty(self) -> None:
  3702. porcelain.repack(self.repo)
  3703. def test_simple(self) -> None:
  3704. handle, fullpath = tempfile.mkstemp(dir=self.repo.path)
  3705. os.close(handle)
  3706. porcelain.add(repo=self.repo.path, paths=fullpath)
  3707. porcelain.repack(self.repo)
  3708. class LsTreeTests(PorcelainTestCase):
  3709. def test_empty(self) -> None:
  3710. porcelain.commit(
  3711. repo=self.repo.path,
  3712. message=b"test status",
  3713. author=b"author <email>",
  3714. committer=b"committer <email>",
  3715. )
  3716. f = StringIO()
  3717. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  3718. self.assertEqual(f.getvalue(), "")
  3719. def test_simple(self) -> None:
  3720. # Commit a dummy file then modify it
  3721. fullpath = os.path.join(self.repo.path, "foo")
  3722. with open(fullpath, "w") as f:
  3723. f.write("origstuff")
  3724. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3725. porcelain.commit(
  3726. repo=self.repo.path,
  3727. message=b"test status",
  3728. author=b"author <email>",
  3729. committer=b"committer <email>",
  3730. )
  3731. f = StringIO()
  3732. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  3733. self.assertEqual(
  3734. f.getvalue(),
  3735. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n",
  3736. )
  3737. def test_recursive(self) -> None:
  3738. # Create a directory then write a dummy file in it
  3739. dirpath = os.path.join(self.repo.path, "adir")
  3740. filepath = os.path.join(dirpath, "afile")
  3741. os.mkdir(dirpath)
  3742. with open(filepath, "w") as f:
  3743. f.write("origstuff")
  3744. porcelain.add(repo=self.repo.path, paths=[filepath])
  3745. porcelain.commit(
  3746. repo=self.repo.path,
  3747. message=b"test status",
  3748. author=b"author <email>",
  3749. committer=b"committer <email>",
  3750. )
  3751. f = StringIO()
  3752. porcelain.ls_tree(self.repo, b"HEAD", outstream=f)
  3753. self.assertEqual(
  3754. f.getvalue(),
  3755. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n",
  3756. )
  3757. f = StringIO()
  3758. porcelain.ls_tree(self.repo, b"HEAD", outstream=f, recursive=True)
  3759. self.assertEqual(
  3760. f.getvalue(),
  3761. "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n"
  3762. "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir"
  3763. "/afile\n",
  3764. )
  3765. class LsRemoteTests(PorcelainTestCase):
  3766. def test_empty(self) -> None:
  3767. result = porcelain.ls_remote(self.repo.path)
  3768. self.assertEqual({}, result.refs)
  3769. self.assertEqual({}, result.symrefs)
  3770. def test_some(self) -> None:
  3771. cid = porcelain.commit(
  3772. repo=self.repo.path,
  3773. message=b"test status",
  3774. author=b"author <email>",
  3775. committer=b"committer <email>",
  3776. )
  3777. result = porcelain.ls_remote(self.repo.path)
  3778. self.assertEqual(
  3779. {b"refs/heads/master": cid, b"HEAD": cid},
  3780. result.refs,
  3781. )
  3782. # HEAD should be a symref to refs/heads/master
  3783. self.assertEqual({b"HEAD": b"refs/heads/master"}, result.symrefs)
  3784. class LsFilesTests(PorcelainTestCase):
  3785. def test_empty(self) -> None:
  3786. self.assertEqual([], list(porcelain.ls_files(self.repo)))
  3787. def test_simple(self) -> None:
  3788. # Commit a dummy file then modify it
  3789. fullpath = os.path.join(self.repo.path, "foo")
  3790. with open(fullpath, "w") as f:
  3791. f.write("origstuff")
  3792. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3793. self.assertEqual([b"foo"], list(porcelain.ls_files(self.repo)))
  3794. class RemoteAddTests(PorcelainTestCase):
  3795. def test_new(self) -> None:
  3796. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  3797. c = self.repo.get_config()
  3798. self.assertEqual(
  3799. c.get((b"remote", b"jelmer"), b"url"),
  3800. b"git://jelmer.uk/code/dulwich",
  3801. )
  3802. def test_exists(self) -> None:
  3803. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  3804. self.assertRaises(
  3805. porcelain.RemoteExists,
  3806. porcelain.remote_add,
  3807. self.repo,
  3808. "jelmer",
  3809. "git://jelmer.uk/code/dulwich",
  3810. )
  3811. class RemoteRemoveTests(PorcelainTestCase):
  3812. def test_remove(self) -> None:
  3813. porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich")
  3814. c = self.repo.get_config()
  3815. self.assertEqual(
  3816. c.get((b"remote", b"jelmer"), b"url"),
  3817. b"git://jelmer.uk/code/dulwich",
  3818. )
  3819. porcelain.remote_remove(self.repo, "jelmer")
  3820. self.assertRaises(KeyError, porcelain.remote_remove, self.repo, "jelmer")
  3821. c = self.repo.get_config()
  3822. self.assertRaises(KeyError, c.get, (b"remote", b"jelmer"), b"url")
  3823. class CheckIgnoreTests(PorcelainTestCase):
  3824. def test_check_ignored(self) -> None:
  3825. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3826. f.write("foo")
  3827. foo_path = os.path.join(self.repo.path, "foo")
  3828. with open(foo_path, "w") as f:
  3829. f.write("BAR")
  3830. bar_path = os.path.join(self.repo.path, "bar")
  3831. with open(bar_path, "w") as f:
  3832. f.write("BAR")
  3833. self.assertEqual(["foo"], list(porcelain.check_ignore(self.repo, [foo_path])))
  3834. self.assertEqual([], list(porcelain.check_ignore(self.repo, [bar_path])))
  3835. def test_check_added_abs(self) -> None:
  3836. path = os.path.join(self.repo.path, "foo")
  3837. with open(path, "w") as f:
  3838. f.write("BAR")
  3839. self.repo.stage(["foo"])
  3840. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3841. f.write("foo\n")
  3842. self.assertEqual([], list(porcelain.check_ignore(self.repo, [path])))
  3843. self.assertEqual(
  3844. ["foo"],
  3845. list(porcelain.check_ignore(self.repo, [path], no_index=True)),
  3846. )
  3847. def test_check_added_rel(self) -> None:
  3848. with open(os.path.join(self.repo.path, "foo"), "w") as f:
  3849. f.write("BAR")
  3850. self.repo.stage(["foo"])
  3851. with open(os.path.join(self.repo.path, ".gitignore"), "w") as f:
  3852. f.write("foo\n")
  3853. cwd = os.getcwd()
  3854. os.mkdir(os.path.join(self.repo.path, "bar"))
  3855. os.chdir(os.path.join(self.repo.path, "bar"))
  3856. try:
  3857. self.assertEqual(list(porcelain.check_ignore(self.repo, ["../foo"])), [])
  3858. self.assertEqual(
  3859. ["../foo"],
  3860. list(porcelain.check_ignore(self.repo, ["../foo"], no_index=True)),
  3861. )
  3862. finally:
  3863. os.chdir(cwd)
  3864. class UpdateHeadTests(PorcelainTestCase):
  3865. def test_set_to_branch(self) -> None:
  3866. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3867. self.repo.refs[b"refs/heads/blah"] = c1.id
  3868. porcelain.update_head(self.repo, "blah")
  3869. self.assertEqual(c1.id, self.repo.head())
  3870. self.assertEqual(b"ref: refs/heads/blah", self.repo.refs.read_ref(b"HEAD"))
  3871. def test_set_to_branch_detached(self) -> None:
  3872. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3873. self.repo.refs[b"refs/heads/blah"] = c1.id
  3874. porcelain.update_head(self.repo, "blah", detached=True)
  3875. self.assertEqual(c1.id, self.repo.head())
  3876. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  3877. def test_set_to_commit_detached(self) -> None:
  3878. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3879. self.repo.refs[b"refs/heads/blah"] = c1.id
  3880. porcelain.update_head(self.repo, c1.id, detached=True)
  3881. self.assertEqual(c1.id, self.repo.head())
  3882. self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD"))
  3883. def test_set_new_branch(self) -> None:
  3884. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3885. self.repo.refs[b"refs/heads/blah"] = c1.id
  3886. porcelain.update_head(self.repo, "blah", new_branch="bar")
  3887. self.assertEqual(c1.id, self.repo.head())
  3888. self.assertEqual(b"ref: refs/heads/bar", self.repo.refs.read_ref(b"HEAD"))
  3889. class MailmapTests(PorcelainTestCase):
  3890. def test_no_mailmap(self) -> None:
  3891. self.assertEqual(
  3892. b"Jelmer Vernooij <jelmer@samba.org>",
  3893. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  3894. )
  3895. def test_mailmap_lookup(self) -> None:
  3896. with open(os.path.join(self.repo.path, ".mailmap"), "wb") as f:
  3897. f.write(
  3898. b"""\
  3899. Jelmer Vernooij <jelmer@debian.org>
  3900. """
  3901. )
  3902. self.assertEqual(
  3903. b"Jelmer Vernooij <jelmer@debian.org>",
  3904. porcelain.check_mailmap(self.repo, b"Jelmer Vernooij <jelmer@samba.org>"),
  3905. )
  3906. class FsckTests(PorcelainTestCase):
  3907. def test_none(self) -> None:
  3908. self.assertEqual([], list(porcelain.fsck(self.repo)))
  3909. def test_git_dir(self) -> None:
  3910. obj = Tree()
  3911. a = Blob()
  3912. a.data = b"foo"
  3913. obj.add(b".git", 0o100644, a.id)
  3914. self.repo.object_store.add_objects([(a, None), (obj, None)])
  3915. self.assertEqual(
  3916. [(obj.id, "invalid name .git")],
  3917. [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)],
  3918. )
  3919. class DescribeTests(PorcelainTestCase):
  3920. def test_no_commits(self) -> None:
  3921. self.assertRaises(KeyError, porcelain.describe, self.repo.path)
  3922. def test_single_commit(self) -> None:
  3923. fullpath = os.path.join(self.repo.path, "foo")
  3924. with open(fullpath, "w") as f:
  3925. f.write("BAR")
  3926. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3927. sha = porcelain.commit(
  3928. self.repo.path,
  3929. message=b"Some message",
  3930. author=b"Joe <joe@example.com>",
  3931. committer=b"Bob <bob@example.com>",
  3932. )
  3933. self.assertEqual(
  3934. "g{}".format(sha[:7].decode("ascii")),
  3935. porcelain.describe(self.repo.path),
  3936. )
  3937. def test_tag(self) -> None:
  3938. fullpath = os.path.join(self.repo.path, "foo")
  3939. with open(fullpath, "w") as f:
  3940. f.write("BAR")
  3941. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3942. porcelain.commit(
  3943. self.repo.path,
  3944. message=b"Some message",
  3945. author=b"Joe <joe@example.com>",
  3946. committer=b"Bob <bob@example.com>",
  3947. )
  3948. porcelain.tag_create(
  3949. self.repo.path,
  3950. b"tryme",
  3951. b"foo <foo@bar.com>",
  3952. b"bar",
  3953. annotated=True,
  3954. )
  3955. self.assertEqual("tryme", porcelain.describe(self.repo.path))
  3956. def test_tag_and_commit(self) -> None:
  3957. fullpath = os.path.join(self.repo.path, "foo")
  3958. with open(fullpath, "w") as f:
  3959. f.write("BAR")
  3960. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3961. porcelain.commit(
  3962. self.repo.path,
  3963. message=b"Some message",
  3964. author=b"Joe <joe@example.com>",
  3965. committer=b"Bob <bob@example.com>",
  3966. )
  3967. porcelain.tag_create(
  3968. self.repo.path,
  3969. b"tryme",
  3970. b"foo <foo@bar.com>",
  3971. b"bar",
  3972. annotated=True,
  3973. )
  3974. with open(fullpath, "w") as f:
  3975. f.write("BAR2")
  3976. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3977. sha = porcelain.commit(
  3978. self.repo.path,
  3979. message=b"Some message",
  3980. author=b"Joe <joe@example.com>",
  3981. committer=b"Bob <bob@example.com>",
  3982. )
  3983. self.assertEqual(
  3984. "tryme-1-g{}".format(sha[:7].decode("ascii")),
  3985. porcelain.describe(self.repo.path),
  3986. )
  3987. def test_tag_and_commit_full(self) -> None:
  3988. fullpath = os.path.join(self.repo.path, "foo")
  3989. with open(fullpath, "w") as f:
  3990. f.write("BAR")
  3991. porcelain.add(repo=self.repo.path, paths=[fullpath])
  3992. porcelain.commit(
  3993. self.repo.path,
  3994. message=b"Some message",
  3995. author=b"Joe <joe@example.com>",
  3996. committer=b"Bob <bob@example.com>",
  3997. )
  3998. porcelain.tag_create(
  3999. self.repo.path,
  4000. b"tryme",
  4001. b"foo <foo@bar.com>",
  4002. b"bar",
  4003. annotated=True,
  4004. )
  4005. with open(fullpath, "w") as f:
  4006. f.write("BAR2")
  4007. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4008. sha = porcelain.commit(
  4009. self.repo.path,
  4010. message=b"Some message",
  4011. author=b"Joe <joe@example.com>",
  4012. committer=b"Bob <bob@example.com>",
  4013. )
  4014. self.assertEqual(
  4015. "tryme-1-g{}".format(sha.decode("ascii")),
  4016. porcelain.describe(self.repo.path, abbrev=40),
  4017. )
  4018. def test_untagged_commit_abbreviation(self) -> None:
  4019. _, _, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]])
  4020. self.repo.refs[b"HEAD"] = c3.id
  4021. brief_description, complete_description = (
  4022. porcelain.describe(self.repo),
  4023. porcelain.describe(self.repo, abbrev=40),
  4024. )
  4025. self.assertTrue(complete_description.startswith(brief_description))
  4026. self.assertEqual(
  4027. "g{}".format(c3.id.decode("ascii")),
  4028. complete_description,
  4029. )
  4030. class PathToTreeTests(PorcelainTestCase):
  4031. def setUp(self) -> None:
  4032. super().setUp()
  4033. self.fp = os.path.join(self.test_dir, "bar")
  4034. with open(self.fp, "w") as f:
  4035. f.write("something")
  4036. oldcwd = os.getcwd()
  4037. self.addCleanup(os.chdir, oldcwd)
  4038. os.chdir(self.test_dir)
  4039. def test_path_to_tree_path_base(self) -> None:
  4040. self.assertEqual(b"bar", porcelain.path_to_tree_path(self.test_dir, self.fp))
  4041. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  4042. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "bar"))
  4043. cwd = os.getcwd()
  4044. self.assertEqual(
  4045. b"bar", porcelain.path_to_tree_path(".", os.path.join(cwd, "bar"))
  4046. )
  4047. self.assertEqual(b"bar", porcelain.path_to_tree_path(cwd, "bar"))
  4048. def test_path_to_tree_path_syntax(self) -> None:
  4049. self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar"))
  4050. def test_path_to_tree_path_error(self) -> None:
  4051. with self.assertRaises(ValueError):
  4052. with tempfile.TemporaryDirectory() as od:
  4053. porcelain.path_to_tree_path(od, self.fp)
  4054. def test_path_to_tree_path_rel(self) -> None:
  4055. cwd = os.getcwd()
  4056. os.mkdir(os.path.join(self.repo.path, "foo"))
  4057. os.mkdir(os.path.join(self.repo.path, "foo/bar"))
  4058. try:
  4059. os.chdir(os.path.join(self.repo.path, "foo/bar"))
  4060. with open("baz", "w") as f:
  4061. f.write("contents")
  4062. self.assertEqual(b"bar/baz", porcelain.path_to_tree_path("..", "baz"))
  4063. self.assertEqual(
  4064. b"bar/baz",
  4065. porcelain.path_to_tree_path(
  4066. os.path.join(os.getcwd(), ".."),
  4067. os.path.join(os.getcwd(), "baz"),
  4068. ),
  4069. )
  4070. self.assertEqual(
  4071. b"bar/baz",
  4072. porcelain.path_to_tree_path("..", os.path.join(os.getcwd(), "baz")),
  4073. )
  4074. self.assertEqual(
  4075. b"bar/baz",
  4076. porcelain.path_to_tree_path(os.path.join(os.getcwd(), ".."), "baz"),
  4077. )
  4078. finally:
  4079. os.chdir(cwd)
  4080. class GetObjectByPathTests(PorcelainTestCase):
  4081. def test_simple(self) -> None:
  4082. fullpath = os.path.join(self.repo.path, "foo")
  4083. with open(fullpath, "w") as f:
  4084. f.write("BAR")
  4085. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4086. porcelain.commit(
  4087. self.repo.path,
  4088. message=b"Some message",
  4089. author=b"Joe <joe@example.com>",
  4090. committer=b"Bob <bob@example.com>",
  4091. )
  4092. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  4093. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  4094. def test_encoding(self) -> None:
  4095. fullpath = os.path.join(self.repo.path, "foo")
  4096. with open(fullpath, "w") as f:
  4097. f.write("BAR")
  4098. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4099. porcelain.commit(
  4100. self.repo.path,
  4101. message=b"Some message",
  4102. author=b"Joe <joe@example.com>",
  4103. committer=b"Bob <bob@example.com>",
  4104. encoding=b"utf-8",
  4105. )
  4106. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data)
  4107. self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data)
  4108. def test_missing(self) -> None:
  4109. self.assertRaises(KeyError, porcelain.get_object_by_path, self.repo, "foo")
  4110. class WriteTreeTests(PorcelainTestCase):
  4111. def test_simple(self) -> None:
  4112. fullpath = os.path.join(self.repo.path, "foo")
  4113. with open(fullpath, "w") as f:
  4114. f.write("BAR")
  4115. porcelain.add(repo=self.repo.path, paths=[fullpath])
  4116. self.assertEqual(
  4117. b"d2092c8a9f311f0311083bf8d177f2ca0ab5b241",
  4118. porcelain.write_tree(self.repo),
  4119. )
  4120. class ActiveBranchTests(PorcelainTestCase):
  4121. def test_simple(self) -> None:
  4122. self.assertEqual(b"master", porcelain.active_branch(self.repo))
  4123. class FindUniqueAbbrevTests(PorcelainTestCase):
  4124. def test_simple(self) -> None:
  4125. c1, c2, c3 = build_commit_graph(
  4126. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  4127. )
  4128. self.repo.refs[b"HEAD"] = c3.id
  4129. self.assertEqual(
  4130. c1.id.decode("ascii")[:7],
  4131. porcelain.find_unique_abbrev(self.repo.object_store, c1.id),
  4132. )
  4133. class PackRefsTests(PorcelainTestCase):
  4134. def test_all(self) -> None:
  4135. c1, c2, c3 = build_commit_graph(
  4136. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  4137. )
  4138. self.repo.refs[b"HEAD"] = c3.id
  4139. self.repo.refs[b"refs/heads/master"] = c2.id
  4140. self.repo.refs[b"refs/tags/foo"] = c1.id
  4141. porcelain.pack_refs(self.repo, all=True)
  4142. self.assertEqual(
  4143. self.repo.refs.get_packed_refs(),
  4144. {
  4145. b"refs/heads/master": c2.id,
  4146. b"refs/tags/foo": c1.id,
  4147. },
  4148. )
  4149. def test_not_all(self) -> None:
  4150. c1, c2, c3 = build_commit_graph(
  4151. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  4152. )
  4153. self.repo.refs[b"HEAD"] = c3.id
  4154. self.repo.refs[b"refs/heads/master"] = c2.id
  4155. self.repo.refs[b"refs/tags/foo"] = c1.id
  4156. porcelain.pack_refs(self.repo)
  4157. self.assertEqual(
  4158. self.repo.refs.get_packed_refs(),
  4159. {
  4160. b"refs/tags/foo": c1.id,
  4161. },
  4162. )
  4163. class ServerTests(PorcelainTestCase):
  4164. @contextlib.contextmanager
  4165. def _serving(self):
  4166. with make_server("localhost", 0, self.app) as server:
  4167. thread = threading.Thread(target=server.serve_forever, daemon=True)
  4168. thread.start()
  4169. try:
  4170. yield f"http://localhost:{server.server_port}"
  4171. finally:
  4172. server.shutdown()
  4173. thread.join(10)
  4174. def setUp(self) -> None:
  4175. super().setUp()
  4176. self.served_repo_path = os.path.join(self.test_dir, "served_repo.git")
  4177. self.served_repo = Repo.init_bare(self.served_repo_path, mkdir=True)
  4178. self.addCleanup(self.served_repo.close)
  4179. backend = DictBackend({"/": self.served_repo})
  4180. self.app = make_wsgi_chain(backend)
  4181. def test_pull(self) -> None:
  4182. (c1,) = build_commit_graph(self.served_repo.object_store, [[1]])
  4183. self.served_repo.refs[b"refs/heads/master"] = c1.id
  4184. with self._serving() as url:
  4185. porcelain.pull(self.repo, url, "master")
  4186. def test_push(self) -> None:
  4187. (c1,) = build_commit_graph(self.repo.object_store, [[1]])
  4188. self.repo.refs[b"refs/heads/master"] = c1.id
  4189. with self._serving() as url:
  4190. porcelain.push(self.repo, url, "master")
  4191. class ForEachTests(PorcelainTestCase):
  4192. def setUp(self) -> None:
  4193. super().setUp()
  4194. c1, c2, c3, c4 = build_commit_graph(
  4195. self.repo.object_store, [[1], [2, 1], [3, 1, 2], [4]]
  4196. )
  4197. porcelain.tag_create(
  4198. self.repo.path,
  4199. b"v0.1",
  4200. objectish=c1.id,
  4201. annotated=True,
  4202. message=b"0.1",
  4203. )
  4204. porcelain.tag_create(
  4205. self.repo.path,
  4206. b"v1.0",
  4207. objectish=c2.id,
  4208. annotated=True,
  4209. message=b"1.0",
  4210. )
  4211. porcelain.tag_create(self.repo.path, b"simple-tag", objectish=c3.id)
  4212. porcelain.tag_create(
  4213. self.repo.path,
  4214. b"v1.1",
  4215. objectish=c4.id,
  4216. annotated=True,
  4217. message=b"1.1",
  4218. )
  4219. porcelain.branch_create(
  4220. self.repo.path, b"feat", objectish=c2.id.decode("ascii")
  4221. )
  4222. self.repo.refs[b"HEAD"] = c4.id
  4223. def test_for_each_ref(self) -> None:
  4224. refs = porcelain.for_each_ref(self.repo)
  4225. self.assertEqual(
  4226. [(object_type, tag) for _, object_type, tag in refs],
  4227. [
  4228. (b"commit", b"refs/heads/feat"),
  4229. (b"commit", b"refs/heads/master"),
  4230. (b"commit", b"refs/tags/simple-tag"),
  4231. (b"tag", b"refs/tags/v0.1"),
  4232. (b"tag", b"refs/tags/v1.0"),
  4233. (b"tag", b"refs/tags/v1.1"),
  4234. ],
  4235. )
  4236. def test_for_each_ref_pattern(self) -> None:
  4237. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v*")
  4238. self.assertEqual(
  4239. [(object_type, tag) for _, object_type, tag in versions],
  4240. [
  4241. (b"tag", b"refs/tags/v0.1"),
  4242. (b"tag", b"refs/tags/v1.0"),
  4243. (b"tag", b"refs/tags/v1.1"),
  4244. ],
  4245. )
  4246. versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v1.?")
  4247. self.assertEqual(
  4248. [(object_type, tag) for _, object_type, tag in versions],
  4249. [
  4250. (b"tag", b"refs/tags/v1.0"),
  4251. (b"tag", b"refs/tags/v1.1"),
  4252. ],
  4253. )
  4254. class SparseCheckoutTests(PorcelainTestCase):
  4255. """Integration tests for Dulwich's sparse checkout feature."""
  4256. # NOTE: We do NOT override `setUp()` here because the parent class
  4257. # (PorcelainTestCase) already:
  4258. # 1) Creates self.test_dir = a unique temp dir
  4259. # 2) Creates a subdir named "repo"
  4260. # 3) Calls Repo.init() on that path
  4261. # Re-initializing again caused FileExistsError.
  4262. #
  4263. # Utility/Placeholder
  4264. #
  4265. def sparse_checkout(self, repo, patterns, force=False):
  4266. """Wrapper around the actual porcelain.sparse_checkout function
  4267. to handle any test-specific setup or logging.
  4268. """
  4269. return porcelain.sparse_checkout(repo, patterns, force=force)
  4270. def _write_file(self, rel_path, content):
  4271. """Helper to write a file in the repository working tree."""
  4272. abs_path = os.path.join(self.repo_path, rel_path)
  4273. os.makedirs(os.path.dirname(abs_path), exist_ok=True)
  4274. with open(abs_path, "w") as f:
  4275. f.write(content)
  4276. return abs_path
  4277. def _commit_file(self, rel_path, content):
  4278. """Helper to write, add, and commit a file."""
  4279. abs_path = self._write_file(rel_path, content)
  4280. add(self.repo_path, paths=[abs_path])
  4281. commit(self.repo_path, message=b"Added " + rel_path.encode("utf-8"))
  4282. def _list_wtree_files(self):
  4283. """Return a set of all files (not dirs) present
  4284. in the working tree, ignoring .git/.
  4285. """
  4286. found_files = set()
  4287. for root, dirs, files in os.walk(self.repo_path):
  4288. # Skip .git in the walk
  4289. if ".git" in dirs:
  4290. dirs.remove(".git")
  4291. for filename in files:
  4292. file_rel = os.path.relpath(os.path.join(root, filename), self.repo_path)
  4293. found_files.add(file_rel)
  4294. return found_files
  4295. def test_only_included_paths_appear_in_wtree(self):
  4296. """Only included paths remain in the working tree, excluded paths are removed.
  4297. Commits two files, "keep_me.txt" and "exclude_me.txt". Then applies a
  4298. sparse-checkout pattern containing only "keep_me.txt". Ensures that
  4299. the latter remains in the working tree, while "exclude_me.txt" is
  4300. removed. This verifies correct application of sparse-checkout patterns
  4301. to remove files not listed.
  4302. """
  4303. self._commit_file("keep_me.txt", "I'll stay\n")
  4304. self._commit_file("exclude_me.txt", "I'll be excluded\n")
  4305. patterns = ["keep_me.txt"]
  4306. self.sparse_checkout(self.repo, patterns)
  4307. actual_files = self._list_wtree_files()
  4308. expected_files = {"keep_me.txt"}
  4309. self.assertEqual(
  4310. expected_files,
  4311. actual_files,
  4312. f"Expected only {expected_files}, but found {actual_files}",
  4313. )
  4314. def test_previously_included_paths_become_excluded(self):
  4315. """Previously included files become excluded after pattern changes.
  4316. Verifies that files initially brought into the working tree (e.g.,
  4317. by including `data/`) can later be excluded by narrowing the
  4318. sparse-checkout pattern to just `data/included_1.txt`. Confirms that
  4319. the file `data/included_2.txt` remains in the index with
  4320. skip-worktree set (rather than being removed entirely), ensuring
  4321. data is not lost and Dulwich correctly updates the index flags.
  4322. """
  4323. self._commit_file("data/included_1.txt", "some content\n")
  4324. self._commit_file("data/included_2.txt", "other content\n")
  4325. initial_patterns = ["data/"]
  4326. self.sparse_checkout(self.repo, initial_patterns)
  4327. updated_patterns = ["data/included_1.txt"]
  4328. self.sparse_checkout(self.repo, updated_patterns)
  4329. actual_files = self._list_wtree_files()
  4330. expected_files = {os.path.join("data", "included_1.txt")}
  4331. self.assertEqual(expected_files, actual_files)
  4332. idx = self.repo.open_index()
  4333. self.assertIn(b"data/included_2.txt", idx)
  4334. entry = idx[b"data/included_2.txt"]
  4335. self.assertTrue(entry.skip_worktree)
  4336. def test_force_removes_local_changes_for_excluded_paths(self):
  4337. """Forced sparse checkout removes local modifications for newly excluded paths.
  4338. Verifies that specifying force=True allows destructive operations
  4339. which discard uncommitted changes. First, we commit "file1.txt" and
  4340. then modify it. Next, we apply a pattern that excludes the file,
  4341. using force=True. The local modifications (and the file) should
  4342. be removed, leaving the working tree empty.
  4343. """
  4344. self._commit_file("file1.txt", "original content\n")
  4345. file1_path = os.path.join(self.repo_path, "file1.txt")
  4346. with open(file1_path, "a") as f:
  4347. f.write("local changes!\n")
  4348. new_patterns = ["some_other_file.txt"]
  4349. self.sparse_checkout(self.repo, new_patterns, force=True)
  4350. actual_files = self._list_wtree_files()
  4351. self.assertEqual(
  4352. set(),
  4353. actual_files,
  4354. "Force-sparse-checkout did not remove file with local changes.",
  4355. )
  4356. def test_destructive_refuse_uncommitted_changes_without_force(self):
  4357. """Fail on uncommitted changes for newly excluded paths without force.
  4358. Ensures that a sparse checkout is blocked if it would remove local
  4359. modifications from the working tree. We commit 'config.yaml', then
  4360. modify it, and finally attempt to exclude it via new patterns without
  4361. using force=True. This should raise a CheckoutError rather than
  4362. discarding the local changes.
  4363. """
  4364. self._commit_file("config.yaml", "initial\n")
  4365. cfg_path = os.path.join(self.repo_path, "config.yaml")
  4366. with open(cfg_path, "a") as f:
  4367. f.write("local modifications\n")
  4368. exclude_patterns = ["docs/"]
  4369. with self.assertRaises(CheckoutError):
  4370. self.sparse_checkout(self.repo, exclude_patterns, force=False)
  4371. def test_fnmatch_gitignore_pattern_expansion(self):
  4372. """Reading/writing patterns align with gitignore/fnmatch expansions.
  4373. Ensures that `sparse_checkout` interprets wildcard patterns (like `*.py`)
  4374. in the same way Git's sparse-checkout would. Multiple files are committed
  4375. to `src/` (e.g. `foo.py`, `foo_test.py`, `foo_helper.py`) and to `docs/`.
  4376. Then the pattern `src/foo*.py` is applied, confirming that only the
  4377. matching Python files remain in the working tree while the Markdown file
  4378. under `docs/` is excluded.
  4379. Finally, verifies that the `.git/info/sparse-checkout` file contains the
  4380. specified wildcard pattern (`src/foo*.py`), ensuring correct round-trip
  4381. of user-supplied patterns.
  4382. """
  4383. self._commit_file("src/foo.py", "print('hello')\n")
  4384. self._commit_file("src/foo_test.py", "print('test')\n")
  4385. self._commit_file("docs/readme.md", "# docs\n")
  4386. self._commit_file("src/foo_helper.py", "print('helper')\n")
  4387. patterns = ["src/foo*.py"]
  4388. self.sparse_checkout(self.repo, patterns)
  4389. actual_files = self._list_wtree_files()
  4390. expected_files = {
  4391. os.path.join("src", "foo.py"),
  4392. os.path.join("src", "foo_test.py"),
  4393. os.path.join("src", "foo_helper.py"),
  4394. }
  4395. self.assertEqual(
  4396. expected_files,
  4397. actual_files,
  4398. "Wildcard pattern not matched as expected. Either too strict or too broad.",
  4399. )
  4400. sc_file = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  4401. self.assertTrue(os.path.isfile(sc_file))
  4402. with open(sc_file) as f:
  4403. lines = f.read().strip().split()
  4404. self.assertIn("src/foo*.py", lines)
  4405. class ConeModeTests(PorcelainTestCase):
  4406. """Provide integration tests for Dulwich's cone mode sparse checkout.
  4407. This test suite verifies the expected behavior for:
  4408. * cone_mode_init
  4409. * cone_mode_set
  4410. * cone_mode_add
  4411. Although Dulwich does not yet implement cone mode, these tests are
  4412. prepared in advance to guide future development.
  4413. """
  4414. def setUp(self):
  4415. """Set up a fresh repository for each test.
  4416. This method creates a new empty repo_path and Repo object
  4417. as provided by the PorcelainTestCase base class.
  4418. """
  4419. super().setUp()
  4420. def _commit_file(self, rel_path, content=b"contents"):
  4421. """Add a file at the given relative path and commit it.
  4422. Creates necessary directories, writes the file content,
  4423. stages, and commits. The commit message and author/committer
  4424. are also provided.
  4425. """
  4426. full_path = os.path.join(self.repo_path, rel_path)
  4427. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  4428. with open(full_path, "wb") as f:
  4429. f.write(content)
  4430. porcelain.add(self.repo_path, paths=[full_path])
  4431. porcelain.commit(
  4432. self.repo_path,
  4433. message=b"Adding " + rel_path.encode("utf-8"),
  4434. author=b"Test Author <author@example.com>",
  4435. committer=b"Test Committer <committer@example.com>",
  4436. )
  4437. def _list_wtree_files(self):
  4438. """Return a set of all file paths relative to the repository root.
  4439. Walks the working tree, skipping the .git directory.
  4440. """
  4441. found_files = set()
  4442. for root, dirs, files in os.walk(self.repo_path):
  4443. if ".git" in dirs:
  4444. dirs.remove(".git")
  4445. for fn in files:
  4446. relp = os.path.relpath(os.path.join(root, fn), self.repo_path)
  4447. found_files.add(relp)
  4448. return found_files
  4449. def test_init_excludes_everything(self):
  4450. """Verify that cone_mode_init writes minimal patterns and empties the working tree.
  4451. Make some dummy files, commit them, then call cone_mode_init. Confirm
  4452. that the working tree is empty, the sparse-checkout file has the
  4453. minimal patterns (/*, !/*/), and the relevant config values are set.
  4454. """
  4455. self._commit_file("docs/readme.md", b"# doc\n")
  4456. self._commit_file("src/main.py", b"print('hello')\n")
  4457. porcelain.cone_mode_init(self.repo)
  4458. actual_files = self._list_wtree_files()
  4459. self.assertEqual(
  4460. set(),
  4461. actual_files,
  4462. "cone_mode_init did not exclude all files from the working tree.",
  4463. )
  4464. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  4465. with open(sp_path) as f:
  4466. lines = [ln.strip() for ln in f if ln.strip()]
  4467. self.assertIn("/*", lines)
  4468. self.assertIn("!/*/", lines)
  4469. config = self.repo.get_config()
  4470. self.assertEqual(config.get((b"core",), b"sparseCheckout"), b"true")
  4471. self.assertEqual(config.get((b"core",), b"sparseCheckoutCone"), b"true")
  4472. def test_set_specific_dirs(self):
  4473. """Verify that cone_mode_set overwrites the included directories to only the specified ones.
  4474. Initializes cone mode, commits some files, then calls cone_mode_set with
  4475. a list of directories. Expects that only those directories remain in the
  4476. working tree.
  4477. """
  4478. porcelain.cone_mode_init(self.repo)
  4479. self._commit_file("docs/readme.md", b"# doc\n")
  4480. self._commit_file("src/main.py", b"print('hello')\n")
  4481. self._commit_file("tests/test_foo.py", b"# tests\n")
  4482. # Everything is still excluded initially by init.
  4483. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  4484. actual_files = self._list_wtree_files()
  4485. expected_files = {
  4486. os.path.join("docs", "readme.md"),
  4487. os.path.join("src", "main.py"),
  4488. }
  4489. self.assertEqual(
  4490. expected_files,
  4491. actual_files,
  4492. "Did not see only the 'docs/' and 'src/' dirs in the working tree.",
  4493. )
  4494. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  4495. with open(sp_path) as f:
  4496. lines = [ln.strip() for ln in f if ln.strip()]
  4497. # For standard cone mode, we'd expect lines like:
  4498. # /* (include top-level files)
  4499. # !/*/ (exclude subdirectories)
  4500. # !/docs/ (re-include docs)
  4501. # !/src/ (re-include src)
  4502. # Instead of the wildcard-based lines the old test used.
  4503. self.assertIn("/*", lines)
  4504. self.assertIn("!/*/", lines)
  4505. self.assertIn("/docs/", lines)
  4506. self.assertIn("/src/", lines)
  4507. self.assertNotIn("/tests/", lines)
  4508. def test_set_overwrites_old_dirs(self):
  4509. """Ensure that calling cone_mode_set again overwrites old includes.
  4510. Initializes cone mode, includes two directories, then calls
  4511. cone_mode_set again with a different directory to confirm the
  4512. new set of includes replaces the old.
  4513. """
  4514. porcelain.cone_mode_init(self.repo)
  4515. self._commit_file("docs/readme.md")
  4516. self._commit_file("src/main.py")
  4517. self._commit_file("tests/test_bar.py")
  4518. porcelain.cone_mode_set(self.repo, dirs=["docs", "src"])
  4519. self.assertEqual(
  4520. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  4521. self._list_wtree_files(),
  4522. )
  4523. # Overwrite includes, now only 'tests'
  4524. porcelain.cone_mode_set(self.repo, dirs=["tests"], force=True)
  4525. actual_files = self._list_wtree_files()
  4526. expected_files = {os.path.join("tests", "test_bar.py")}
  4527. self.assertEqual(expected_files, actual_files)
  4528. def test_force_removal_of_local_mods(self):
  4529. """Confirm that force=True removes local changes in excluded paths.
  4530. cone_mode_init and cone_mode_set are called, a file is locally modified,
  4531. and then cone_mode_set is called again with force=True to exclude that path.
  4532. The excluded file should be removed with no CheckoutError.
  4533. """
  4534. porcelain.cone_mode_init(self.repo)
  4535. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  4536. self._commit_file("docs/readme.md", b"Docs stuff\n")
  4537. self._commit_file("src/main.py", b"print('hello')\n")
  4538. # Modify src/main.py
  4539. with open(os.path.join(self.repo_path, "src/main.py"), "ab") as f:
  4540. f.write(b"extra line\n")
  4541. # Exclude src/ with force=True
  4542. porcelain.cone_mode_set(self.repo, dirs=["docs"], force=True)
  4543. actual_files = self._list_wtree_files()
  4544. expected_files = {os.path.join("docs", "readme.md")}
  4545. self.assertEqual(expected_files, actual_files)
  4546. def test_add_and_merge_dirs(self):
  4547. """Verify that cone_mode_add merges new directories instead of overwriting them.
  4548. After initializing cone mode and including a single directory, call
  4549. cone_mode_add with a new directory. Confirm that both directories
  4550. remain included. Repeat for an additional directory to ensure it
  4551. is merged, not overwritten.
  4552. """
  4553. porcelain.cone_mode_init(self.repo)
  4554. self._commit_file("docs/readme.md", b"# doc\n")
  4555. self._commit_file("src/main.py", b"print('hello')\n")
  4556. self._commit_file("tests/test_bar.py", b"# tests\n")
  4557. # Include "docs" only
  4558. porcelain.cone_mode_set(self.repo, dirs=["docs"])
  4559. self.assertEqual({os.path.join("docs", "readme.md")}, self._list_wtree_files())
  4560. # Add "src"
  4561. porcelain.cone_mode_add(self.repo, dirs=["src"])
  4562. actual_files = self._list_wtree_files()
  4563. self.assertEqual(
  4564. {os.path.join("docs", "readme.md"), os.path.join("src", "main.py")},
  4565. actual_files,
  4566. )
  4567. # Add "tests" as well
  4568. porcelain.cone_mode_add(self.repo, dirs=["tests"])
  4569. actual_files = self._list_wtree_files()
  4570. expected_files = {
  4571. os.path.join("docs", "readme.md"),
  4572. os.path.join("src", "main.py"),
  4573. os.path.join("tests", "test_bar.py"),
  4574. }
  4575. self.assertEqual(expected_files, actual_files)
  4576. # Check .git/info/sparse-checkout
  4577. sp_path = os.path.join(self.repo_path, ".git", "info", "sparse-checkout")
  4578. with open(sp_path) as f:
  4579. lines = [ln.strip() for ln in f if ln.strip()]
  4580. # Standard cone mode lines:
  4581. # "/*" -> include top-level
  4582. # "!/*/" -> exclude subdirectories
  4583. # "!/docs/", "!/src/", "!/tests/" -> re-include the directories we added
  4584. self.assertIn("/*", lines)
  4585. self.assertIn("!/*/", lines)
  4586. self.assertIn("/docs/", lines)
  4587. self.assertIn("/src/", lines)
  4588. self.assertIn("/tests/", lines)
  4589. class UnpackObjectsTest(PorcelainTestCase):
  4590. def test_unpack_objects(self):
  4591. """Test unpacking objects from a pack file."""
  4592. # Create a test repository with some objects
  4593. b1 = Blob()
  4594. b1.data = b"test content 1"
  4595. b2 = Blob()
  4596. b2.data = b"test content 2"
  4597. # Add objects to the repo
  4598. self.repo.object_store.add_object(b1)
  4599. self.repo.object_store.add_object(b2)
  4600. # Create a pack file with these objects
  4601. pack_path = os.path.join(self.test_dir, "test_pack")
  4602. with (
  4603. open(pack_path + ".pack", "wb") as pack_f,
  4604. open(pack_path + ".idx", "wb") as idx_f,
  4605. ):
  4606. porcelain.pack_objects(
  4607. self.repo,
  4608. [b1.id, b2.id],
  4609. pack_f,
  4610. idx_f,
  4611. )
  4612. # Create a new repository to unpack into
  4613. target_repo_path = os.path.join(self.test_dir, "target_repo")
  4614. target_repo = Repo.init(target_repo_path, mkdir=True)
  4615. self.addCleanup(target_repo.close)
  4616. # Unpack the objects
  4617. count = porcelain.unpack_objects(pack_path + ".pack", target_repo_path)
  4618. # Verify the objects were unpacked
  4619. self.assertEqual(2, count)
  4620. self.assertIn(b1.id, target_repo.object_store)
  4621. self.assertIn(b2.id, target_repo.object_store)
  4622. # Verify the content is correct
  4623. unpacked_b1 = target_repo.object_store[b1.id]
  4624. unpacked_b2 = target_repo.object_store[b2.id]
  4625. self.assertEqual(b1.data, unpacked_b1.data)
  4626. self.assertEqual(b2.data, unpacked_b2.data)
  4627. class CountObjectsTests(PorcelainTestCase):
  4628. def test_count_objects_empty_repo(self):
  4629. """Test counting objects in an empty repository."""
  4630. stats = porcelain.count_objects(self.repo)
  4631. self.assertEqual(0, stats.count)
  4632. self.assertEqual(0, stats.size)
  4633. def test_count_objects_verbose_empty_repo(self):
  4634. """Test verbose counting in an empty repository."""
  4635. stats = porcelain.count_objects(self.repo, verbose=True)
  4636. self.assertEqual(0, stats.count)
  4637. self.assertEqual(0, stats.size)
  4638. self.assertEqual(0, stats.in_pack)
  4639. self.assertEqual(0, stats.packs)
  4640. self.assertEqual(0, stats.size_pack)
  4641. def test_count_objects_with_loose_objects(self):
  4642. """Test counting loose objects."""
  4643. # Create some loose objects
  4644. blob1 = make_object(Blob, data=b"data1")
  4645. blob2 = make_object(Blob, data=b"data2")
  4646. self.repo.object_store.add_object(blob1)
  4647. self.repo.object_store.add_object(blob2)
  4648. stats = porcelain.count_objects(self.repo)
  4649. self.assertEqual(2, stats.count)
  4650. self.assertGreater(stats.size, 0)
  4651. def test_count_objects_verbose_with_objects(self):
  4652. """Test verbose counting with both loose and packed objects."""
  4653. # Add some loose objects
  4654. for i in range(3):
  4655. blob = make_object(Blob, data=f"data{i}".encode())
  4656. self.repo.object_store.add_object(blob)
  4657. # Create a simple commit to have some objects in a pack
  4658. tree = Tree()
  4659. c1 = make_commit(tree=tree.id, message=b"Test commit")
  4660. self.repo.object_store.add_objects([(tree, None), (c1, None)])
  4661. self.repo.refs[b"HEAD"] = c1.id
  4662. # Repack to create a pack file
  4663. porcelain.repack(self.repo)
  4664. stats = porcelain.count_objects(self.repo, verbose=True)
  4665. # After repacking, loose objects might be cleaned up
  4666. self.assertIsInstance(stats.count, int)
  4667. self.assertIsInstance(stats.size, int)
  4668. self.assertGreater(stats.in_pack, 0) # Should have packed objects
  4669. self.assertGreater(stats.packs, 0) # Should have at least one pack
  4670. self.assertGreater(stats.size_pack, 0) # Pack should have size
  4671. # Verify it's the correct dataclass type
  4672. self.assertIsInstance(stats, CountObjectsResult)