test_cli.py 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570
  1. #!/usr/bin/env python
  2. # test_cli.py -- tests for dulwich.cli
  3. # vim: expandtab
  4. #
  5. # Copyright (C) 2024 Jelmer Vernooij <jelmer@jelmer.uk>
  6. #
  7. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  8. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  9. # General Public License as published by the Free Software Foundation; version 2.0
  10. # or (at your option) any later version. You can redistribute it and/or
  11. # modify it under the terms of either of these two licenses.
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. #
  19. # You should have received a copy of the licenses; if not, see
  20. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  21. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  22. # License, Version 2.0.
  23. """Tests for dulwich.cli."""
  24. import io
  25. import os
  26. import shutil
  27. import sys
  28. import tempfile
  29. import unittest
  30. from unittest import skipIf
  31. from unittest.mock import MagicMock, patch
  32. from dulwich import cli
  33. from dulwich.cli import format_bytes, launch_editor, parse_relative_time
  34. from dulwich.repo import Repo
  35. from dulwich.tests.utils import (
  36. build_commit_graph,
  37. )
  38. from . import TestCase
  39. class DulwichCliTestCase(TestCase):
  40. """Base class for CLI tests."""
  41. def setUp(self) -> None:
  42. super().setUp()
  43. self.test_dir = tempfile.mkdtemp()
  44. self.addCleanup(shutil.rmtree, self.test_dir)
  45. self.repo_path = os.path.join(self.test_dir, "repo")
  46. os.mkdir(self.repo_path)
  47. self.repo = Repo.init(self.repo_path)
  48. self.addCleanup(self.repo.close)
  49. def _run_cli(self, *args, stdout_stream=None):
  50. """Run CLI command and capture output."""
  51. class MockStream:
  52. def __init__(self):
  53. self._buffer = io.BytesIO()
  54. self.buffer = self._buffer
  55. def write(self, data):
  56. if isinstance(data, bytes):
  57. self._buffer.write(data)
  58. else:
  59. self._buffer.write(data.encode("utf-8"))
  60. def getvalue(self):
  61. value = self._buffer.getvalue()
  62. try:
  63. return value.decode("utf-8")
  64. except UnicodeDecodeError:
  65. return value
  66. def __getattr__(self, name):
  67. return getattr(self._buffer, name)
  68. old_stdout = sys.stdout
  69. old_stderr = sys.stderr
  70. old_cwd = os.getcwd()
  71. try:
  72. # Use custom stdout_stream if provided, otherwise use MockStream
  73. if stdout_stream:
  74. sys.stdout = stdout_stream
  75. if not hasattr(sys.stdout, "buffer"):
  76. sys.stdout.buffer = sys.stdout
  77. else:
  78. sys.stdout = MockStream()
  79. sys.stderr = MockStream()
  80. os.chdir(self.repo_path)
  81. result = cli.main(list(args))
  82. return result, sys.stdout.getvalue(), sys.stderr.getvalue()
  83. finally:
  84. sys.stdout = old_stdout
  85. sys.stderr = old_stderr
  86. os.chdir(old_cwd)
  87. class InitCommandTest(DulwichCliTestCase):
  88. """Tests for init command."""
  89. def test_init_basic(self):
  90. # Create a new directory for init
  91. new_repo_path = os.path.join(self.test_dir, "new_repo")
  92. result, stdout, stderr = self._run_cli("init", new_repo_path)
  93. self.assertTrue(os.path.exists(os.path.join(new_repo_path, ".git")))
  94. def test_init_bare(self):
  95. # Create a new directory for bare repo
  96. bare_repo_path = os.path.join(self.test_dir, "bare_repo")
  97. result, stdout, stderr = self._run_cli("init", "--bare", bare_repo_path)
  98. self.assertTrue(os.path.exists(os.path.join(bare_repo_path, "HEAD")))
  99. self.assertFalse(os.path.exists(os.path.join(bare_repo_path, ".git")))
  100. class HelperFunctionsTest(TestCase):
  101. """Tests for CLI helper functions."""
  102. def test_format_bytes(self):
  103. self.assertEqual("0.0 B", format_bytes(0))
  104. self.assertEqual("100.0 B", format_bytes(100))
  105. self.assertEqual("1.0 KB", format_bytes(1024))
  106. self.assertEqual("1.5 KB", format_bytes(1536))
  107. self.assertEqual("1.0 MB", format_bytes(1024 * 1024))
  108. self.assertEqual("1.0 GB", format_bytes(1024 * 1024 * 1024))
  109. self.assertEqual("1.0 TB", format_bytes(1024 * 1024 * 1024 * 1024))
  110. def test_launch_editor_with_cat(self):
  111. """Test launch_editor by using cat as the editor."""
  112. self.overrideEnv("GIT_EDITOR", "cat")
  113. result = launch_editor(b"Test template content")
  114. self.assertEqual(b"Test template content", result)
  115. class AddCommandTest(DulwichCliTestCase):
  116. """Tests for add command."""
  117. def test_add_single_file(self):
  118. # Create a file to add
  119. test_file = os.path.join(self.repo_path, "test.txt")
  120. with open(test_file, "w") as f:
  121. f.write("test content")
  122. result, stdout, stderr = self._run_cli("add", "test.txt")
  123. # Check that file is in index
  124. self.assertIn(b"test.txt", self.repo.open_index())
  125. def test_add_multiple_files(self):
  126. # Create multiple files
  127. for i in range(3):
  128. test_file = os.path.join(self.repo_path, f"test{i}.txt")
  129. with open(test_file, "w") as f:
  130. f.write(f"content {i}")
  131. result, stdout, stderr = self._run_cli(
  132. "add", "test0.txt", "test1.txt", "test2.txt"
  133. )
  134. index = self.repo.open_index()
  135. self.assertIn(b"test0.txt", index)
  136. self.assertIn(b"test1.txt", index)
  137. self.assertIn(b"test2.txt", index)
  138. class RmCommandTest(DulwichCliTestCase):
  139. """Tests for rm command."""
  140. def test_rm_file(self):
  141. # Create, add and commit a file first
  142. test_file = os.path.join(self.repo_path, "test.txt")
  143. with open(test_file, "w") as f:
  144. f.write("test content")
  145. self._run_cli("add", "test.txt")
  146. self._run_cli("commit", "--message=Add test file")
  147. # Now remove it from index and working directory
  148. result, stdout, stderr = self._run_cli("rm", "test.txt")
  149. # Check that file is not in index
  150. self.assertNotIn(b"test.txt", self.repo.open_index())
  151. class CommitCommandTest(DulwichCliTestCase):
  152. """Tests for commit command."""
  153. def test_commit_basic(self):
  154. # Create and add a file
  155. test_file = os.path.join(self.repo_path, "test.txt")
  156. with open(test_file, "w") as f:
  157. f.write("test content")
  158. self._run_cli("add", "test.txt")
  159. # Commit
  160. result, stdout, stderr = self._run_cli("commit", "--message=Initial commit")
  161. # Check that HEAD points to a commit
  162. self.assertIsNotNone(self.repo.head())
  163. def test_commit_all_flag(self):
  164. # Create initial commit
  165. test_file = os.path.join(self.repo_path, "test.txt")
  166. with open(test_file, "w") as f:
  167. f.write("initial content")
  168. self._run_cli("add", "test.txt")
  169. self._run_cli("commit", "--message=Initial commit")
  170. # Modify the file (don't stage it)
  171. with open(test_file, "w") as f:
  172. f.write("modified content")
  173. # Create another file and don't add it (untracked)
  174. untracked_file = os.path.join(self.repo_path, "untracked.txt")
  175. with open(untracked_file, "w") as f:
  176. f.write("untracked content")
  177. # Commit with -a flag should stage and commit the modified file,
  178. # but not the untracked file
  179. result, stdout, stderr = self._run_cli(
  180. "commit", "-a", "--message=Modified commit"
  181. )
  182. self.assertIsNotNone(self.repo.head())
  183. # Check that the modification was committed
  184. with open(test_file) as f:
  185. content = f.read()
  186. self.assertEqual(content, "modified content")
  187. # Check that untracked file is still untracked
  188. self.assertTrue(os.path.exists(untracked_file))
  189. def test_commit_all_flag_no_changes(self):
  190. # Create initial commit
  191. test_file = os.path.join(self.repo_path, "test.txt")
  192. with open(test_file, "w") as f:
  193. f.write("initial content")
  194. self._run_cli("add", "test.txt")
  195. self._run_cli("commit", "--message=Initial commit")
  196. # Try to commit with -a when there are no changes
  197. # This should still work (git allows this)
  198. result, stdout, stderr = self._run_cli(
  199. "commit", "-a", "--message=No changes commit"
  200. )
  201. self.assertIsNotNone(self.repo.head())
  202. def test_commit_all_flag_multiple_files(self):
  203. # Create initial commit with multiple files
  204. file1 = os.path.join(self.repo_path, "file1.txt")
  205. file2 = os.path.join(self.repo_path, "file2.txt")
  206. with open(file1, "w") as f:
  207. f.write("content1")
  208. with open(file2, "w") as f:
  209. f.write("content2")
  210. self._run_cli("add", "file1.txt", "file2.txt")
  211. self._run_cli("commit", "--message=Initial commit")
  212. # Modify both files
  213. with open(file1, "w") as f:
  214. f.write("modified content1")
  215. with open(file2, "w") as f:
  216. f.write("modified content2")
  217. # Create an untracked file
  218. untracked_file = os.path.join(self.repo_path, "untracked.txt")
  219. with open(untracked_file, "w") as f:
  220. f.write("untracked content")
  221. # Commit with -a should stage both modified files but not untracked
  222. result, stdout, stderr = self._run_cli(
  223. "commit", "-a", "--message=Modified both files"
  224. )
  225. self.assertIsNotNone(self.repo.head())
  226. # Verify modifications were committed
  227. with open(file1) as f:
  228. self.assertEqual(f.read(), "modified content1")
  229. with open(file2) as f:
  230. self.assertEqual(f.read(), "modified content2")
  231. # Verify untracked file still exists
  232. self.assertTrue(os.path.exists(untracked_file))
  233. @patch("dulwich.cli.launch_editor")
  234. def test_commit_editor_success(self, mock_editor):
  235. """Test commit with editor when user provides a message."""
  236. # Create and add a file
  237. test_file = os.path.join(self.repo_path, "test.txt")
  238. with open(test_file, "w") as f:
  239. f.write("test content")
  240. self._run_cli("add", "test.txt")
  241. # Mock editor to return a commit message
  242. mock_editor.return_value = b"My commit message\n\n# This is a comment\n"
  243. # Commit without --message flag
  244. result, stdout, stderr = self._run_cli("commit")
  245. # Check that HEAD points to a commit
  246. commit = self.repo[self.repo.head()]
  247. self.assertEqual(commit.message, b"My commit message")
  248. # Verify editor was called
  249. mock_editor.assert_called_once()
  250. @patch("dulwich.cli.launch_editor")
  251. def test_commit_editor_empty_message(self, mock_editor):
  252. """Test commit with editor when user provides empty message."""
  253. # Create and add a file
  254. test_file = os.path.join(self.repo_path, "test.txt")
  255. with open(test_file, "w") as f:
  256. f.write("test content")
  257. self._run_cli("add", "test.txt")
  258. # Mock editor to return only comments
  259. mock_editor.return_value = b"# All lines are comments\n# No actual message\n"
  260. # Commit without --message flag should fail with exit code 1
  261. result, stdout, stderr = self._run_cli("commit")
  262. self.assertEqual(result, 1)
  263. @patch("dulwich.cli.launch_editor")
  264. def test_commit_editor_unchanged_template(self, mock_editor):
  265. """Test commit with editor when user doesn't change the template."""
  266. # Create and add a file
  267. test_file = os.path.join(self.repo_path, "test.txt")
  268. with open(test_file, "w") as f:
  269. f.write("test content")
  270. self._run_cli("add", "test.txt")
  271. # Mock editor to return the exact template that was passed to it
  272. def return_unchanged_template(template):
  273. return template
  274. mock_editor.side_effect = return_unchanged_template
  275. # Commit without --message flag should fail with exit code 1
  276. result, stdout, stderr = self._run_cli("commit")
  277. self.assertEqual(result, 1)
  278. class LogCommandTest(DulwichCliTestCase):
  279. """Tests for log command."""
  280. def test_log_empty_repo(self):
  281. result, stdout, stderr = self._run_cli("log")
  282. # Empty repo should not crash
  283. def test_log_with_commits(self):
  284. # Create some commits
  285. c1, c2, c3 = build_commit_graph(
  286. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  287. )
  288. self.repo.refs[b"HEAD"] = c3.id
  289. result, stdout, stderr = self._run_cli("log")
  290. self.assertIn("Commit 3", stdout)
  291. self.assertIn("Commit 2", stdout)
  292. self.assertIn("Commit 1", stdout)
  293. def test_log_reverse(self):
  294. # Create some commits
  295. c1, c2, c3 = build_commit_graph(
  296. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  297. )
  298. self.repo.refs[b"HEAD"] = c3.id
  299. result, stdout, stderr = self._run_cli("log", "--reverse")
  300. # Check order - commit 1 should appear before commit 3
  301. pos1 = stdout.index("Commit 1")
  302. pos3 = stdout.index("Commit 3")
  303. self.assertLess(pos1, pos3)
  304. class StatusCommandTest(DulwichCliTestCase):
  305. """Tests for status command."""
  306. def test_status_empty(self):
  307. result, stdout, stderr = self._run_cli("status")
  308. # Should not crash on empty repo
  309. def test_status_with_untracked(self):
  310. # Create an untracked file
  311. test_file = os.path.join(self.repo_path, "untracked.txt")
  312. with open(test_file, "w") as f:
  313. f.write("untracked content")
  314. result, stdout, stderr = self._run_cli("status")
  315. self.assertIn("Untracked files:", stdout)
  316. self.assertIn("untracked.txt", stdout)
  317. class BranchCommandTest(DulwichCliTestCase):
  318. """Tests for branch command."""
  319. def test_branch_create(self):
  320. # Create initial commit
  321. test_file = os.path.join(self.repo_path, "test.txt")
  322. with open(test_file, "w") as f:
  323. f.write("test")
  324. self._run_cli("add", "test.txt")
  325. self._run_cli("commit", "--message=Initial")
  326. # Create branch
  327. result, stdout, stderr = self._run_cli("branch", "test-branch")
  328. self.assertIn(b"refs/heads/test-branch", self.repo.refs.keys())
  329. def test_branch_delete(self):
  330. # Create initial commit and branch
  331. test_file = os.path.join(self.repo_path, "test.txt")
  332. with open(test_file, "w") as f:
  333. f.write("test")
  334. self._run_cli("add", "test.txt")
  335. self._run_cli("commit", "--message=Initial")
  336. self._run_cli("branch", "test-branch")
  337. # Delete branch
  338. result, stdout, stderr = self._run_cli("branch", "-d", "test-branch")
  339. self.assertNotIn(b"refs/heads/test-branch", self.repo.refs.keys())
  340. def test_branch_list_all(self):
  341. # Create initial commit
  342. test_file = os.path.join(self.repo_path, "test.txt")
  343. with open(test_file, "w") as f:
  344. f.write("test")
  345. self._run_cli("add", "test.txt")
  346. self._run_cli("commit", "--message=Initial")
  347. # Create local test branches
  348. self._run_cli("branch", "feature-1")
  349. self._run_cli("branch", "feature-2")
  350. # Setup a remote and create remote branches
  351. self.repo.refs[b"refs/remotes/origin/master"] = self.repo.refs[
  352. b"refs/heads/master"
  353. ]
  354. self.repo.refs[b"refs/remotes/origin/feature-remote"] = self.repo.refs[
  355. b"refs/heads/master"
  356. ]
  357. # Test --all listing
  358. result, stdout, stderr = self._run_cli("branch", "--all")
  359. self.assertEqual(result, 0)
  360. expected_branches = {
  361. "feature-1", # local branch
  362. "feature-2", # local branch
  363. "master", # local branch
  364. "origin/master", # remote branch
  365. "origin/feature-remote", # remote branch
  366. }
  367. lines = [line.strip() for line in stdout.splitlines()]
  368. # All branches from stdout
  369. all_branches = set(line for line in lines)
  370. self.assertEqual(all_branches, expected_branches)
  371. def test_branch_list_remotes(self):
  372. # Create initial commit
  373. test_file = os.path.join(self.repo_path, "test.txt")
  374. with open(test_file, "w") as f:
  375. f.write("test")
  376. self._run_cli("add", "test.txt")
  377. self._run_cli("commit", "--message=Initial")
  378. # Setup a remote and create remote branches
  379. self.repo.refs[b"refs/remotes/origin/master"] = self.repo.refs[
  380. b"refs/heads/master"
  381. ]
  382. self.repo.refs[b"refs/remotes/origin/feature-remote-1"] = self.repo.refs[
  383. b"refs/heads/master"
  384. ]
  385. self.repo.refs[b"refs/remotes/origin/feature-remote-2"] = self.repo.refs[
  386. b"refs/heads/master"
  387. ]
  388. # Test --remotes listing
  389. result, stdout, stderr = self._run_cli("branch", "--remotes")
  390. self.assertEqual(result, 0)
  391. branches = [line.strip() for line in stdout.splitlines()]
  392. expected_branches = [
  393. "origin/feature-remote-1",
  394. "origin/feature-remote-2",
  395. "origin/master",
  396. ]
  397. self.assertEqual(branches, expected_branches)
  398. class CheckoutCommandTest(DulwichCliTestCase):
  399. """Tests for checkout command."""
  400. def test_checkout_branch(self):
  401. # Create initial commit and branch
  402. test_file = os.path.join(self.repo_path, "test.txt")
  403. with open(test_file, "w") as f:
  404. f.write("test")
  405. self._run_cli("add", "test.txt")
  406. self._run_cli("commit", "--message=Initial")
  407. self._run_cli("branch", "test-branch")
  408. # Checkout branch
  409. result, stdout, stderr = self._run_cli("checkout", "test-branch")
  410. self.assertEqual(
  411. self.repo.refs.read_ref(b"HEAD"), b"ref: refs/heads/test-branch"
  412. )
  413. class TagCommandTest(DulwichCliTestCase):
  414. """Tests for tag command."""
  415. def test_tag_create(self):
  416. # Create initial commit
  417. test_file = os.path.join(self.repo_path, "test.txt")
  418. with open(test_file, "w") as f:
  419. f.write("test")
  420. self._run_cli("add", "test.txt")
  421. self._run_cli("commit", "--message=Initial")
  422. # Create tag
  423. result, stdout, stderr = self._run_cli("tag", "v1.0")
  424. self.assertIn(b"refs/tags/v1.0", self.repo.refs.keys())
  425. class DiffCommandTest(DulwichCliTestCase):
  426. """Tests for diff command."""
  427. def test_diff_working_tree(self):
  428. # Create and commit a file
  429. test_file = os.path.join(self.repo_path, "test.txt")
  430. with open(test_file, "w") as f:
  431. f.write("initial content\n")
  432. self._run_cli("add", "test.txt")
  433. self._run_cli("commit", "--message=Initial")
  434. # Modify the file
  435. with open(test_file, "w") as f:
  436. f.write("initial content\nmodified\n")
  437. # Test unstaged diff
  438. result, stdout, stderr = self._run_cli("diff")
  439. self.assertIn("+modified", stdout)
  440. def test_diff_staged(self):
  441. # Create initial commit
  442. test_file = os.path.join(self.repo_path, "test.txt")
  443. with open(test_file, "w") as f:
  444. f.write("initial content\n")
  445. self._run_cli("add", "test.txt")
  446. self._run_cli("commit", "--message=Initial")
  447. # Modify and stage the file
  448. with open(test_file, "w") as f:
  449. f.write("initial content\nnew file\n")
  450. self._run_cli("add", "test.txt")
  451. # Test staged diff
  452. result, stdout, stderr = self._run_cli("diff", "--staged")
  453. self.assertIn("+new file", stdout)
  454. def test_diff_cached(self):
  455. # Create initial commit
  456. test_file = os.path.join(self.repo_path, "test.txt")
  457. with open(test_file, "w") as f:
  458. f.write("initial content\n")
  459. self._run_cli("add", "test.txt")
  460. self._run_cli("commit", "--message=Initial")
  461. # Modify and stage the file
  462. with open(test_file, "w") as f:
  463. f.write("initial content\nnew file\n")
  464. self._run_cli("add", "test.txt")
  465. # Test cached diff (alias for staged)
  466. result, stdout, stderr = self._run_cli("diff", "--cached")
  467. self.assertIn("+new file", stdout)
  468. def test_diff_commit(self):
  469. # Create two commits
  470. test_file = os.path.join(self.repo_path, "test.txt")
  471. with open(test_file, "w") as f:
  472. f.write("first version\n")
  473. self._run_cli("add", "test.txt")
  474. self._run_cli("commit", "--message=First")
  475. with open(test_file, "w") as f:
  476. f.write("first version\nsecond line\n")
  477. self._run_cli("add", "test.txt")
  478. self._run_cli("commit", "--message=Second")
  479. # Add working tree changes
  480. with open(test_file, "a") as f:
  481. f.write("working tree change\n")
  482. # Test single commit diff (should show working tree vs HEAD)
  483. result, stdout, stderr = self._run_cli("diff", "HEAD")
  484. self.assertIn("+working tree change", stdout)
  485. def test_diff_two_commits(self):
  486. # Create two commits
  487. test_file = os.path.join(self.repo_path, "test.txt")
  488. with open(test_file, "w") as f:
  489. f.write("first version\n")
  490. self._run_cli("add", "test.txt")
  491. self._run_cli("commit", "--message=First")
  492. # Get first commit SHA
  493. first_commit = self.repo.refs[b"HEAD"].decode()
  494. with open(test_file, "w") as f:
  495. f.write("first version\nsecond line\n")
  496. self._run_cli("add", "test.txt")
  497. self._run_cli("commit", "--message=Second")
  498. # Get second commit SHA
  499. second_commit = self.repo.refs[b"HEAD"].decode()
  500. # Test diff between two commits
  501. result, stdout, stderr = self._run_cli("diff", first_commit, second_commit)
  502. self.assertIn("+second line", stdout)
  503. def test_diff_commit_vs_working_tree(self):
  504. # Test that diff <commit> shows working tree vs commit (not commit vs parent)
  505. test_file = os.path.join(self.repo_path, "test.txt")
  506. with open(test_file, "w") as f:
  507. f.write("first version\n")
  508. self._run_cli("add", "test.txt")
  509. self._run_cli("commit", "--message=First")
  510. first_commit = self.repo.refs[b"HEAD"].decode()
  511. with open(test_file, "w") as f:
  512. f.write("first version\nsecond line\n")
  513. self._run_cli("add", "test.txt")
  514. self._run_cli("commit", "--message=Second")
  515. # Add changes to working tree
  516. with open(test_file, "w") as f:
  517. f.write("completely different\n")
  518. # diff <first_commit> should show working tree vs first commit
  519. result, stdout, stderr = self._run_cli("diff", first_commit)
  520. self.assertIn("-first version", stdout)
  521. self.assertIn("+completely different", stdout)
  522. def test_diff_with_paths(self):
  523. # Test path filtering
  524. # Create multiple files
  525. file1 = os.path.join(self.repo_path, "file1.txt")
  526. file2 = os.path.join(self.repo_path, "file2.txt")
  527. subdir = os.path.join(self.repo_path, "subdir")
  528. os.makedirs(subdir)
  529. file3 = os.path.join(subdir, "file3.txt")
  530. with open(file1, "w") as f:
  531. f.write("content1\n")
  532. with open(file2, "w") as f:
  533. f.write("content2\n")
  534. with open(file3, "w") as f:
  535. f.write("content3\n")
  536. self._run_cli("add", ".")
  537. self._run_cli("commit", "--message=Initial")
  538. # Modify all files
  539. with open(file1, "w") as f:
  540. f.write("modified1\n")
  541. with open(file2, "w") as f:
  542. f.write("modified2\n")
  543. with open(file3, "w") as f:
  544. f.write("modified3\n")
  545. # Test diff with specific file
  546. result, stdout, stderr = self._run_cli("diff", "--", "file1.txt")
  547. self.assertIn("file1.txt", stdout)
  548. self.assertNotIn("file2.txt", stdout)
  549. self.assertNotIn("file3.txt", stdout)
  550. # Test diff with directory
  551. result, stdout, stderr = self._run_cli("diff", "--", "subdir")
  552. self.assertNotIn("file1.txt", stdout)
  553. self.assertNotIn("file2.txt", stdout)
  554. self.assertIn("file3.txt", stdout)
  555. # Test staged diff with paths
  556. self._run_cli("add", "file1.txt")
  557. result, stdout, stderr = self._run_cli("diff", "--staged", "--", "file1.txt")
  558. self.assertIn("file1.txt", stdout)
  559. self.assertIn("+modified1", stdout)
  560. # Test diff with multiple paths (file2 and file3 are still unstaged)
  561. result, stdout, stderr = self._run_cli(
  562. "diff", "--", "file2.txt", "subdir/file3.txt"
  563. )
  564. self.assertIn("file2.txt", stdout)
  565. self.assertIn("file3.txt", stdout)
  566. self.assertNotIn("file1.txt", stdout)
  567. # Test diff with commit and paths
  568. first_commit = self.repo.refs[b"HEAD"].decode()
  569. with open(file1, "w") as f:
  570. f.write("newer1\n")
  571. result, stdout, stderr = self._run_cli("diff", first_commit, "--", "file1.txt")
  572. self.assertIn("file1.txt", stdout)
  573. self.assertIn("-content1", stdout)
  574. self.assertIn("+newer1", stdout)
  575. self.assertNotIn("file2.txt", stdout)
  576. class FilterBranchCommandTest(DulwichCliTestCase):
  577. """Tests for filter-branch command."""
  578. def setUp(self):
  579. super().setUp()
  580. # Create a more complex repository structure for testing
  581. # Create some files in subdirectories
  582. os.makedirs(os.path.join(self.repo_path, "subdir"))
  583. os.makedirs(os.path.join(self.repo_path, "other"))
  584. # Create files
  585. files = {
  586. "README.md": "# Test Repo",
  587. "subdir/file1.txt": "File in subdir",
  588. "subdir/file2.txt": "Another file in subdir",
  589. "other/file3.txt": "File in other dir",
  590. "root.txt": "File at root",
  591. }
  592. for path, content in files.items():
  593. file_path = os.path.join(self.repo_path, path)
  594. with open(file_path, "w") as f:
  595. f.write(content)
  596. # Add all files and create initial commit
  597. self._run_cli("add", ".")
  598. self._run_cli("commit", "--message=Initial commit")
  599. # Create a second commit modifying subdir
  600. with open(os.path.join(self.repo_path, "subdir/file1.txt"), "a") as f:
  601. f.write("\nModified content")
  602. self._run_cli("add", "subdir/file1.txt")
  603. self._run_cli("commit", "--message=Modify subdir file")
  604. # Create a third commit in other dir
  605. with open(os.path.join(self.repo_path, "other/file3.txt"), "a") as f:
  606. f.write("\nMore content")
  607. self._run_cli("add", "other/file3.txt")
  608. self._run_cli("commit", "--message=Modify other file")
  609. # Create a branch
  610. self._run_cli("branch", "test-branch")
  611. # Create a tag
  612. self._run_cli("tag", "v1.0")
  613. def test_filter_branch_subdirectory_filter(self):
  614. """Test filter-branch with subdirectory filter."""
  615. # Run filter-branch to extract only the subdir
  616. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  617. result, stdout, stderr = self._run_cli(
  618. "filter-branch", "--subdirectory-filter", "subdir"
  619. )
  620. # Check that the operation succeeded
  621. self.assertEqual(result, 0)
  622. log_output = "\n".join(cm.output)
  623. self.assertIn("Rewrite HEAD", log_output)
  624. # filter-branch rewrites history but doesn't update working tree
  625. # We need to check the commit contents, not the working tree
  626. # Reset to the rewritten HEAD to update working tree
  627. self._run_cli("reset", "--hard", "HEAD")
  628. # Now check that only files from subdir remain at root level
  629. self.assertTrue(os.path.exists(os.path.join(self.repo_path, "file1.txt")))
  630. self.assertTrue(os.path.exists(os.path.join(self.repo_path, "file2.txt")))
  631. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "README.md")))
  632. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "root.txt")))
  633. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "other")))
  634. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "subdir")))
  635. # Check that original refs were backed up
  636. original_refs = [
  637. ref for ref in self.repo.refs.keys() if ref.startswith(b"refs/original/")
  638. ]
  639. self.assertTrue(
  640. len(original_refs) > 0, "No original refs found after filter-branch"
  641. )
  642. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  643. def test_filter_branch_msg_filter(self):
  644. """Test filter-branch with message filter."""
  645. # Run filter-branch to prepend [FILTERED] to commit messages
  646. result, stdout, stderr = self._run_cli(
  647. "filter-branch", "--msg-filter", "sed 's/^/[FILTERED] /'"
  648. )
  649. self.assertEqual(result, 0)
  650. # Check that commit messages were modified
  651. result, stdout, stderr = self._run_cli("log")
  652. self.assertIn("[FILTERED] Modify other file", stdout)
  653. self.assertIn("[FILTERED] Modify subdir file", stdout)
  654. self.assertIn("[FILTERED] Initial commit", stdout)
  655. def test_filter_branch_env_filter(self):
  656. """Test filter-branch with environment filter."""
  657. # Run filter-branch to change author email
  658. env_filter = """
  659. if [ "$GIT_AUTHOR_EMAIL" = "test@example.com" ]; then
  660. export GIT_AUTHOR_EMAIL="filtered@example.com"
  661. fi
  662. """
  663. result, stdout, stderr = self._run_cli(
  664. "filter-branch", "--env-filter", env_filter
  665. )
  666. self.assertEqual(result, 0)
  667. def test_filter_branch_prune_empty(self):
  668. """Test filter-branch with prune-empty option."""
  669. # Create a commit that only touches files outside subdir
  670. with open(os.path.join(self.repo_path, "root.txt"), "a") as f:
  671. f.write("\nNew line")
  672. self._run_cli("add", "root.txt")
  673. self._run_cli("commit", "--message=Modify root file only")
  674. # Run filter-branch to extract subdir with prune-empty
  675. result, stdout, stderr = self._run_cli(
  676. "filter-branch", "--subdirectory-filter", "subdir", "--prune-empty"
  677. )
  678. self.assertEqual(result, 0)
  679. # The last commit should have been pruned
  680. result, stdout, stderr = self._run_cli("log")
  681. self.assertNotIn("Modify root file only", stdout)
  682. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  683. def test_filter_branch_force(self):
  684. """Test filter-branch with force option."""
  685. # Run filter-branch once with a filter that actually changes something
  686. result, stdout, stderr = self._run_cli(
  687. "filter-branch", "--msg-filter", "sed 's/^/[TEST] /'"
  688. )
  689. self.assertEqual(result, 0)
  690. # Check that backup refs were created
  691. # The implementation backs up refs under refs/original/
  692. original_refs = [
  693. ref for ref in self.repo.refs.keys() if ref.startswith(b"refs/original/")
  694. ]
  695. self.assertTrue(len(original_refs) > 0, "No original refs found")
  696. # Run again without force - should fail
  697. with self.assertLogs("dulwich.cli", level="ERROR") as cm:
  698. result, stdout, stderr = self._run_cli(
  699. "filter-branch", "--msg-filter", "sed 's/^/[TEST2] /'"
  700. )
  701. self.assertEqual(result, 1)
  702. log_output = "\n".join(cm.output)
  703. self.assertIn("Cannot create a new backup", log_output)
  704. self.assertIn("refs/original", log_output)
  705. # Run with force - should succeed
  706. result, stdout, stderr = self._run_cli(
  707. "filter-branch", "--force", "--msg-filter", "sed 's/^/[TEST3] /'"
  708. )
  709. self.assertEqual(result, 0)
  710. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  711. def test_filter_branch_specific_branch(self):
  712. """Test filter-branch on a specific branch."""
  713. # Switch to test-branch and add a commit
  714. self._run_cli("checkout", "test-branch")
  715. with open(os.path.join(self.repo_path, "branch-file.txt"), "w") as f:
  716. f.write("Branch specific file")
  717. self._run_cli("add", "branch-file.txt")
  718. self._run_cli("commit", "--message=Branch commit")
  719. # Run filter-branch on the test-branch
  720. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  721. result, stdout, stderr = self._run_cli(
  722. "filter-branch", "--msg-filter", "sed 's/^/[BRANCH] /'", "test-branch"
  723. )
  724. self.assertEqual(result, 0)
  725. log_output = "\n".join(cm.output)
  726. self.assertIn("Ref 'refs/heads/test-branch' was rewritten", log_output)
  727. # Check that only test-branch was modified
  728. result, stdout, stderr = self._run_cli("log")
  729. self.assertIn("[BRANCH] Branch commit", stdout)
  730. # Switch to master and check it wasn't modified
  731. self._run_cli("checkout", "master")
  732. result, stdout, stderr = self._run_cli("log")
  733. self.assertNotIn("[BRANCH]", stdout)
  734. def test_filter_branch_tree_filter(self):
  735. """Test filter-branch with tree filter."""
  736. # Use a tree filter to remove a specific file
  737. tree_filter = "rm -f root.txt"
  738. result, stdout, stderr = self._run_cli(
  739. "filter-branch", "--tree-filter", tree_filter
  740. )
  741. self.assertEqual(result, 0)
  742. # Check that the file was removed from the latest commit
  743. # We need to check the commit tree, not the working directory
  744. result, stdout, stderr = self._run_cli("ls-tree", "HEAD")
  745. self.assertNotIn("root.txt", stdout)
  746. def test_filter_branch_index_filter(self):
  747. """Test filter-branch with index filter."""
  748. # Use an index filter to remove a file from the index
  749. index_filter = "git rm --cached --ignore-unmatch root.txt"
  750. result, stdout, stderr = self._run_cli(
  751. "filter-branch", "--index-filter", index_filter
  752. )
  753. self.assertEqual(result, 0)
  754. def test_filter_branch_parent_filter(self):
  755. """Test filter-branch with parent filter."""
  756. # Create a merge commit first
  757. self._run_cli("checkout", "HEAD", "-b", "feature")
  758. with open(os.path.join(self.repo_path, "feature.txt"), "w") as f:
  759. f.write("Feature")
  760. self._run_cli("add", "feature.txt")
  761. self._run_cli("commit", "--message=Feature commit")
  762. self._run_cli("checkout", "master")
  763. self._run_cli("merge", "feature", "--message=Merge feature")
  764. # Use parent filter to linearize history (remove second parent)
  765. parent_filter = "cut -d' ' -f1"
  766. result, stdout, stderr = self._run_cli(
  767. "filter-branch", "--parent-filter", parent_filter
  768. )
  769. self.assertEqual(result, 0)
  770. def test_filter_branch_commit_filter(self):
  771. """Test filter-branch with commit filter."""
  772. # Use commit filter to skip commits with certain messages
  773. commit_filter = """
  774. if grep -q "Modify other" <<< "$GIT_COMMIT_MESSAGE"; then
  775. skip_commit "$@"
  776. else
  777. git commit-tree "$@"
  778. fi
  779. """
  780. result, stdout, stderr = self._run_cli(
  781. "filter-branch", "--commit-filter", commit_filter
  782. )
  783. # Note: This test may fail because the commit filter syntax is simplified
  784. # In real Git, skip_commit is a function, but our implementation may differ
  785. def test_filter_branch_tag_name_filter(self):
  786. """Test filter-branch with tag name filter."""
  787. # Run filter-branch with tag name filter to rename tags
  788. result, stdout, stderr = self._run_cli(
  789. "filter-branch",
  790. "--tag-name-filter",
  791. "sed 's/^v/version-/'",
  792. "--msg-filter",
  793. "cat",
  794. )
  795. self.assertEqual(result, 0)
  796. # Check that tag was renamed
  797. self.assertIn(b"refs/tags/version-1.0", self.repo.refs.keys())
  798. def test_filter_branch_errors(self):
  799. """Test filter-branch error handling."""
  800. # Test with invalid subdirectory
  801. result, stdout, stderr = self._run_cli(
  802. "filter-branch", "--subdirectory-filter", "nonexistent"
  803. )
  804. # Should still succeed but produce empty history
  805. self.assertEqual(result, 0)
  806. def test_filter_branch_no_args(self):
  807. """Test filter-branch with no arguments."""
  808. # Should work as no-op
  809. result, stdout, stderr = self._run_cli("filter-branch")
  810. self.assertEqual(result, 0)
  811. class ShowCommandTest(DulwichCliTestCase):
  812. """Tests for show command."""
  813. def test_show_commit(self):
  814. # Create a commit
  815. test_file = os.path.join(self.repo_path, "test.txt")
  816. with open(test_file, "w") as f:
  817. f.write("test content")
  818. self._run_cli("add", "test.txt")
  819. self._run_cli("commit", "--message=Test commit")
  820. result, stdout, stderr = self._run_cli("show", "HEAD")
  821. self.assertIn("Test commit", stdout)
  822. class FormatPatchCommandTest(DulwichCliTestCase):
  823. """Tests for format-patch command."""
  824. def test_format_patch_single_commit(self):
  825. # Create a commit with actual content
  826. from dulwich.objects import Blob, Tree
  827. # Initial commit
  828. tree1 = Tree()
  829. self.repo.object_store.add_object(tree1)
  830. self.repo.get_worktree().commit(
  831. message=b"Initial commit",
  832. tree=tree1.id,
  833. )
  834. # Second commit with a file
  835. blob = Blob.from_string(b"Hello, World!\n")
  836. self.repo.object_store.add_object(blob)
  837. tree2 = Tree()
  838. tree2.add(b"hello.txt", 0o100644, blob.id)
  839. self.repo.object_store.add_object(tree2)
  840. self.repo.get_worktree().commit(
  841. message=b"Add hello.txt",
  842. tree=tree2.id,
  843. )
  844. # Test format-patch for last commit
  845. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  846. result, stdout, stderr = self._run_cli("format-patch", "-n", "1")
  847. self.assertEqual(result, None)
  848. log_output = "\n".join(cm.output)
  849. self.assertIn("0001-Add-hello.txt.patch", log_output)
  850. # Check patch contents
  851. patch_file = os.path.join(self.repo_path, "0001-Add-hello.txt.patch")
  852. with open(patch_file, "rb") as f:
  853. content = f.read()
  854. # Check header
  855. self.assertIn(b"Subject: [PATCH 1/1] Add hello.txt", content)
  856. self.assertIn(b"From:", content)
  857. self.assertIn(b"Date:", content)
  858. # Check diff content
  859. self.assertIn(b"diff --git a/hello.txt b/hello.txt", content)
  860. self.assertIn(b"new file mode", content)
  861. self.assertIn(b"+Hello, World!", content)
  862. # Check footer
  863. self.assertIn(b"-- \nDulwich", content)
  864. # Clean up
  865. os.remove(patch_file)
  866. def test_format_patch_multiple_commits(self):
  867. from dulwich.objects import Blob, Tree
  868. # Initial commit
  869. tree1 = Tree()
  870. self.repo.object_store.add_object(tree1)
  871. self.repo.get_worktree().commit(
  872. message=b"Initial commit",
  873. tree=tree1.id,
  874. )
  875. # Second commit
  876. blob1 = Blob.from_string(b"File 1 content\n")
  877. self.repo.object_store.add_object(blob1)
  878. tree2 = Tree()
  879. tree2.add(b"file1.txt", 0o100644, blob1.id)
  880. self.repo.object_store.add_object(tree2)
  881. self.repo.get_worktree().commit(
  882. message=b"Add file1.txt",
  883. tree=tree2.id,
  884. )
  885. # Third commit
  886. blob2 = Blob.from_string(b"File 2 content\n")
  887. self.repo.object_store.add_object(blob2)
  888. tree3 = Tree()
  889. tree3.add(b"file1.txt", 0o100644, blob1.id)
  890. tree3.add(b"file2.txt", 0o100644, blob2.id)
  891. self.repo.object_store.add_object(tree3)
  892. self.repo.get_worktree().commit(
  893. message=b"Add file2.txt",
  894. tree=tree3.id,
  895. )
  896. # Test format-patch for last 2 commits
  897. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  898. result, stdout, stderr = self._run_cli("format-patch", "-n", "2")
  899. self.assertEqual(result, None)
  900. log_output = "\n".join(cm.output)
  901. self.assertIn("0001-Add-file1.txt.patch", log_output)
  902. self.assertIn("0002-Add-file2.txt.patch", log_output)
  903. # Check first patch
  904. with open(os.path.join(self.repo_path, "0001-Add-file1.txt.patch"), "rb") as f:
  905. content = f.read()
  906. self.assertIn(b"Subject: [PATCH 1/2] Add file1.txt", content)
  907. self.assertIn(b"+File 1 content", content)
  908. # Check second patch
  909. with open(os.path.join(self.repo_path, "0002-Add-file2.txt.patch"), "rb") as f:
  910. content = f.read()
  911. self.assertIn(b"Subject: [PATCH 2/2] Add file2.txt", content)
  912. self.assertIn(b"+File 2 content", content)
  913. # Clean up
  914. os.remove(os.path.join(self.repo_path, "0001-Add-file1.txt.patch"))
  915. os.remove(os.path.join(self.repo_path, "0002-Add-file2.txt.patch"))
  916. def test_format_patch_output_directory(self):
  917. from dulwich.objects import Blob, Tree
  918. # Create a commit
  919. blob = Blob.from_string(b"Test content\n")
  920. self.repo.object_store.add_object(blob)
  921. tree = Tree()
  922. tree.add(b"test.txt", 0o100644, blob.id)
  923. self.repo.object_store.add_object(tree)
  924. self.repo.get_worktree().commit(
  925. message=b"Test commit",
  926. tree=tree.id,
  927. )
  928. # Create output directory
  929. output_dir = os.path.join(self.test_dir, "patches")
  930. os.makedirs(output_dir)
  931. # Test format-patch with output directory
  932. result, stdout, stderr = self._run_cli(
  933. "format-patch", "-o", output_dir, "-n", "1"
  934. )
  935. self.assertEqual(result, None)
  936. # Check that file was created in output directory with correct content
  937. patch_file = os.path.join(output_dir, "0001-Test-commit.patch")
  938. self.assertTrue(os.path.exists(patch_file))
  939. with open(patch_file, "rb") as f:
  940. content = f.read()
  941. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  942. self.assertIn(b"+Test content", content)
  943. def test_format_patch_commit_range(self):
  944. from dulwich.objects import Blob, Tree
  945. # Create commits with actual file changes
  946. commits = []
  947. trees = []
  948. # Initial empty commit
  949. tree0 = Tree()
  950. self.repo.object_store.add_object(tree0)
  951. trees.append(tree0)
  952. c0 = self.repo.get_worktree().commit(
  953. message=b"Initial commit",
  954. tree=tree0.id,
  955. )
  956. commits.append(c0)
  957. # Add three files in separate commits
  958. for i in range(1, 4):
  959. blob = Blob.from_string(f"Content {i}\n".encode())
  960. self.repo.object_store.add_object(blob)
  961. tree = Tree()
  962. # Copy previous files
  963. for j in range(1, i):
  964. prev_blob_id = trees[j][f"file{j}.txt".encode()][1]
  965. tree.add(f"file{j}.txt".encode(), 0o100644, prev_blob_id)
  966. # Add new file
  967. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  968. self.repo.object_store.add_object(tree)
  969. trees.append(tree)
  970. c = self.repo.get_worktree().commit(
  971. message=f"Add file{i}.txt".encode(),
  972. tree=tree.id,
  973. )
  974. commits.append(c)
  975. # Test format-patch with commit range (should get commits 2 and 3)
  976. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  977. result, stdout, stderr = self._run_cli(
  978. "format-patch", f"{commits[1].decode()}..{commits[3].decode()}"
  979. )
  980. self.assertEqual(result, None)
  981. # Should create patches for commits 2 and 3
  982. log_output = "\n".join(cm.output)
  983. self.assertIn("0001-Add-file2.txt.patch", log_output)
  984. self.assertIn("0002-Add-file3.txt.patch", log_output)
  985. # Verify patch contents
  986. with open(os.path.join(self.repo_path, "0001-Add-file2.txt.patch"), "rb") as f:
  987. content = f.read()
  988. self.assertIn(b"Subject: [PATCH 1/2] Add file2.txt", content)
  989. self.assertIn(b"+Content 2", content)
  990. self.assertNotIn(b"file3.txt", content) # Should not include file3
  991. with open(os.path.join(self.repo_path, "0002-Add-file3.txt.patch"), "rb") as f:
  992. content = f.read()
  993. self.assertIn(b"Subject: [PATCH 2/2] Add file3.txt", content)
  994. self.assertIn(b"+Content 3", content)
  995. self.assertNotIn(b"file2.txt", content) # Should not modify file2
  996. # Clean up
  997. os.remove(os.path.join(self.repo_path, "0001-Add-file2.txt.patch"))
  998. os.remove(os.path.join(self.repo_path, "0002-Add-file3.txt.patch"))
  999. def test_format_patch_stdout(self):
  1000. from dulwich.objects import Blob, Tree
  1001. # Create a commit with modified file
  1002. tree1 = Tree()
  1003. blob1 = Blob.from_string(b"Original content\n")
  1004. self.repo.object_store.add_object(blob1)
  1005. tree1.add(b"file.txt", 0o100644, blob1.id)
  1006. self.repo.object_store.add_object(tree1)
  1007. self.repo.get_worktree().commit(
  1008. message=b"Initial commit",
  1009. tree=tree1.id,
  1010. )
  1011. tree2 = Tree()
  1012. blob2 = Blob.from_string(b"Modified content\n")
  1013. self.repo.object_store.add_object(blob2)
  1014. tree2.add(b"file.txt", 0o100644, blob2.id)
  1015. self.repo.object_store.add_object(tree2)
  1016. self.repo.get_worktree().commit(
  1017. message=b"Modify file.txt",
  1018. tree=tree2.id,
  1019. )
  1020. # Mock stdout as a BytesIO for binary output
  1021. stdout_stream = io.BytesIO()
  1022. stdout_stream.buffer = stdout_stream
  1023. # Run command with --stdout
  1024. old_stdout = sys.stdout
  1025. old_stderr = sys.stderr
  1026. old_cwd = os.getcwd()
  1027. try:
  1028. sys.stdout = stdout_stream
  1029. sys.stderr = io.StringIO()
  1030. os.chdir(self.repo_path)
  1031. cli.main(["format-patch", "--stdout", "-n", "1"])
  1032. finally:
  1033. sys.stdout = old_stdout
  1034. sys.stderr = old_stderr
  1035. os.chdir(old_cwd)
  1036. # Check output
  1037. stdout_stream.seek(0)
  1038. output = stdout_stream.read()
  1039. self.assertIn(b"Subject: [PATCH 1/1] Modify file.txt", output)
  1040. self.assertIn(b"diff --git a/file.txt b/file.txt", output)
  1041. self.assertIn(b"-Original content", output)
  1042. self.assertIn(b"+Modified content", output)
  1043. self.assertIn(b"-- \nDulwich", output)
  1044. def test_format_patch_empty_repo(self):
  1045. # Test with empty repository
  1046. result, stdout, stderr = self._run_cli("format-patch", "-n", "5")
  1047. self.assertEqual(result, None)
  1048. # Should produce no output for empty repo
  1049. self.assertEqual(stdout.strip(), "")
  1050. class FetchPackCommandTest(DulwichCliTestCase):
  1051. """Tests for fetch-pack command."""
  1052. @patch("dulwich.cli.get_transport_and_path")
  1053. def test_fetch_pack_basic(self, mock_transport):
  1054. # Mock the transport
  1055. mock_client = MagicMock()
  1056. mock_transport.return_value = (mock_client, "/path/to/repo")
  1057. mock_client.fetch.return_value = None
  1058. result, stdout, stderr = self._run_cli(
  1059. "fetch-pack", "git://example.com/repo.git"
  1060. )
  1061. mock_client.fetch.assert_called_once()
  1062. class LsRemoteCommandTest(DulwichCliTestCase):
  1063. """Tests for ls-remote command."""
  1064. def test_ls_remote_basic(self):
  1065. # Create a commit
  1066. test_file = os.path.join(self.repo_path, "test.txt")
  1067. with open(test_file, "w") as f:
  1068. f.write("test")
  1069. self._run_cli("add", "test.txt")
  1070. self._run_cli("commit", "--message=Initial")
  1071. # Test basic ls-remote
  1072. result, stdout, stderr = self._run_cli("ls-remote", self.repo_path)
  1073. lines = stdout.strip().split("\n")
  1074. self.assertTrue(any("HEAD" in line for line in lines))
  1075. self.assertTrue(any("refs/heads/master" in line for line in lines))
  1076. def test_ls_remote_symref(self):
  1077. # Create a commit
  1078. test_file = os.path.join(self.repo_path, "test.txt")
  1079. with open(test_file, "w") as f:
  1080. f.write("test")
  1081. self._run_cli("add", "test.txt")
  1082. self._run_cli("commit", "--message=Initial")
  1083. # Test ls-remote with --symref option
  1084. result, stdout, stderr = self._run_cli("ls-remote", "--symref", self.repo_path)
  1085. lines = stdout.strip().split("\n")
  1086. # Should show symref for HEAD in exact format: "ref: refs/heads/master\tHEAD"
  1087. expected_line = "ref: refs/heads/master\tHEAD"
  1088. self.assertIn(
  1089. expected_line,
  1090. lines,
  1091. f"Expected line '{expected_line}' not found in output: {lines}",
  1092. )
  1093. class PullCommandTest(DulwichCliTestCase):
  1094. """Tests for pull command."""
  1095. @patch("dulwich.porcelain.pull")
  1096. def test_pull_basic(self, mock_pull):
  1097. result, stdout, stderr = self._run_cli("pull", "origin")
  1098. mock_pull.assert_called_once()
  1099. @patch("dulwich.porcelain.pull")
  1100. def test_pull_with_refspec(self, mock_pull):
  1101. result, stdout, stderr = self._run_cli("pull", "origin", "master")
  1102. mock_pull.assert_called_once()
  1103. class PushCommandTest(DulwichCliTestCase):
  1104. """Tests for push command."""
  1105. @patch("dulwich.porcelain.push")
  1106. def test_push_basic(self, mock_push):
  1107. result, stdout, stderr = self._run_cli("push", "origin")
  1108. mock_push.assert_called_once()
  1109. @patch("dulwich.porcelain.push")
  1110. def test_push_force(self, mock_push):
  1111. result, stdout, stderr = self._run_cli("push", "-f", "origin")
  1112. mock_push.assert_called_with(".", "origin", None, force=True)
  1113. class ArchiveCommandTest(DulwichCliTestCase):
  1114. """Tests for archive command."""
  1115. def test_archive_basic(self):
  1116. # Create a commit
  1117. test_file = os.path.join(self.repo_path, "test.txt")
  1118. with open(test_file, "w") as f:
  1119. f.write("test content")
  1120. self._run_cli("add", "test.txt")
  1121. self._run_cli("commit", "--message=Initial")
  1122. # Archive produces binary output, so use BytesIO
  1123. result, stdout, stderr = self._run_cli(
  1124. "archive", "HEAD", stdout_stream=io.BytesIO()
  1125. )
  1126. # Should complete without error and produce some binary output
  1127. self.assertIsInstance(stdout, bytes)
  1128. self.assertGreater(len(stdout), 0)
  1129. class ForEachRefCommandTest(DulwichCliTestCase):
  1130. """Tests for for-each-ref command."""
  1131. def test_for_each_ref(self):
  1132. # Create a commit
  1133. test_file = os.path.join(self.repo_path, "test.txt")
  1134. with open(test_file, "w") as f:
  1135. f.write("test")
  1136. self._run_cli("add", "test.txt")
  1137. self._run_cli("commit", "--message=Initial")
  1138. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1139. result, stdout, stderr = self._run_cli("for-each-ref")
  1140. log_output = "\n".join(cm.output)
  1141. # Just check that we have some refs output and it contains refs/heads
  1142. self.assertTrue(len(cm.output) > 0, "Expected some ref output")
  1143. self.assertIn("refs/heads/", log_output)
  1144. class PackRefsCommandTest(DulwichCliTestCase):
  1145. """Tests for pack-refs command."""
  1146. def test_pack_refs(self):
  1147. # Create some refs
  1148. test_file = os.path.join(self.repo_path, "test.txt")
  1149. with open(test_file, "w") as f:
  1150. f.write("test")
  1151. self._run_cli("add", "test.txt")
  1152. self._run_cli("commit", "--message=Initial")
  1153. self._run_cli("branch", "test-branch")
  1154. result, stdout, stderr = self._run_cli("pack-refs", "--all")
  1155. # Check that packed-refs file exists
  1156. self.assertTrue(
  1157. os.path.exists(os.path.join(self.repo_path, ".git", "packed-refs"))
  1158. )
  1159. class SubmoduleCommandTest(DulwichCliTestCase):
  1160. """Tests for submodule commands."""
  1161. def test_submodule_list(self):
  1162. # Create an initial commit so repo has a HEAD
  1163. test_file = os.path.join(self.repo_path, "test.txt")
  1164. with open(test_file, "w") as f:
  1165. f.write("test")
  1166. self._run_cli("add", "test.txt")
  1167. self._run_cli("commit", "--message=Initial")
  1168. result, stdout, stderr = self._run_cli("submodule")
  1169. # Should not crash on repo without submodules
  1170. def test_submodule_init(self):
  1171. # Create .gitmodules file for init to work
  1172. gitmodules = os.path.join(self.repo_path, ".gitmodules")
  1173. with open(gitmodules, "w") as f:
  1174. f.write("") # Empty .gitmodules file
  1175. result, stdout, stderr = self._run_cli("submodule", "init")
  1176. # Should not crash
  1177. class StashCommandTest(DulwichCliTestCase):
  1178. """Tests for stash commands."""
  1179. def test_stash_list_empty(self):
  1180. result, stdout, stderr = self._run_cli("stash", "list")
  1181. # Should not crash on empty stash
  1182. def test_stash_push_pop(self):
  1183. # Create a file and modify it
  1184. test_file = os.path.join(self.repo_path, "test.txt")
  1185. with open(test_file, "w") as f:
  1186. f.write("initial")
  1187. self._run_cli("add", "test.txt")
  1188. self._run_cli("commit", "--message=Initial")
  1189. # Modify file
  1190. with open(test_file, "w") as f:
  1191. f.write("modified")
  1192. # Stash changes
  1193. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1194. result, stdout, stderr = self._run_cli("stash", "push")
  1195. self.assertIn("Saved working directory", cm.output[0])
  1196. # Note: Dulwich stash doesn't currently update the working tree
  1197. # so the file remains modified after stash push
  1198. # Note: stash pop is not fully implemented in Dulwich yet
  1199. # so we only test stash push here
  1200. class MergeCommandTest(DulwichCliTestCase):
  1201. """Tests for merge command."""
  1202. def test_merge_basic(self):
  1203. # Create initial commit
  1204. test_file = os.path.join(self.repo_path, "test.txt")
  1205. with open(test_file, "w") as f:
  1206. f.write("initial")
  1207. self._run_cli("add", "test.txt")
  1208. self._run_cli("commit", "--message=Initial")
  1209. # Create and checkout new branch
  1210. self._run_cli("branch", "feature")
  1211. self._run_cli("checkout", "feature")
  1212. # Make changes in feature branch
  1213. with open(test_file, "w") as f:
  1214. f.write("feature changes")
  1215. self._run_cli("add", "test.txt")
  1216. self._run_cli("commit", "--message=Feature commit")
  1217. # Go back to main
  1218. self._run_cli("checkout", "master")
  1219. # Merge feature branch
  1220. result, stdout, stderr = self._run_cli("merge", "feature")
  1221. class HelpCommandTest(DulwichCliTestCase):
  1222. """Tests for help command."""
  1223. def test_help_basic(self):
  1224. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1225. result, stdout, stderr = self._run_cli("help")
  1226. log_output = "\n".join(cm.output)
  1227. self.assertIn("dulwich command line tool", log_output)
  1228. def test_help_all(self):
  1229. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1230. result, stdout, stderr = self._run_cli("help", "-a")
  1231. log_output = "\n".join(cm.output)
  1232. self.assertIn("Available commands:", log_output)
  1233. self.assertIn("add", log_output)
  1234. self.assertIn("commit", log_output)
  1235. class RemoteCommandTest(DulwichCliTestCase):
  1236. """Tests for remote commands."""
  1237. def test_remote_add(self):
  1238. result, stdout, stderr = self._run_cli(
  1239. "remote", "add", "origin", "https://github.com/example/repo.git"
  1240. )
  1241. # Check remote was added to config
  1242. config = self.repo.get_config()
  1243. self.assertEqual(
  1244. config.get((b"remote", b"origin"), b"url"),
  1245. b"https://github.com/example/repo.git",
  1246. )
  1247. class CheckIgnoreCommandTest(DulwichCliTestCase):
  1248. """Tests for check-ignore command."""
  1249. def test_check_ignore(self):
  1250. # Create .gitignore
  1251. gitignore = os.path.join(self.repo_path, ".gitignore")
  1252. with open(gitignore, "w") as f:
  1253. f.write("*.log\n")
  1254. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1255. result, stdout, stderr = self._run_cli(
  1256. "check-ignore", "test.log", "test.txt"
  1257. )
  1258. log_output = "\n".join(cm.output)
  1259. self.assertIn("test.log", log_output)
  1260. self.assertNotIn("test.txt", log_output)
  1261. class LsFilesCommandTest(DulwichCliTestCase):
  1262. """Tests for ls-files command."""
  1263. def test_ls_files(self):
  1264. # Add some files
  1265. for name in ["a.txt", "b.txt", "c.txt"]:
  1266. path = os.path.join(self.repo_path, name)
  1267. with open(path, "w") as f:
  1268. f.write(f"content of {name}")
  1269. self._run_cli("add", "a.txt", "b.txt", "c.txt")
  1270. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1271. result, stdout, stderr = self._run_cli("ls-files")
  1272. log_output = "\n".join(cm.output)
  1273. self.assertIn("a.txt", log_output)
  1274. self.assertIn("b.txt", log_output)
  1275. self.assertIn("c.txt", log_output)
  1276. class LsTreeCommandTest(DulwichCliTestCase):
  1277. """Tests for ls-tree command."""
  1278. def test_ls_tree(self):
  1279. # Create a directory structure
  1280. os.mkdir(os.path.join(self.repo_path, "subdir"))
  1281. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  1282. f.write("file content")
  1283. with open(os.path.join(self.repo_path, "subdir", "nested.txt"), "w") as f:
  1284. f.write("nested content")
  1285. self._run_cli("add", ".")
  1286. self._run_cli("commit", "--message=Initial")
  1287. result, stdout, stderr = self._run_cli("ls-tree", "HEAD")
  1288. self.assertIn("file.txt", stdout)
  1289. self.assertIn("subdir", stdout)
  1290. def test_ls_tree_recursive(self):
  1291. # Create nested structure
  1292. os.mkdir(os.path.join(self.repo_path, "subdir"))
  1293. with open(os.path.join(self.repo_path, "subdir", "nested.txt"), "w") as f:
  1294. f.write("nested")
  1295. self._run_cli("add", ".")
  1296. self._run_cli("commit", "--message=Initial")
  1297. result, stdout, stderr = self._run_cli("ls-tree", "-r", "HEAD")
  1298. self.assertIn("subdir/nested.txt", stdout)
  1299. class DescribeCommandTest(DulwichCliTestCase):
  1300. """Tests for describe command."""
  1301. def test_describe(self):
  1302. # Create tagged commit
  1303. test_file = os.path.join(self.repo_path, "test.txt")
  1304. with open(test_file, "w") as f:
  1305. f.write("test")
  1306. self._run_cli("add", "test.txt")
  1307. self._run_cli("commit", "--message=Initial")
  1308. self._run_cli("tag", "v1.0")
  1309. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1310. result, stdout, stderr = self._run_cli("describe")
  1311. self.assertIn("v1.0", cm.output[0])
  1312. class FsckCommandTest(DulwichCliTestCase):
  1313. """Tests for fsck command."""
  1314. def test_fsck(self):
  1315. # Create a commit
  1316. test_file = os.path.join(self.repo_path, "test.txt")
  1317. with open(test_file, "w") as f:
  1318. f.write("test")
  1319. self._run_cli("add", "test.txt")
  1320. self._run_cli("commit", "--message=Initial")
  1321. result, stdout, stderr = self._run_cli("fsck")
  1322. # Should complete without errors
  1323. class RepackCommandTest(DulwichCliTestCase):
  1324. """Tests for repack command."""
  1325. def test_repack(self):
  1326. # Create some objects
  1327. for i in range(5):
  1328. test_file = os.path.join(self.repo_path, f"test{i}.txt")
  1329. with open(test_file, "w") as f:
  1330. f.write(f"content {i}")
  1331. self._run_cli("add", f"test{i}.txt")
  1332. self._run_cli("commit", f"--message=Commit {i}")
  1333. result, stdout, stderr = self._run_cli("repack")
  1334. # Should create pack files
  1335. pack_dir = os.path.join(self.repo_path, ".git", "objects", "pack")
  1336. self.assertTrue(any(f.endswith(".pack") for f in os.listdir(pack_dir)))
  1337. class ResetCommandTest(DulwichCliTestCase):
  1338. """Tests for reset command."""
  1339. def test_reset_soft(self):
  1340. # Create commits
  1341. test_file = os.path.join(self.repo_path, "test.txt")
  1342. with open(test_file, "w") as f:
  1343. f.write("first")
  1344. self._run_cli("add", "test.txt")
  1345. self._run_cli("commit", "--message=First")
  1346. first_commit = self.repo.head()
  1347. with open(test_file, "w") as f:
  1348. f.write("second")
  1349. self._run_cli("add", "test.txt")
  1350. self._run_cli("commit", "--message=Second")
  1351. # Reset soft
  1352. result, stdout, stderr = self._run_cli("reset", "--soft", first_commit.decode())
  1353. # HEAD should be at first commit
  1354. self.assertEqual(self.repo.head(), first_commit)
  1355. class WriteTreeCommandTest(DulwichCliTestCase):
  1356. """Tests for write-tree command."""
  1357. def test_write_tree(self):
  1358. # Create and add files
  1359. test_file = os.path.join(self.repo_path, "test.txt")
  1360. with open(test_file, "w") as f:
  1361. f.write("test")
  1362. self._run_cli("add", "test.txt")
  1363. result, stdout, stderr = self._run_cli("write-tree")
  1364. # Should output tree SHA
  1365. self.assertEqual(len(stdout.strip()), 40)
  1366. class UpdateServerInfoCommandTest(DulwichCliTestCase):
  1367. """Tests for update-server-info command."""
  1368. def test_update_server_info(self):
  1369. result, stdout, stderr = self._run_cli("update-server-info")
  1370. # Should create info/refs file
  1371. info_refs = os.path.join(self.repo_path, ".git", "info", "refs")
  1372. self.assertTrue(os.path.exists(info_refs))
  1373. class SymbolicRefCommandTest(DulwichCliTestCase):
  1374. """Tests for symbolic-ref command."""
  1375. def test_symbolic_ref(self):
  1376. # Create a branch
  1377. test_file = os.path.join(self.repo_path, "test.txt")
  1378. with open(test_file, "w") as f:
  1379. f.write("test")
  1380. self._run_cli("add", "test.txt")
  1381. self._run_cli("commit", "--message=Initial")
  1382. self._run_cli("branch", "test-branch")
  1383. result, stdout, stderr = self._run_cli(
  1384. "symbolic-ref", "HEAD", "refs/heads/test-branch"
  1385. )
  1386. # HEAD should now point to test-branch
  1387. self.assertEqual(
  1388. self.repo.refs.read_ref(b"HEAD"), b"ref: refs/heads/test-branch"
  1389. )
  1390. class BundleCommandTest(DulwichCliTestCase):
  1391. """Tests for bundle commands."""
  1392. def setUp(self):
  1393. super().setUp()
  1394. # Create a basic repository with some commits for bundle testing
  1395. # Create initial commit
  1396. test_file = os.path.join(self.repo_path, "file1.txt")
  1397. with open(test_file, "w") as f:
  1398. f.write("Content of file1\n")
  1399. self._run_cli("add", "file1.txt")
  1400. self._run_cli("commit", "--message=Initial commit")
  1401. # Create second commit
  1402. test_file2 = os.path.join(self.repo_path, "file2.txt")
  1403. with open(test_file2, "w") as f:
  1404. f.write("Content of file2\n")
  1405. self._run_cli("add", "file2.txt")
  1406. self._run_cli("commit", "--message=Add file2")
  1407. # Create a branch and tag for testing
  1408. self._run_cli("branch", "feature")
  1409. self._run_cli("tag", "v1.0")
  1410. def test_bundle_create_basic(self):
  1411. """Test basic bundle creation."""
  1412. bundle_file = os.path.join(self.test_dir, "test.bundle")
  1413. result, stdout, stderr = self._run_cli("bundle", "create", bundle_file, "HEAD")
  1414. self.assertEqual(result, 0)
  1415. self.assertTrue(os.path.exists(bundle_file))
  1416. self.assertGreater(os.path.getsize(bundle_file), 0)
  1417. def test_bundle_create_all_refs(self):
  1418. """Test bundle creation with --all flag."""
  1419. bundle_file = os.path.join(self.test_dir, "all.bundle")
  1420. result, stdout, stderr = self._run_cli("bundle", "create", "--all", bundle_file)
  1421. self.assertEqual(result, 0)
  1422. self.assertTrue(os.path.exists(bundle_file))
  1423. def test_bundle_create_specific_refs(self):
  1424. """Test bundle creation with specific refs."""
  1425. bundle_file = os.path.join(self.test_dir, "refs.bundle")
  1426. # Only use HEAD since feature branch may not exist
  1427. result, stdout, stderr = self._run_cli("bundle", "create", bundle_file, "HEAD")
  1428. self.assertEqual(result, 0)
  1429. self.assertTrue(os.path.exists(bundle_file))
  1430. def test_bundle_create_with_range(self):
  1431. """Test bundle creation with commit range."""
  1432. # Get the first commit SHA by looking at the log
  1433. result, stdout, stderr = self._run_cli("log", "--reverse")
  1434. lines = stdout.strip().split("\n")
  1435. # Find first commit line that contains a SHA
  1436. first_commit = None
  1437. for line in lines:
  1438. if line.startswith("commit "):
  1439. first_commit = line.split()[1][:8] # Get short SHA
  1440. break
  1441. if first_commit:
  1442. bundle_file = os.path.join(self.test_dir, "range.bundle")
  1443. result, stdout, stderr = self._run_cli(
  1444. "bundle", "create", bundle_file, f"{first_commit}..HEAD"
  1445. )
  1446. self.assertEqual(result, 0)
  1447. self.assertTrue(os.path.exists(bundle_file))
  1448. else:
  1449. self.skipTest("Could not determine first commit SHA")
  1450. def test_bundle_create_to_stdout(self):
  1451. """Test bundle creation to stdout."""
  1452. result, stdout, stderr = self._run_cli("bundle", "create", "-", "HEAD")
  1453. self.assertEqual(result, 0)
  1454. self.assertGreater(len(stdout), 0)
  1455. # Bundle output is binary, so check it's not empty
  1456. self.assertIsInstance(stdout, (str, bytes))
  1457. def test_bundle_create_no_refs(self):
  1458. """Test bundle creation with no refs specified."""
  1459. bundle_file = os.path.join(self.test_dir, "noref.bundle")
  1460. with self.assertLogs("dulwich.cli", level="ERROR") as cm:
  1461. result, stdout, stderr = self._run_cli("bundle", "create", bundle_file)
  1462. self.assertEqual(result, 1)
  1463. self.assertIn("No refs specified", cm.output[0])
  1464. def test_bundle_create_empty_bundle_refused(self):
  1465. """Test that empty bundles are refused."""
  1466. bundle_file = os.path.join(self.test_dir, "empty.bundle")
  1467. # Try to create bundle with non-existent ref - this should fail with KeyError
  1468. with self.assertRaises(KeyError):
  1469. result, stdout, stderr = self._run_cli(
  1470. "bundle", "create", bundle_file, "nonexistent-ref"
  1471. )
  1472. def test_bundle_verify_valid(self):
  1473. """Test bundle verification of valid bundle."""
  1474. bundle_file = os.path.join(self.test_dir, "valid.bundle")
  1475. # First create a bundle
  1476. result, stdout, stderr = self._run_cli("bundle", "create", bundle_file, "HEAD")
  1477. self.assertEqual(result, 0)
  1478. # Now verify it
  1479. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1480. result, stdout, stderr = self._run_cli("bundle", "verify", bundle_file)
  1481. self.assertEqual(result, 0)
  1482. self.assertIn("valid and can be applied", cm.output[0])
  1483. def test_bundle_verify_quiet(self):
  1484. """Test bundle verification with quiet flag."""
  1485. bundle_file = os.path.join(self.test_dir, "quiet.bundle")
  1486. # Create bundle
  1487. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1488. # Verify quietly
  1489. result, stdout, stderr = self._run_cli(
  1490. "bundle", "verify", "--quiet", bundle_file
  1491. )
  1492. self.assertEqual(result, 0)
  1493. self.assertEqual(stdout.strip(), "")
  1494. def test_bundle_verify_from_stdin(self):
  1495. """Test bundle verification from stdin."""
  1496. bundle_file = os.path.join(self.test_dir, "stdin.bundle")
  1497. # Create bundle
  1498. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1499. # Read bundle content
  1500. with open(bundle_file, "rb") as f:
  1501. bundle_content = f.read()
  1502. # Mock stdin with bundle content
  1503. old_stdin = sys.stdin
  1504. try:
  1505. sys.stdin = io.BytesIO(bundle_content)
  1506. sys.stdin.buffer = sys.stdin
  1507. result, stdout, stderr = self._run_cli("bundle", "verify", "-")
  1508. self.assertEqual(result, 0)
  1509. finally:
  1510. sys.stdin = old_stdin
  1511. def test_bundle_list_heads(self):
  1512. """Test listing bundle heads."""
  1513. bundle_file = os.path.join(self.test_dir, "heads.bundle")
  1514. # Create bundle with HEAD only
  1515. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1516. # List heads
  1517. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1518. result, stdout, stderr = self._run_cli("bundle", "list-heads", bundle_file)
  1519. self.assertEqual(result, 0)
  1520. # Should contain at least the HEAD reference
  1521. self.assertTrue(len(cm.output) > 0)
  1522. def test_bundle_list_heads_specific_refs(self):
  1523. """Test listing specific bundle heads."""
  1524. bundle_file = os.path.join(self.test_dir, "specific.bundle")
  1525. # Create bundle with HEAD
  1526. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1527. # List heads without filtering
  1528. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1529. result, stdout, stderr = self._run_cli("bundle", "list-heads", bundle_file)
  1530. self.assertEqual(result, 0)
  1531. # Should contain some reference
  1532. self.assertTrue(len(cm.output) > 0)
  1533. def test_bundle_list_heads_from_stdin(self):
  1534. """Test listing bundle heads from stdin."""
  1535. bundle_file = os.path.join(self.test_dir, "stdin-heads.bundle")
  1536. # Create bundle
  1537. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1538. # Read bundle content
  1539. with open(bundle_file, "rb") as f:
  1540. bundle_content = f.read()
  1541. # Mock stdin
  1542. old_stdin = sys.stdin
  1543. try:
  1544. sys.stdin = io.BytesIO(bundle_content)
  1545. sys.stdin.buffer = sys.stdin
  1546. result, stdout, stderr = self._run_cli("bundle", "list-heads", "-")
  1547. self.assertEqual(result, 0)
  1548. finally:
  1549. sys.stdin = old_stdin
  1550. def test_bundle_unbundle(self):
  1551. """Test bundle unbundling."""
  1552. bundle_file = os.path.join(self.test_dir, "unbundle.bundle")
  1553. # Create bundle
  1554. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1555. # Unbundle
  1556. result, stdout, stderr = self._run_cli("bundle", "unbundle", bundle_file)
  1557. self.assertEqual(result, 0)
  1558. def test_bundle_unbundle_specific_refs(self):
  1559. """Test unbundling specific refs."""
  1560. bundle_file = os.path.join(self.test_dir, "unbundle-specific.bundle")
  1561. # Create bundle with HEAD
  1562. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1563. # Unbundle only HEAD
  1564. result, stdout, stderr = self._run_cli(
  1565. "bundle", "unbundle", bundle_file, "HEAD"
  1566. )
  1567. self.assertEqual(result, 0)
  1568. def test_bundle_unbundle_from_stdin(self):
  1569. """Test unbundling from stdin."""
  1570. bundle_file = os.path.join(self.test_dir, "stdin-unbundle.bundle")
  1571. # Create bundle
  1572. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1573. # Read bundle content to simulate stdin
  1574. with open(bundle_file, "rb") as f:
  1575. bundle_content = f.read()
  1576. # Mock stdin with bundle content
  1577. old_stdin = sys.stdin
  1578. try:
  1579. # Create a BytesIO object with buffer attribute
  1580. mock_stdin = io.BytesIO(bundle_content)
  1581. mock_stdin.buffer = mock_stdin
  1582. sys.stdin = mock_stdin
  1583. result, stdout, stderr = self._run_cli("bundle", "unbundle", "-")
  1584. self.assertEqual(result, 0)
  1585. finally:
  1586. sys.stdin = old_stdin
  1587. def test_bundle_unbundle_with_progress(self):
  1588. """Test unbundling with progress output."""
  1589. bundle_file = os.path.join(self.test_dir, "progress.bundle")
  1590. # Create bundle
  1591. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1592. # Unbundle with progress
  1593. result, stdout, stderr = self._run_cli(
  1594. "bundle", "unbundle", "--progress", bundle_file
  1595. )
  1596. self.assertEqual(result, 0)
  1597. def test_bundle_create_with_progress(self):
  1598. """Test bundle creation with progress output."""
  1599. bundle_file = os.path.join(self.test_dir, "create-progress.bundle")
  1600. result, stdout, stderr = self._run_cli(
  1601. "bundle", "create", "--progress", bundle_file, "HEAD"
  1602. )
  1603. self.assertEqual(result, 0)
  1604. self.assertTrue(os.path.exists(bundle_file))
  1605. def test_bundle_create_with_quiet(self):
  1606. """Test bundle creation with quiet flag."""
  1607. bundle_file = os.path.join(self.test_dir, "quiet-create.bundle")
  1608. result, stdout, stderr = self._run_cli(
  1609. "bundle", "create", "--quiet", bundle_file, "HEAD"
  1610. )
  1611. self.assertEqual(result, 0)
  1612. self.assertTrue(os.path.exists(bundle_file))
  1613. def test_bundle_create_version_2(self):
  1614. """Test bundle creation with specific version."""
  1615. bundle_file = os.path.join(self.test_dir, "v2.bundle")
  1616. result, stdout, stderr = self._run_cli(
  1617. "bundle", "create", "--version", "2", bundle_file, "HEAD"
  1618. )
  1619. self.assertEqual(result, 0)
  1620. self.assertTrue(os.path.exists(bundle_file))
  1621. def test_bundle_create_version_3(self):
  1622. """Test bundle creation with version 3."""
  1623. bundle_file = os.path.join(self.test_dir, "v3.bundle")
  1624. result, stdout, stderr = self._run_cli(
  1625. "bundle", "create", "--version", "3", bundle_file, "HEAD"
  1626. )
  1627. self.assertEqual(result, 0)
  1628. self.assertTrue(os.path.exists(bundle_file))
  1629. def test_bundle_invalid_subcommand(self):
  1630. """Test invalid bundle subcommand."""
  1631. with self.assertLogs("dulwich.cli", level="ERROR") as cm:
  1632. result, stdout, stderr = self._run_cli("bundle", "invalid-command")
  1633. self.assertEqual(result, 1)
  1634. self.assertIn("Unknown bundle subcommand", cm.output[0])
  1635. def test_bundle_no_subcommand(self):
  1636. """Test bundle command with no subcommand."""
  1637. with self.assertLogs("dulwich.cli", level="ERROR") as cm:
  1638. result, stdout, stderr = self._run_cli("bundle")
  1639. self.assertEqual(result, 1)
  1640. self.assertIn("Usage: bundle", cm.output[0])
  1641. def test_bundle_create_with_stdin_refs(self):
  1642. """Test bundle creation reading refs from stdin."""
  1643. bundle_file = os.path.join(self.test_dir, "stdin-refs.bundle")
  1644. # Mock stdin with refs
  1645. old_stdin = sys.stdin
  1646. try:
  1647. sys.stdin = io.StringIO("master\nfeature\n")
  1648. result, stdout, stderr = self._run_cli(
  1649. "bundle", "create", "--stdin", bundle_file
  1650. )
  1651. self.assertEqual(result, 0)
  1652. self.assertTrue(os.path.exists(bundle_file))
  1653. finally:
  1654. sys.stdin = old_stdin
  1655. def test_bundle_verify_missing_prerequisites(self):
  1656. """Test bundle verification with missing prerequisites."""
  1657. # Create a simple bundle first
  1658. bundle_file = os.path.join(self.test_dir, "prereq.bundle")
  1659. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1660. # Create a new repo to simulate missing objects
  1661. new_repo_path = os.path.join(self.test_dir, "new_repo")
  1662. os.mkdir(new_repo_path)
  1663. new_repo = Repo.init(new_repo_path)
  1664. new_repo.close()
  1665. # Try to verify in new repo
  1666. old_cwd = os.getcwd()
  1667. try:
  1668. os.chdir(new_repo_path)
  1669. result, stdout, stderr = self._run_cli("bundle", "verify", bundle_file)
  1670. # Just check that verification runs - result depends on bundle content
  1671. self.assertIn(result, [0, 1])
  1672. finally:
  1673. os.chdir(old_cwd)
  1674. def test_bundle_create_with_committish_range(self):
  1675. """Test bundle creation with commit range using parse_committish_range."""
  1676. # Create additional commits for range testing
  1677. test_file3 = os.path.join(self.repo_path, "file3.txt")
  1678. with open(test_file3, "w") as f:
  1679. f.write("Content of file3\n")
  1680. self._run_cli("add", "file3.txt")
  1681. self._run_cli("commit", "--message=Add file3")
  1682. # Get commit SHAs
  1683. result, stdout, stderr = self._run_cli("log")
  1684. lines = stdout.strip().split("\n")
  1685. # Extract SHAs from commit lines
  1686. commits = []
  1687. for line in lines:
  1688. if line.startswith("commit:"):
  1689. sha = line.split()[1]
  1690. commits.append(sha[:8]) # Get short SHA
  1691. # We should have exactly 3 commits: Add file3, Add file2, Initial commit
  1692. self.assertEqual(len(commits), 3)
  1693. bundle_file = os.path.join(self.test_dir, "range-test.bundle")
  1694. # Test with commit range using .. syntax
  1695. # Create a bundle containing commits reachable from commits[0] but not from commits[2]
  1696. result, stdout, stderr = self._run_cli(
  1697. "bundle", "create", bundle_file, f"{commits[2]}..HEAD"
  1698. )
  1699. if result != 0:
  1700. self.fail(
  1701. f"Bundle create failed with exit code {result}. stdout: {stdout!r}, stderr: {stderr!r}"
  1702. )
  1703. self.assertEqual(result, 0)
  1704. self.assertTrue(os.path.exists(bundle_file))
  1705. # Verify the bundle was created
  1706. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1707. result, stdout, stderr = self._run_cli("bundle", "verify", bundle_file)
  1708. self.assertEqual(result, 0)
  1709. self.assertIn("valid and can be applied", cm.output[0])
  1710. class FormatBytesTestCase(TestCase):
  1711. """Tests for format_bytes function."""
  1712. def test_bytes(self):
  1713. """Test formatting bytes."""
  1714. self.assertEqual("0.0 B", format_bytes(0))
  1715. self.assertEqual("1.0 B", format_bytes(1))
  1716. self.assertEqual("512.0 B", format_bytes(512))
  1717. self.assertEqual("1023.0 B", format_bytes(1023))
  1718. def test_kilobytes(self):
  1719. """Test formatting kilobytes."""
  1720. self.assertEqual("1.0 KB", format_bytes(1024))
  1721. self.assertEqual("1.5 KB", format_bytes(1536))
  1722. self.assertEqual("2.0 KB", format_bytes(2048))
  1723. self.assertEqual("1023.0 KB", format_bytes(1024 * 1023))
  1724. def test_megabytes(self):
  1725. """Test formatting megabytes."""
  1726. self.assertEqual("1.0 MB", format_bytes(1024 * 1024))
  1727. self.assertEqual("1.5 MB", format_bytes(1024 * 1024 * 1.5))
  1728. self.assertEqual("10.0 MB", format_bytes(1024 * 1024 * 10))
  1729. self.assertEqual("1023.0 MB", format_bytes(1024 * 1024 * 1023))
  1730. def test_gigabytes(self):
  1731. """Test formatting gigabytes."""
  1732. self.assertEqual("1.0 GB", format_bytes(1024 * 1024 * 1024))
  1733. self.assertEqual("2.5 GB", format_bytes(1024 * 1024 * 1024 * 2.5))
  1734. self.assertEqual("1023.0 GB", format_bytes(1024 * 1024 * 1024 * 1023))
  1735. def test_terabytes(self):
  1736. """Test formatting terabytes."""
  1737. self.assertEqual("1.0 TB", format_bytes(1024 * 1024 * 1024 * 1024))
  1738. self.assertEqual("5.0 TB", format_bytes(1024 * 1024 * 1024 * 1024 * 5))
  1739. self.assertEqual("1000.0 TB", format_bytes(1024 * 1024 * 1024 * 1024 * 1000))
  1740. class ParseRelativeTimeTestCase(TestCase):
  1741. """Tests for parse_relative_time function."""
  1742. def test_now(self):
  1743. """Test parsing 'now'."""
  1744. self.assertEqual(0, parse_relative_time("now"))
  1745. def test_seconds(self):
  1746. """Test parsing seconds."""
  1747. self.assertEqual(1, parse_relative_time("1 second ago"))
  1748. self.assertEqual(5, parse_relative_time("5 seconds ago"))
  1749. self.assertEqual(30, parse_relative_time("30 seconds ago"))
  1750. def test_minutes(self):
  1751. """Test parsing minutes."""
  1752. self.assertEqual(60, parse_relative_time("1 minute ago"))
  1753. self.assertEqual(300, parse_relative_time("5 minutes ago"))
  1754. self.assertEqual(1800, parse_relative_time("30 minutes ago"))
  1755. def test_hours(self):
  1756. """Test parsing hours."""
  1757. self.assertEqual(3600, parse_relative_time("1 hour ago"))
  1758. self.assertEqual(7200, parse_relative_time("2 hours ago"))
  1759. self.assertEqual(86400, parse_relative_time("24 hours ago"))
  1760. def test_days(self):
  1761. """Test parsing days."""
  1762. self.assertEqual(86400, parse_relative_time("1 day ago"))
  1763. self.assertEqual(604800, parse_relative_time("7 days ago"))
  1764. self.assertEqual(2592000, parse_relative_time("30 days ago"))
  1765. def test_weeks(self):
  1766. """Test parsing weeks."""
  1767. self.assertEqual(604800, parse_relative_time("1 week ago"))
  1768. self.assertEqual(1209600, parse_relative_time("2 weeks ago"))
  1769. self.assertEqual(
  1770. 36288000, parse_relative_time("60 weeks ago")
  1771. ) # 60 * 7 * 24 * 60 * 60
  1772. def test_invalid_format(self):
  1773. """Test invalid time formats."""
  1774. with self.assertRaises(ValueError) as cm:
  1775. parse_relative_time("invalid")
  1776. self.assertIn("Invalid relative time format", str(cm.exception))
  1777. with self.assertRaises(ValueError) as cm:
  1778. parse_relative_time("2 weeks")
  1779. self.assertIn("Invalid relative time format", str(cm.exception))
  1780. with self.assertRaises(ValueError) as cm:
  1781. parse_relative_time("ago")
  1782. self.assertIn("Invalid relative time format", str(cm.exception))
  1783. with self.assertRaises(ValueError) as cm:
  1784. parse_relative_time("two weeks ago")
  1785. self.assertIn("Invalid number in relative time", str(cm.exception))
  1786. def test_invalid_unit(self):
  1787. """Test invalid time units."""
  1788. with self.assertRaises(ValueError) as cm:
  1789. parse_relative_time("5 months ago")
  1790. self.assertIn("Unknown time unit: months", str(cm.exception))
  1791. with self.assertRaises(ValueError) as cm:
  1792. parse_relative_time("2 years ago")
  1793. self.assertIn("Unknown time unit: years", str(cm.exception))
  1794. def test_singular_plural(self):
  1795. """Test that both singular and plural forms work."""
  1796. self.assertEqual(
  1797. parse_relative_time("1 second ago"), parse_relative_time("1 seconds ago")
  1798. )
  1799. self.assertEqual(
  1800. parse_relative_time("1 minute ago"), parse_relative_time("1 minutes ago")
  1801. )
  1802. self.assertEqual(
  1803. parse_relative_time("1 hour ago"), parse_relative_time("1 hours ago")
  1804. )
  1805. self.assertEqual(
  1806. parse_relative_time("1 day ago"), parse_relative_time("1 days ago")
  1807. )
  1808. self.assertEqual(
  1809. parse_relative_time("1 week ago"), parse_relative_time("1 weeks ago")
  1810. )
  1811. class GetPagerTest(TestCase):
  1812. """Tests for get_pager function."""
  1813. def setUp(self):
  1814. super().setUp()
  1815. # Save original environment
  1816. self.original_env = os.environ.copy()
  1817. # Clear pager-related environment variables
  1818. for var in ["DULWICH_PAGER", "GIT_PAGER", "PAGER"]:
  1819. os.environ.pop(var, None)
  1820. # Reset the global pager disable flag
  1821. cli.get_pager._disabled = False
  1822. def tearDown(self):
  1823. super().tearDown()
  1824. # Restore original environment
  1825. os.environ.clear()
  1826. os.environ.update(self.original_env)
  1827. # Reset the global pager disable flag
  1828. cli.get_pager._disabled = False
  1829. def test_pager_disabled_globally(self):
  1830. """Test that globally disabled pager returns stdout wrapper."""
  1831. cli.disable_pager()
  1832. pager = cli.get_pager()
  1833. self.assertIsInstance(pager, cli._StreamContextAdapter)
  1834. self.assertEqual(pager.stream, sys.stdout)
  1835. def test_pager_not_tty(self):
  1836. """Test that pager is disabled when stdout is not a TTY."""
  1837. with patch("sys.stdout.isatty", return_value=False):
  1838. pager = cli.get_pager()
  1839. self.assertIsInstance(pager, cli._StreamContextAdapter)
  1840. def test_pager_env_dulwich_pager(self):
  1841. """Test DULWICH_PAGER environment variable."""
  1842. os.environ["DULWICH_PAGER"] = "custom_pager"
  1843. with patch("sys.stdout.isatty", return_value=True):
  1844. pager = cli.get_pager()
  1845. self.assertIsInstance(pager, cli.Pager)
  1846. self.assertEqual(pager.pager_cmd, "custom_pager")
  1847. def test_pager_env_dulwich_pager_false(self):
  1848. """Test DULWICH_PAGER=false disables pager."""
  1849. os.environ["DULWICH_PAGER"] = "false"
  1850. with patch("sys.stdout.isatty", return_value=True):
  1851. pager = cli.get_pager()
  1852. self.assertIsInstance(pager, cli._StreamContextAdapter)
  1853. def test_pager_env_git_pager(self):
  1854. """Test GIT_PAGER environment variable."""
  1855. os.environ["GIT_PAGER"] = "git_custom_pager"
  1856. with patch("sys.stdout.isatty", return_value=True):
  1857. pager = cli.get_pager()
  1858. self.assertIsInstance(pager, cli.Pager)
  1859. self.assertEqual(pager.pager_cmd, "git_custom_pager")
  1860. def test_pager_env_pager(self):
  1861. """Test PAGER environment variable."""
  1862. os.environ["PAGER"] = "my_pager"
  1863. with patch("sys.stdout.isatty", return_value=True):
  1864. pager = cli.get_pager()
  1865. self.assertIsInstance(pager, cli.Pager)
  1866. self.assertEqual(pager.pager_cmd, "my_pager")
  1867. def test_pager_env_priority(self):
  1868. """Test environment variable priority order."""
  1869. os.environ["PAGER"] = "pager_low"
  1870. os.environ["GIT_PAGER"] = "pager_medium"
  1871. os.environ["DULWICH_PAGER"] = "pager_high"
  1872. with patch("sys.stdout.isatty", return_value=True):
  1873. pager = cli.get_pager()
  1874. self.assertEqual(pager.pager_cmd, "pager_high")
  1875. def test_pager_config_core_pager(self):
  1876. """Test core.pager configuration."""
  1877. config = MagicMock()
  1878. config.get.return_value = b"config_pager"
  1879. with patch("sys.stdout.isatty", return_value=True):
  1880. pager = cli.get_pager(config=config)
  1881. self.assertIsInstance(pager, cli.Pager)
  1882. self.assertEqual(pager.pager_cmd, "config_pager")
  1883. config.get.assert_called_with(("core",), b"pager")
  1884. def test_pager_config_core_pager_false(self):
  1885. """Test core.pager=false disables pager."""
  1886. config = MagicMock()
  1887. config.get.return_value = b"false"
  1888. with patch("sys.stdout.isatty", return_value=True):
  1889. pager = cli.get_pager(config=config)
  1890. self.assertIsInstance(pager, cli._StreamContextAdapter)
  1891. def test_pager_config_core_pager_empty(self):
  1892. """Test core.pager="" disables pager."""
  1893. config = MagicMock()
  1894. config.get.return_value = b""
  1895. with patch("sys.stdout.isatty", return_value=True):
  1896. pager = cli.get_pager(config=config)
  1897. self.assertIsInstance(pager, cli._StreamContextAdapter)
  1898. def test_pager_config_per_command(self):
  1899. """Test per-command pager configuration."""
  1900. config = MagicMock()
  1901. config.get.side_effect = lambda section, key: {
  1902. (("pager",), b"log"): b"log_pager",
  1903. }.get((section, key), KeyError())
  1904. with patch("sys.stdout.isatty", return_value=True):
  1905. pager = cli.get_pager(config=config, cmd_name="log")
  1906. self.assertIsInstance(pager, cli.Pager)
  1907. self.assertEqual(pager.pager_cmd, "log_pager")
  1908. def test_pager_config_per_command_false(self):
  1909. """Test per-command pager=false disables pager."""
  1910. config = MagicMock()
  1911. config.get.return_value = b"false"
  1912. with patch("sys.stdout.isatty", return_value=True):
  1913. pager = cli.get_pager(config=config, cmd_name="log")
  1914. self.assertIsInstance(pager, cli._StreamContextAdapter)
  1915. def test_pager_config_per_command_true(self):
  1916. """Test per-command pager=true uses default pager."""
  1917. config = MagicMock()
  1918. def get_side_effect(section, key):
  1919. if section == ("pager",) and key == b"log":
  1920. return b"true"
  1921. raise KeyError
  1922. config.get.side_effect = get_side_effect
  1923. with patch("sys.stdout.isatty", return_value=True):
  1924. with patch("shutil.which", side_effect=lambda cmd: cmd == "less"):
  1925. pager = cli.get_pager(config=config, cmd_name="log")
  1926. self.assertIsInstance(pager, cli.Pager)
  1927. self.assertEqual(pager.pager_cmd, "less -FRX")
  1928. def test_pager_priority_order(self):
  1929. """Test complete priority order."""
  1930. # Set up all possible configurations
  1931. os.environ["PAGER"] = "env_pager"
  1932. os.environ["GIT_PAGER"] = "env_git_pager"
  1933. config = MagicMock()
  1934. def get_side_effect(section, key):
  1935. if section == ("pager",) and key == b"log":
  1936. return b"cmd_pager"
  1937. elif section == ("core",) and key == b"pager":
  1938. return b"core_pager"
  1939. raise KeyError
  1940. config.get.side_effect = get_side_effect
  1941. with patch("sys.stdout.isatty", return_value=True):
  1942. # Per-command config should win
  1943. pager = cli.get_pager(config=config, cmd_name="log")
  1944. self.assertEqual(pager.pager_cmd, "cmd_pager")
  1945. def test_pager_fallback_less(self):
  1946. """Test fallback to less with proper flags."""
  1947. with patch("sys.stdout.isatty", return_value=True):
  1948. with patch("shutil.which", side_effect=lambda cmd: cmd == "less"):
  1949. pager = cli.get_pager()
  1950. self.assertIsInstance(pager, cli.Pager)
  1951. self.assertEqual(pager.pager_cmd, "less -FRX")
  1952. def test_pager_fallback_more(self):
  1953. """Test fallback to more when less is not available."""
  1954. with patch("sys.stdout.isatty", return_value=True):
  1955. with patch("shutil.which", side_effect=lambda cmd: cmd == "more"):
  1956. pager = cli.get_pager()
  1957. self.assertIsInstance(pager, cli.Pager)
  1958. self.assertEqual(pager.pager_cmd, "more")
  1959. def test_pager_fallback_cat(self):
  1960. """Test ultimate fallback to cat."""
  1961. with patch("sys.stdout.isatty", return_value=True):
  1962. with patch("shutil.which", return_value=None):
  1963. pager = cli.get_pager()
  1964. self.assertIsInstance(pager, cli.Pager)
  1965. self.assertEqual(pager.pager_cmd, "cat")
  1966. def test_pager_context_manager(self):
  1967. """Test that pager works as a context manager."""
  1968. with patch("sys.stdout.isatty", return_value=True):
  1969. with cli.get_pager() as pager:
  1970. self.assertTrue(hasattr(pager, "write"))
  1971. self.assertTrue(hasattr(pager, "flush"))
  1972. class WorktreeCliTests(DulwichCliTestCase):
  1973. """Tests for worktree CLI commands."""
  1974. def setUp(self):
  1975. super().setUp()
  1976. # Base class already creates and initializes the repo
  1977. # Just create initial commit
  1978. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  1979. f.write("test content")
  1980. from dulwich import porcelain
  1981. porcelain.add(self.repo_path, ["test.txt"])
  1982. porcelain.commit(self.repo_path, message=b"Initial commit")
  1983. def test_worktree_list(self):
  1984. """Test worktree list command."""
  1985. # Change to repo directory
  1986. old_cwd = os.getcwd()
  1987. os.chdir(self.repo_path)
  1988. try:
  1989. io.StringIO()
  1990. cmd = cli.cmd_worktree()
  1991. result = cmd.run(["list"])
  1992. # Should list the main worktree
  1993. self.assertEqual(result, 0)
  1994. finally:
  1995. os.chdir(old_cwd)
  1996. def test_worktree_add(self):
  1997. """Test worktree add command."""
  1998. wt_path = os.path.join(self.test_dir, "worktree1")
  1999. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2000. result, stdout, stderr = self._run_cli(
  2001. "worktree", "add", wt_path, "feature"
  2002. )
  2003. self.assertEqual(result, 0)
  2004. self.assertTrue(os.path.exists(wt_path))
  2005. log_output = "\n".join(cm.output)
  2006. self.assertIn("Worktree added:", log_output)
  2007. def test_worktree_add_detached(self):
  2008. """Test worktree add with detached HEAD."""
  2009. wt_path = os.path.join(self.test_dir, "detached-wt")
  2010. # Change to repo directory
  2011. old_cwd = os.getcwd()
  2012. os.chdir(self.repo_path)
  2013. try:
  2014. cmd = cli.cmd_worktree()
  2015. with patch("sys.stdout", new_callable=io.StringIO):
  2016. result = cmd.run(["add", "--detach", wt_path])
  2017. self.assertEqual(result, 0)
  2018. self.assertTrue(os.path.exists(wt_path))
  2019. finally:
  2020. os.chdir(old_cwd)
  2021. def test_worktree_remove(self):
  2022. """Test worktree remove command."""
  2023. # First add a worktree
  2024. wt_path = os.path.join(self.test_dir, "to-remove")
  2025. result, stdout, stderr = self._run_cli("worktree", "add", wt_path)
  2026. self.assertEqual(result, 0)
  2027. # Then remove it
  2028. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2029. result, stdout, stderr = self._run_cli("worktree", "remove", wt_path)
  2030. self.assertEqual(result, 0)
  2031. self.assertFalse(os.path.exists(wt_path))
  2032. log_output = "\n".join(cm.output)
  2033. self.assertIn("Worktree removed:", log_output)
  2034. def test_worktree_prune(self):
  2035. """Test worktree prune command."""
  2036. # Add a worktree and manually remove it
  2037. wt_path = os.path.join(self.test_dir, "to-prune")
  2038. result, stdout, stderr = self._run_cli("worktree", "add", wt_path)
  2039. self.assertEqual(result, 0)
  2040. shutil.rmtree(wt_path)
  2041. # Prune
  2042. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2043. result, stdout, stderr = self._run_cli("worktree", "prune", "-v")
  2044. self.assertEqual(result, 0)
  2045. log_output = "\n".join(cm.output)
  2046. self.assertIn("to-prune", log_output)
  2047. def test_worktree_lock_unlock(self):
  2048. """Test worktree lock and unlock commands."""
  2049. # Add a worktree
  2050. wt_path = os.path.join(self.test_dir, "lockable")
  2051. result, stdout, stderr = self._run_cli("worktree", "add", wt_path)
  2052. self.assertEqual(result, 0)
  2053. # Lock it
  2054. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2055. result, stdout, stderr = self._run_cli(
  2056. "worktree", "lock", wt_path, "--reason", "Testing"
  2057. )
  2058. self.assertEqual(result, 0)
  2059. log_output = "\n".join(cm.output)
  2060. self.assertIn("Worktree locked:", log_output)
  2061. # Unlock it
  2062. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2063. result, stdout, stderr = self._run_cli("worktree", "unlock", wt_path)
  2064. self.assertEqual(result, 0)
  2065. log_output = "\n".join(cm.output)
  2066. self.assertIn("Worktree unlocked:", log_output)
  2067. def test_worktree_move(self):
  2068. """Test worktree move command."""
  2069. # Add a worktree
  2070. old_path = os.path.join(self.test_dir, "old-location")
  2071. new_path = os.path.join(self.test_dir, "new-location")
  2072. result, stdout, stderr = self._run_cli("worktree", "add", old_path)
  2073. self.assertEqual(result, 0)
  2074. # Move it
  2075. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2076. result, stdout, stderr = self._run_cli(
  2077. "worktree", "move", old_path, new_path
  2078. )
  2079. self.assertEqual(result, 0)
  2080. self.assertFalse(os.path.exists(old_path))
  2081. self.assertTrue(os.path.exists(new_path))
  2082. log_output = "\n".join(cm.output)
  2083. self.assertIn("Worktree moved:", log_output)
  2084. def test_worktree_invalid_command(self):
  2085. """Test invalid worktree subcommand."""
  2086. cmd = cli.cmd_worktree()
  2087. with patch("sys.stderr", new_callable=io.StringIO):
  2088. with self.assertRaises(SystemExit):
  2089. cmd.run(["invalid"])
  2090. if __name__ == "__main__":
  2091. unittest.main()