test_cli.py 92 KB

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