2
0

test_cli.py 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973
  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 public 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, 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 AddCommandTest(DulwichCliTestCase):
  101. """Tests for add command."""
  102. def test_add_single_file(self):
  103. # Create a file to add
  104. test_file = os.path.join(self.repo_path, "test.txt")
  105. with open(test_file, "w") as f:
  106. f.write("test content")
  107. result, stdout, stderr = self._run_cli("add", "test.txt")
  108. # Check that file is in index
  109. self.assertIn(b"test.txt", self.repo.open_index())
  110. def test_add_multiple_files(self):
  111. # Create multiple files
  112. for i in range(3):
  113. test_file = os.path.join(self.repo_path, f"test{i}.txt")
  114. with open(test_file, "w") as f:
  115. f.write(f"content {i}")
  116. result, stdout, stderr = self._run_cli(
  117. "add", "test0.txt", "test1.txt", "test2.txt"
  118. )
  119. index = self.repo.open_index()
  120. self.assertIn(b"test0.txt", index)
  121. self.assertIn(b"test1.txt", index)
  122. self.assertIn(b"test2.txt", index)
  123. class RmCommandTest(DulwichCliTestCase):
  124. """Tests for rm command."""
  125. def test_rm_file(self):
  126. # Create, add and commit a file first
  127. test_file = os.path.join(self.repo_path, "test.txt")
  128. with open(test_file, "w") as f:
  129. f.write("test content")
  130. self._run_cli("add", "test.txt")
  131. self._run_cli("commit", "--message=Add test file")
  132. # Now remove it from index and working directory
  133. result, stdout, stderr = self._run_cli("rm", "test.txt")
  134. # Check that file is not in index
  135. self.assertNotIn(b"test.txt", self.repo.open_index())
  136. class CommitCommandTest(DulwichCliTestCase):
  137. """Tests for commit command."""
  138. def test_commit_basic(self):
  139. # Create and add a file
  140. test_file = os.path.join(self.repo_path, "test.txt")
  141. with open(test_file, "w") as f:
  142. f.write("test content")
  143. self._run_cli("add", "test.txt")
  144. # Commit
  145. result, stdout, stderr = self._run_cli("commit", "--message=Initial commit")
  146. # Check that HEAD points to a commit
  147. self.assertIsNotNone(self.repo.head())
  148. class LogCommandTest(DulwichCliTestCase):
  149. """Tests for log command."""
  150. def test_log_empty_repo(self):
  151. result, stdout, stderr = self._run_cli("log")
  152. # Empty repo should not crash
  153. def test_log_with_commits(self):
  154. # Create some commits
  155. c1, c2, c3 = build_commit_graph(
  156. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  157. )
  158. self.repo.refs[b"HEAD"] = c3.id
  159. result, stdout, stderr = self._run_cli("log")
  160. self.assertIn("Commit 3", stdout)
  161. self.assertIn("Commit 2", stdout)
  162. self.assertIn("Commit 1", stdout)
  163. def test_log_reverse(self):
  164. # Create some commits
  165. c1, c2, c3 = build_commit_graph(
  166. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  167. )
  168. self.repo.refs[b"HEAD"] = c3.id
  169. result, stdout, stderr = self._run_cli("log", "--reverse")
  170. # Check order - commit 1 should appear before commit 3
  171. pos1 = stdout.index("Commit 1")
  172. pos3 = stdout.index("Commit 3")
  173. self.assertLess(pos1, pos3)
  174. class StatusCommandTest(DulwichCliTestCase):
  175. """Tests for status command."""
  176. def test_status_empty(self):
  177. result, stdout, stderr = self._run_cli("status")
  178. # Should not crash on empty repo
  179. def test_status_with_untracked(self):
  180. # Create an untracked file
  181. test_file = os.path.join(self.repo_path, "untracked.txt")
  182. with open(test_file, "w") as f:
  183. f.write("untracked content")
  184. result, stdout, stderr = self._run_cli("status")
  185. self.assertIn("Untracked files:", stdout)
  186. self.assertIn("untracked.txt", stdout)
  187. class BranchCommandTest(DulwichCliTestCase):
  188. """Tests for branch command."""
  189. def test_branch_create(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("test")
  194. self._run_cli("add", "test.txt")
  195. self._run_cli("commit", "--message=Initial")
  196. # Create branch
  197. result, stdout, stderr = self._run_cli("branch", "test-branch")
  198. self.assertIn(b"refs/heads/test-branch", self.repo.refs.keys())
  199. def test_branch_delete(self):
  200. # Create initial commit and branch
  201. test_file = os.path.join(self.repo_path, "test.txt")
  202. with open(test_file, "w") as f:
  203. f.write("test")
  204. self._run_cli("add", "test.txt")
  205. self._run_cli("commit", "--message=Initial")
  206. self._run_cli("branch", "test-branch")
  207. # Delete branch
  208. result, stdout, stderr = self._run_cli("branch", "-d", "test-branch")
  209. self.assertNotIn(b"refs/heads/test-branch", self.repo.refs.keys())
  210. class CheckoutCommandTest(DulwichCliTestCase):
  211. """Tests for checkout command."""
  212. def test_checkout_branch(self):
  213. # Create initial commit and branch
  214. test_file = os.path.join(self.repo_path, "test.txt")
  215. with open(test_file, "w") as f:
  216. f.write("test")
  217. self._run_cli("add", "test.txt")
  218. self._run_cli("commit", "--message=Initial")
  219. self._run_cli("branch", "test-branch")
  220. # Checkout branch
  221. result, stdout, stderr = self._run_cli("checkout", "test-branch")
  222. self.assertEqual(
  223. self.repo.refs.read_ref(b"HEAD"), b"ref: refs/heads/test-branch"
  224. )
  225. class TagCommandTest(DulwichCliTestCase):
  226. """Tests for tag command."""
  227. def test_tag_create(self):
  228. # Create initial commit
  229. test_file = os.path.join(self.repo_path, "test.txt")
  230. with open(test_file, "w") as f:
  231. f.write("test")
  232. self._run_cli("add", "test.txt")
  233. self._run_cli("commit", "--message=Initial")
  234. # Create tag
  235. result, stdout, stderr = self._run_cli("tag", "v1.0")
  236. self.assertIn(b"refs/tags/v1.0", self.repo.refs.keys())
  237. class DiffCommandTest(DulwichCliTestCase):
  238. """Tests for diff command."""
  239. def test_diff_working_tree(self):
  240. # Create and commit a file
  241. test_file = os.path.join(self.repo_path, "test.txt")
  242. with open(test_file, "w") as f:
  243. f.write("initial content\n")
  244. self._run_cli("add", "test.txt")
  245. self._run_cli("commit", "--message=Initial")
  246. # Modify the file
  247. with open(test_file, "w") as f:
  248. f.write("initial content\nmodified\n")
  249. # Test unstaged diff
  250. result, stdout, stderr = self._run_cli("diff")
  251. self.assertIn("+modified", stdout)
  252. def test_diff_staged(self):
  253. # Create initial commit
  254. test_file = os.path.join(self.repo_path, "test.txt")
  255. with open(test_file, "w") as f:
  256. f.write("initial content\n")
  257. self._run_cli("add", "test.txt")
  258. self._run_cli("commit", "--message=Initial")
  259. # Modify and stage the file
  260. with open(test_file, "w") as f:
  261. f.write("initial content\nnew file\n")
  262. self._run_cli("add", "test.txt")
  263. # Test staged diff
  264. result, stdout, stderr = self._run_cli("diff", "--staged")
  265. self.assertIn("+new file", stdout)
  266. def test_diff_cached(self):
  267. # Create initial commit
  268. test_file = os.path.join(self.repo_path, "test.txt")
  269. with open(test_file, "w") as f:
  270. f.write("initial content\n")
  271. self._run_cli("add", "test.txt")
  272. self._run_cli("commit", "--message=Initial")
  273. # Modify and stage the file
  274. with open(test_file, "w") as f:
  275. f.write("initial content\nnew file\n")
  276. self._run_cli("add", "test.txt")
  277. # Test cached diff (alias for staged)
  278. result, stdout, stderr = self._run_cli("diff", "--cached")
  279. self.assertIn("+new file", stdout)
  280. def test_diff_commit(self):
  281. # Create two commits
  282. test_file = os.path.join(self.repo_path, "test.txt")
  283. with open(test_file, "w") as f:
  284. f.write("first version\n")
  285. self._run_cli("add", "test.txt")
  286. self._run_cli("commit", "--message=First")
  287. with open(test_file, "w") as f:
  288. f.write("first version\nsecond line\n")
  289. self._run_cli("add", "test.txt")
  290. self._run_cli("commit", "--message=Second")
  291. # Add working tree changes
  292. with open(test_file, "a") as f:
  293. f.write("working tree change\n")
  294. # Test single commit diff (should show working tree vs HEAD)
  295. result, stdout, stderr = self._run_cli("diff", "HEAD")
  296. self.assertIn("+working tree change", stdout)
  297. def test_diff_two_commits(self):
  298. # Create two commits
  299. test_file = os.path.join(self.repo_path, "test.txt")
  300. with open(test_file, "w") as f:
  301. f.write("first version\n")
  302. self._run_cli("add", "test.txt")
  303. self._run_cli("commit", "--message=First")
  304. # Get first commit SHA
  305. first_commit = self.repo.refs[b"HEAD"].decode()
  306. with open(test_file, "w") as f:
  307. f.write("first version\nsecond line\n")
  308. self._run_cli("add", "test.txt")
  309. self._run_cli("commit", "--message=Second")
  310. # Get second commit SHA
  311. second_commit = self.repo.refs[b"HEAD"].decode()
  312. # Test diff between two commits
  313. result, stdout, stderr = self._run_cli("diff", first_commit, second_commit)
  314. self.assertIn("+second line", stdout)
  315. def test_diff_commit_vs_working_tree(self):
  316. # Test that diff <commit> shows working tree vs commit (not commit vs parent)
  317. test_file = os.path.join(self.repo_path, "test.txt")
  318. with open(test_file, "w") as f:
  319. f.write("first version\n")
  320. self._run_cli("add", "test.txt")
  321. self._run_cli("commit", "--message=First")
  322. first_commit = self.repo.refs[b"HEAD"].decode()
  323. with open(test_file, "w") as f:
  324. f.write("first version\nsecond line\n")
  325. self._run_cli("add", "test.txt")
  326. self._run_cli("commit", "--message=Second")
  327. # Add changes to working tree
  328. with open(test_file, "w") as f:
  329. f.write("completely different\n")
  330. # diff <first_commit> should show working tree vs first commit
  331. result, stdout, stderr = self._run_cli("diff", first_commit)
  332. self.assertIn("-first version", stdout)
  333. self.assertIn("+completely different", stdout)
  334. def test_diff_with_paths(self):
  335. # Test path filtering
  336. # Create multiple files
  337. file1 = os.path.join(self.repo_path, "file1.txt")
  338. file2 = os.path.join(self.repo_path, "file2.txt")
  339. subdir = os.path.join(self.repo_path, "subdir")
  340. os.makedirs(subdir)
  341. file3 = os.path.join(subdir, "file3.txt")
  342. with open(file1, "w") as f:
  343. f.write("content1\n")
  344. with open(file2, "w") as f:
  345. f.write("content2\n")
  346. with open(file3, "w") as f:
  347. f.write("content3\n")
  348. self._run_cli("add", ".")
  349. self._run_cli("commit", "--message=Initial")
  350. # Modify all files
  351. with open(file1, "w") as f:
  352. f.write("modified1\n")
  353. with open(file2, "w") as f:
  354. f.write("modified2\n")
  355. with open(file3, "w") as f:
  356. f.write("modified3\n")
  357. # Test diff with specific file
  358. result, stdout, stderr = self._run_cli("diff", "--", "file1.txt")
  359. self.assertIn("file1.txt", stdout)
  360. self.assertNotIn("file2.txt", stdout)
  361. self.assertNotIn("file3.txt", stdout)
  362. # Test diff with directory
  363. result, stdout, stderr = self._run_cli("diff", "--", "subdir")
  364. self.assertNotIn("file1.txt", stdout)
  365. self.assertNotIn("file2.txt", stdout)
  366. self.assertIn("file3.txt", stdout)
  367. # Test staged diff with paths
  368. self._run_cli("add", "file1.txt")
  369. result, stdout, stderr = self._run_cli("diff", "--staged", "--", "file1.txt")
  370. self.assertIn("file1.txt", stdout)
  371. self.assertIn("+modified1", stdout)
  372. # Test diff with multiple paths (file2 and file3 are still unstaged)
  373. result, stdout, stderr = self._run_cli(
  374. "diff", "--", "file2.txt", "subdir/file3.txt"
  375. )
  376. self.assertIn("file2.txt", stdout)
  377. self.assertIn("file3.txt", stdout)
  378. self.assertNotIn("file1.txt", stdout)
  379. # Test diff with commit and paths
  380. first_commit = self.repo.refs[b"HEAD"].decode()
  381. with open(file1, "w") as f:
  382. f.write("newer1\n")
  383. result, stdout, stderr = self._run_cli("diff", first_commit, "--", "file1.txt")
  384. self.assertIn("file1.txt", stdout)
  385. self.assertIn("-content1", stdout)
  386. self.assertIn("+newer1", stdout)
  387. self.assertNotIn("file2.txt", stdout)
  388. class FilterBranchCommandTest(DulwichCliTestCase):
  389. """Tests for filter-branch command."""
  390. def setUp(self):
  391. super().setUp()
  392. # Create a more complex repository structure for testing
  393. # Create some files in subdirectories
  394. os.makedirs(os.path.join(self.repo_path, "subdir"))
  395. os.makedirs(os.path.join(self.repo_path, "other"))
  396. # Create files
  397. files = {
  398. "README.md": "# Test Repo",
  399. "subdir/file1.txt": "File in subdir",
  400. "subdir/file2.txt": "Another file in subdir",
  401. "other/file3.txt": "File in other dir",
  402. "root.txt": "File at root",
  403. }
  404. for path, content in files.items():
  405. file_path = os.path.join(self.repo_path, path)
  406. with open(file_path, "w") as f:
  407. f.write(content)
  408. # Add all files and create initial commit
  409. self._run_cli("add", ".")
  410. self._run_cli("commit", "--message=Initial commit")
  411. # Create a second commit modifying subdir
  412. with open(os.path.join(self.repo_path, "subdir/file1.txt"), "a") as f:
  413. f.write("\nModified content")
  414. self._run_cli("add", "subdir/file1.txt")
  415. self._run_cli("commit", "--message=Modify subdir file")
  416. # Create a third commit in other dir
  417. with open(os.path.join(self.repo_path, "other/file3.txt"), "a") as f:
  418. f.write("\nMore content")
  419. self._run_cli("add", "other/file3.txt")
  420. self._run_cli("commit", "--message=Modify other file")
  421. # Create a branch
  422. self._run_cli("branch", "test-branch")
  423. # Create a tag
  424. self._run_cli("tag", "v1.0")
  425. def test_filter_branch_subdirectory_filter(self):
  426. """Test filter-branch with subdirectory filter."""
  427. # Run filter-branch to extract only the subdir
  428. result, stdout, stderr = self._run_cli(
  429. "filter-branch", "--subdirectory-filter", "subdir"
  430. )
  431. # Check that the operation succeeded
  432. self.assertEqual(result, 0)
  433. self.assertIn("Rewrite HEAD", stdout)
  434. # filter-branch rewrites history but doesn't update working tree
  435. # We need to check the commit contents, not the working tree
  436. # Reset to the rewritten HEAD to update working tree
  437. self._run_cli("reset", "--hard", "HEAD")
  438. # Now check that only files from subdir remain at root level
  439. self.assertTrue(os.path.exists(os.path.join(self.repo_path, "file1.txt")))
  440. self.assertTrue(os.path.exists(os.path.join(self.repo_path, "file2.txt")))
  441. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "README.md")))
  442. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "root.txt")))
  443. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "other")))
  444. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "subdir")))
  445. # Check that original refs were backed up
  446. original_refs = [
  447. ref for ref in self.repo.refs.keys() if ref.startswith(b"refs/original/")
  448. ]
  449. self.assertTrue(
  450. len(original_refs) > 0, "No original refs found after filter-branch"
  451. )
  452. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  453. def test_filter_branch_msg_filter(self):
  454. """Test filter-branch with message filter."""
  455. # Run filter-branch to prepend [FILTERED] to commit messages
  456. result, stdout, stderr = self._run_cli(
  457. "filter-branch", "--msg-filter", "sed 's/^/[FILTERED] /'"
  458. )
  459. self.assertEqual(result, 0)
  460. # Check that commit messages were modified
  461. result, stdout, stderr = self._run_cli("log")
  462. self.assertIn("[FILTERED] Modify other file", stdout)
  463. self.assertIn("[FILTERED] Modify subdir file", stdout)
  464. self.assertIn("[FILTERED] Initial commit", stdout)
  465. def test_filter_branch_env_filter(self):
  466. """Test filter-branch with environment filter."""
  467. # Run filter-branch to change author email
  468. env_filter = """
  469. if [ "$GIT_AUTHOR_EMAIL" = "test@example.com" ]; then
  470. export GIT_AUTHOR_EMAIL="filtered@example.com"
  471. fi
  472. """
  473. result, stdout, stderr = self._run_cli(
  474. "filter-branch", "--env-filter", env_filter
  475. )
  476. self.assertEqual(result, 0)
  477. def test_filter_branch_prune_empty(self):
  478. """Test filter-branch with prune-empty option."""
  479. # Create a commit that only touches files outside subdir
  480. with open(os.path.join(self.repo_path, "root.txt"), "a") as f:
  481. f.write("\nNew line")
  482. self._run_cli("add", "root.txt")
  483. self._run_cli("commit", "--message=Modify root file only")
  484. # Run filter-branch to extract subdir with prune-empty
  485. result, stdout, stderr = self._run_cli(
  486. "filter-branch", "--subdirectory-filter", "subdir", "--prune-empty"
  487. )
  488. self.assertEqual(result, 0)
  489. # The last commit should have been pruned
  490. result, stdout, stderr = self._run_cli("log")
  491. self.assertNotIn("Modify root file only", stdout)
  492. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  493. def test_filter_branch_force(self):
  494. """Test filter-branch with force option."""
  495. # Run filter-branch once with a filter that actually changes something
  496. result, stdout, stderr = self._run_cli(
  497. "filter-branch", "--msg-filter", "sed 's/^/[TEST] /'"
  498. )
  499. self.assertEqual(result, 0)
  500. # Check that backup refs were created
  501. # The implementation backs up refs under refs/original/
  502. original_refs = [
  503. ref for ref in self.repo.refs.keys() if ref.startswith(b"refs/original/")
  504. ]
  505. self.assertTrue(len(original_refs) > 0, "No original refs found")
  506. # Run again without force - should fail
  507. result, stdout, stderr = self._run_cli(
  508. "filter-branch", "--msg-filter", "sed 's/^/[TEST2] /'"
  509. )
  510. self.assertEqual(result, 1)
  511. self.assertIn("Cannot create a new backup", stdout)
  512. self.assertIn("refs/original", stdout)
  513. # Run with force - should succeed
  514. result, stdout, stderr = self._run_cli(
  515. "filter-branch", "--force", "--msg-filter", "sed 's/^/[TEST3] /'"
  516. )
  517. self.assertEqual(result, 0)
  518. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  519. def test_filter_branch_specific_branch(self):
  520. """Test filter-branch on a specific branch."""
  521. # Switch to test-branch and add a commit
  522. self._run_cli("checkout", "test-branch")
  523. with open(os.path.join(self.repo_path, "branch-file.txt"), "w") as f:
  524. f.write("Branch specific file")
  525. self._run_cli("add", "branch-file.txt")
  526. self._run_cli("commit", "--message=Branch commit")
  527. # Run filter-branch on the test-branch
  528. result, stdout, stderr = self._run_cli(
  529. "filter-branch", "--msg-filter", "sed 's/^/[BRANCH] /'", "test-branch"
  530. )
  531. self.assertEqual(result, 0)
  532. self.assertIn("Ref 'refs/heads/test-branch' was rewritten", stdout)
  533. # Check that only test-branch was modified
  534. result, stdout, stderr = self._run_cli("log")
  535. self.assertIn("[BRANCH] Branch commit", stdout)
  536. # Switch to master and check it wasn't modified
  537. self._run_cli("checkout", "master")
  538. result, stdout, stderr = self._run_cli("log")
  539. self.assertNotIn("[BRANCH]", stdout)
  540. def test_filter_branch_tree_filter(self):
  541. """Test filter-branch with tree filter."""
  542. # Use a tree filter to remove a specific file
  543. tree_filter = "rm -f root.txt"
  544. result, stdout, stderr = self._run_cli(
  545. "filter-branch", "--tree-filter", tree_filter
  546. )
  547. self.assertEqual(result, 0)
  548. # Check that the file was removed from the latest commit
  549. # We need to check the commit tree, not the working directory
  550. result, stdout, stderr = self._run_cli("ls-tree", "HEAD")
  551. self.assertNotIn("root.txt", stdout)
  552. def test_filter_branch_index_filter(self):
  553. """Test filter-branch with index filter."""
  554. # Use an index filter to remove a file from the index
  555. index_filter = "git rm --cached --ignore-unmatch root.txt"
  556. result, stdout, stderr = self._run_cli(
  557. "filter-branch", "--index-filter", index_filter
  558. )
  559. self.assertEqual(result, 0)
  560. def test_filter_branch_parent_filter(self):
  561. """Test filter-branch with parent filter."""
  562. # Create a merge commit first
  563. self._run_cli("checkout", "HEAD", "-b", "feature")
  564. with open(os.path.join(self.repo_path, "feature.txt"), "w") as f:
  565. f.write("Feature")
  566. self._run_cli("add", "feature.txt")
  567. self._run_cli("commit", "--message=Feature commit")
  568. self._run_cli("checkout", "master")
  569. self._run_cli("merge", "feature", "--message=Merge feature")
  570. # Use parent filter to linearize history (remove second parent)
  571. parent_filter = "cut -d' ' -f1"
  572. result, stdout, stderr = self._run_cli(
  573. "filter-branch", "--parent-filter", parent_filter
  574. )
  575. self.assertEqual(result, 0)
  576. def test_filter_branch_commit_filter(self):
  577. """Test filter-branch with commit filter."""
  578. # Use commit filter to skip commits with certain messages
  579. commit_filter = """
  580. if grep -q "Modify other" <<< "$GIT_COMMIT_MESSAGE"; then
  581. skip_commit "$@"
  582. else
  583. git commit-tree "$@"
  584. fi
  585. """
  586. result, stdout, stderr = self._run_cli(
  587. "filter-branch", "--commit-filter", commit_filter
  588. )
  589. # Note: This test may fail because the commit filter syntax is simplified
  590. # In real Git, skip_commit is a function, but our implementation may differ
  591. def test_filter_branch_tag_name_filter(self):
  592. """Test filter-branch with tag name filter."""
  593. # Run filter-branch with tag name filter to rename tags
  594. result, stdout, stderr = self._run_cli(
  595. "filter-branch",
  596. "--tag-name-filter",
  597. "sed 's/^v/version-/'",
  598. "--msg-filter",
  599. "cat",
  600. )
  601. self.assertEqual(result, 0)
  602. # Check that tag was renamed
  603. self.assertIn(b"refs/tags/version-1.0", self.repo.refs.keys())
  604. def test_filter_branch_errors(self):
  605. """Test filter-branch error handling."""
  606. # Test with invalid subdirectory
  607. result, stdout, stderr = self._run_cli(
  608. "filter-branch", "--subdirectory-filter", "nonexistent"
  609. )
  610. # Should still succeed but produce empty history
  611. self.assertEqual(result, 0)
  612. def test_filter_branch_no_args(self):
  613. """Test filter-branch with no arguments."""
  614. # Should work as no-op
  615. result, stdout, stderr = self._run_cli("filter-branch")
  616. self.assertEqual(result, 0)
  617. class ShowCommandTest(DulwichCliTestCase):
  618. """Tests for show command."""
  619. def test_show_commit(self):
  620. # Create a commit
  621. test_file = os.path.join(self.repo_path, "test.txt")
  622. with open(test_file, "w") as f:
  623. f.write("test content")
  624. self._run_cli("add", "test.txt")
  625. self._run_cli("commit", "--message=Test commit")
  626. result, stdout, stderr = self._run_cli("show", "HEAD")
  627. self.assertIn("Test commit", stdout)
  628. class FormatPatchCommandTest(DulwichCliTestCase):
  629. """Tests for format-patch command."""
  630. def test_format_patch_single_commit(self):
  631. # Create a commit with actual content
  632. from dulwich.objects import Blob, Tree
  633. # Initial commit
  634. tree1 = Tree()
  635. self.repo.object_store.add_object(tree1)
  636. self.repo.do_commit(
  637. message=b"Initial commit",
  638. tree=tree1.id,
  639. )
  640. # Second commit with a file
  641. blob = Blob.from_string(b"Hello, World!\n")
  642. self.repo.object_store.add_object(blob)
  643. tree2 = Tree()
  644. tree2.add(b"hello.txt", 0o100644, blob.id)
  645. self.repo.object_store.add_object(tree2)
  646. self.repo.do_commit(
  647. message=b"Add hello.txt",
  648. tree=tree2.id,
  649. )
  650. # Test format-patch for last commit
  651. result, stdout, stderr = self._run_cli("format-patch", "-n", "1")
  652. self.assertEqual(result, None)
  653. self.assertIn("0001-Add-hello.txt.patch", stdout)
  654. # Check patch contents
  655. patch_file = os.path.join(self.repo_path, "0001-Add-hello.txt.patch")
  656. with open(patch_file, "rb") as f:
  657. content = f.read()
  658. # Check header
  659. self.assertIn(b"Subject: [PATCH 1/1] Add hello.txt", content)
  660. self.assertIn(b"From:", content)
  661. self.assertIn(b"Date:", content)
  662. # Check diff content
  663. self.assertIn(b"diff --git a/hello.txt b/hello.txt", content)
  664. self.assertIn(b"new file mode", content)
  665. self.assertIn(b"+Hello, World!", content)
  666. # Check footer
  667. self.assertIn(b"-- \nDulwich", content)
  668. # Clean up
  669. os.remove(patch_file)
  670. def test_format_patch_multiple_commits(self):
  671. from dulwich.objects import Blob, Tree
  672. # Initial commit
  673. tree1 = Tree()
  674. self.repo.object_store.add_object(tree1)
  675. self.repo.do_commit(
  676. message=b"Initial commit",
  677. tree=tree1.id,
  678. )
  679. # Second commit
  680. blob1 = Blob.from_string(b"File 1 content\n")
  681. self.repo.object_store.add_object(blob1)
  682. tree2 = Tree()
  683. tree2.add(b"file1.txt", 0o100644, blob1.id)
  684. self.repo.object_store.add_object(tree2)
  685. self.repo.do_commit(
  686. message=b"Add file1.txt",
  687. tree=tree2.id,
  688. )
  689. # Third commit
  690. blob2 = Blob.from_string(b"File 2 content\n")
  691. self.repo.object_store.add_object(blob2)
  692. tree3 = Tree()
  693. tree3.add(b"file1.txt", 0o100644, blob1.id)
  694. tree3.add(b"file2.txt", 0o100644, blob2.id)
  695. self.repo.object_store.add_object(tree3)
  696. self.repo.do_commit(
  697. message=b"Add file2.txt",
  698. tree=tree3.id,
  699. )
  700. # Test format-patch for last 2 commits
  701. result, stdout, stderr = self._run_cli("format-patch", "-n", "2")
  702. self.assertEqual(result, None)
  703. self.assertIn("0001-Add-file1.txt.patch", stdout)
  704. self.assertIn("0002-Add-file2.txt.patch", stdout)
  705. # Check first patch
  706. with open(os.path.join(self.repo_path, "0001-Add-file1.txt.patch"), "rb") as f:
  707. content = f.read()
  708. self.assertIn(b"Subject: [PATCH 1/2] Add file1.txt", content)
  709. self.assertIn(b"+File 1 content", content)
  710. # Check second patch
  711. with open(os.path.join(self.repo_path, "0002-Add-file2.txt.patch"), "rb") as f:
  712. content = f.read()
  713. self.assertIn(b"Subject: [PATCH 2/2] Add file2.txt", content)
  714. self.assertIn(b"+File 2 content", content)
  715. # Clean up
  716. os.remove(os.path.join(self.repo_path, "0001-Add-file1.txt.patch"))
  717. os.remove(os.path.join(self.repo_path, "0002-Add-file2.txt.patch"))
  718. def test_format_patch_output_directory(self):
  719. from dulwich.objects import Blob, Tree
  720. # Create a commit
  721. blob = Blob.from_string(b"Test content\n")
  722. self.repo.object_store.add_object(blob)
  723. tree = Tree()
  724. tree.add(b"test.txt", 0o100644, blob.id)
  725. self.repo.object_store.add_object(tree)
  726. self.repo.do_commit(
  727. message=b"Test commit",
  728. tree=tree.id,
  729. )
  730. # Create output directory
  731. output_dir = os.path.join(self.test_dir, "patches")
  732. os.makedirs(output_dir)
  733. # Test format-patch with output directory
  734. result, stdout, stderr = self._run_cli(
  735. "format-patch", "-o", output_dir, "-n", "1"
  736. )
  737. self.assertEqual(result, None)
  738. # Check that file was created in output directory with correct content
  739. patch_file = os.path.join(output_dir, "0001-Test-commit.patch")
  740. self.assertTrue(os.path.exists(patch_file))
  741. with open(patch_file, "rb") as f:
  742. content = f.read()
  743. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  744. self.assertIn(b"+Test content", content)
  745. def test_format_patch_commit_range(self):
  746. from dulwich.objects import Blob, Tree
  747. # Create commits with actual file changes
  748. commits = []
  749. trees = []
  750. # Initial empty commit
  751. tree0 = Tree()
  752. self.repo.object_store.add_object(tree0)
  753. trees.append(tree0)
  754. c0 = self.repo.do_commit(
  755. message=b"Initial commit",
  756. tree=tree0.id,
  757. )
  758. commits.append(c0)
  759. # Add three files in separate commits
  760. for i in range(1, 4):
  761. blob = Blob.from_string(f"Content {i}\n".encode())
  762. self.repo.object_store.add_object(blob)
  763. tree = Tree()
  764. # Copy previous files
  765. for j in range(1, i):
  766. prev_blob_id = trees[j][f"file{j}.txt".encode()][1]
  767. tree.add(f"file{j}.txt".encode(), 0o100644, prev_blob_id)
  768. # Add new file
  769. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  770. self.repo.object_store.add_object(tree)
  771. trees.append(tree)
  772. c = self.repo.do_commit(
  773. message=f"Add file{i}.txt".encode(),
  774. tree=tree.id,
  775. )
  776. commits.append(c)
  777. # Test format-patch with commit range (should get commits 2 and 3)
  778. result, stdout, stderr = self._run_cli(
  779. "format-patch", f"{commits[1].decode()}..{commits[3].decode()}"
  780. )
  781. self.assertEqual(result, None)
  782. # Should create patches for commits 2 and 3
  783. self.assertIn("0001-Add-file2.txt.patch", stdout)
  784. self.assertIn("0002-Add-file3.txt.patch", stdout)
  785. # Verify patch contents
  786. with open(os.path.join(self.repo_path, "0001-Add-file2.txt.patch"), "rb") as f:
  787. content = f.read()
  788. self.assertIn(b"Subject: [PATCH 1/2] Add file2.txt", content)
  789. self.assertIn(b"+Content 2", content)
  790. self.assertNotIn(b"file3.txt", content) # Should not include file3
  791. with open(os.path.join(self.repo_path, "0002-Add-file3.txt.patch"), "rb") as f:
  792. content = f.read()
  793. self.assertIn(b"Subject: [PATCH 2/2] Add file3.txt", content)
  794. self.assertIn(b"+Content 3", content)
  795. self.assertNotIn(b"file2.txt", content) # Should not modify file2
  796. # Clean up
  797. os.remove(os.path.join(self.repo_path, "0001-Add-file2.txt.patch"))
  798. os.remove(os.path.join(self.repo_path, "0002-Add-file3.txt.patch"))
  799. def test_format_patch_stdout(self):
  800. from dulwich.objects import Blob, Tree
  801. # Create a commit with modified file
  802. tree1 = Tree()
  803. blob1 = Blob.from_string(b"Original content\n")
  804. self.repo.object_store.add_object(blob1)
  805. tree1.add(b"file.txt", 0o100644, blob1.id)
  806. self.repo.object_store.add_object(tree1)
  807. self.repo.do_commit(
  808. message=b"Initial commit",
  809. tree=tree1.id,
  810. )
  811. tree2 = Tree()
  812. blob2 = Blob.from_string(b"Modified content\n")
  813. self.repo.object_store.add_object(blob2)
  814. tree2.add(b"file.txt", 0o100644, blob2.id)
  815. self.repo.object_store.add_object(tree2)
  816. self.repo.do_commit(
  817. message=b"Modify file.txt",
  818. tree=tree2.id,
  819. )
  820. # Mock stdout as a BytesIO for binary output
  821. stdout_stream = io.BytesIO()
  822. stdout_stream.buffer = stdout_stream
  823. # Run command with --stdout
  824. old_stdout = sys.stdout
  825. old_stderr = sys.stderr
  826. old_cwd = os.getcwd()
  827. try:
  828. sys.stdout = stdout_stream
  829. sys.stderr = io.StringIO()
  830. os.chdir(self.repo_path)
  831. cli.main(["format-patch", "--stdout", "-n", "1"])
  832. finally:
  833. sys.stdout = old_stdout
  834. sys.stderr = old_stderr
  835. os.chdir(old_cwd)
  836. # Check output
  837. stdout_stream.seek(0)
  838. output = stdout_stream.read()
  839. self.assertIn(b"Subject: [PATCH 1/1] Modify file.txt", output)
  840. self.assertIn(b"diff --git a/file.txt b/file.txt", output)
  841. self.assertIn(b"-Original content", output)
  842. self.assertIn(b"+Modified content", output)
  843. self.assertIn(b"-- \nDulwich", output)
  844. def test_format_patch_empty_repo(self):
  845. # Test with empty repository
  846. result, stdout, stderr = self._run_cli("format-patch", "-n", "5")
  847. self.assertEqual(result, None)
  848. # Should produce no output for empty repo
  849. self.assertEqual(stdout.strip(), "")
  850. class FetchPackCommandTest(DulwichCliTestCase):
  851. """Tests for fetch-pack command."""
  852. @patch("dulwich.cli.get_transport_and_path")
  853. def test_fetch_pack_basic(self, mock_transport):
  854. # Mock the transport
  855. mock_client = MagicMock()
  856. mock_transport.return_value = (mock_client, "/path/to/repo")
  857. mock_client.fetch.return_value = None
  858. result, stdout, stderr = self._run_cli(
  859. "fetch-pack", "git://example.com/repo.git"
  860. )
  861. mock_client.fetch.assert_called_once()
  862. class LsRemoteCommandTest(DulwichCliTestCase):
  863. """Tests for ls-remote command."""
  864. def test_ls_remote_basic(self):
  865. # Create a commit
  866. test_file = os.path.join(self.repo_path, "test.txt")
  867. with open(test_file, "w") as f:
  868. f.write("test")
  869. self._run_cli("add", "test.txt")
  870. self._run_cli("commit", "--message=Initial")
  871. # Test basic ls-remote
  872. result, stdout, stderr = self._run_cli("ls-remote", self.repo_path)
  873. lines = stdout.strip().split("\n")
  874. self.assertTrue(any("HEAD" in line for line in lines))
  875. self.assertTrue(any("refs/heads/master" in line for line in lines))
  876. def test_ls_remote_symref(self):
  877. # Create a commit
  878. test_file = os.path.join(self.repo_path, "test.txt")
  879. with open(test_file, "w") as f:
  880. f.write("test")
  881. self._run_cli("add", "test.txt")
  882. self._run_cli("commit", "--message=Initial")
  883. # Test ls-remote with --symref option
  884. result, stdout, stderr = self._run_cli("ls-remote", "--symref", self.repo_path)
  885. lines = stdout.strip().split("\n")
  886. # Should show symref for HEAD in exact format: "ref: refs/heads/master\tHEAD"
  887. expected_line = "ref: refs/heads/master\tHEAD"
  888. self.assertIn(
  889. expected_line,
  890. lines,
  891. f"Expected line '{expected_line}' not found in output: {lines}",
  892. )
  893. class PullCommandTest(DulwichCliTestCase):
  894. """Tests for pull command."""
  895. @patch("dulwich.porcelain.pull")
  896. def test_pull_basic(self, mock_pull):
  897. result, stdout, stderr = self._run_cli("pull", "origin")
  898. mock_pull.assert_called_once()
  899. @patch("dulwich.porcelain.pull")
  900. def test_pull_with_refspec(self, mock_pull):
  901. result, stdout, stderr = self._run_cli("pull", "origin", "master")
  902. mock_pull.assert_called_once()
  903. class PushCommandTest(DulwichCliTestCase):
  904. """Tests for push command."""
  905. @patch("dulwich.porcelain.push")
  906. def test_push_basic(self, mock_push):
  907. result, stdout, stderr = self._run_cli("push", "origin")
  908. mock_push.assert_called_once()
  909. @patch("dulwich.porcelain.push")
  910. def test_push_force(self, mock_push):
  911. result, stdout, stderr = self._run_cli("push", "-f", "origin")
  912. mock_push.assert_called_with(".", "origin", None, force=True)
  913. class ArchiveCommandTest(DulwichCliTestCase):
  914. """Tests for archive command."""
  915. def test_archive_basic(self):
  916. # Create a commit
  917. test_file = os.path.join(self.repo_path, "test.txt")
  918. with open(test_file, "w") as f:
  919. f.write("test content")
  920. self._run_cli("add", "test.txt")
  921. self._run_cli("commit", "--message=Initial")
  922. # Archive produces binary output, so use BytesIO
  923. result, stdout, stderr = self._run_cli(
  924. "archive", "HEAD", stdout_stream=io.BytesIO()
  925. )
  926. # Should complete without error and produce some binary output
  927. self.assertIsInstance(stdout, bytes)
  928. self.assertGreater(len(stdout), 0)
  929. class ForEachRefCommandTest(DulwichCliTestCase):
  930. """Tests for for-each-ref command."""
  931. def test_for_each_ref(self):
  932. # Create a commit
  933. test_file = os.path.join(self.repo_path, "test.txt")
  934. with open(test_file, "w") as f:
  935. f.write("test")
  936. self._run_cli("add", "test.txt")
  937. self._run_cli("commit", "--message=Initial")
  938. result, stdout, stderr = self._run_cli("for-each-ref")
  939. self.assertIn("refs/heads/master", stdout)
  940. class PackRefsCommandTest(DulwichCliTestCase):
  941. """Tests for pack-refs command."""
  942. def test_pack_refs(self):
  943. # Create some refs
  944. test_file = os.path.join(self.repo_path, "test.txt")
  945. with open(test_file, "w") as f:
  946. f.write("test")
  947. self._run_cli("add", "test.txt")
  948. self._run_cli("commit", "--message=Initial")
  949. self._run_cli("branch", "test-branch")
  950. result, stdout, stderr = self._run_cli("pack-refs", "--all")
  951. # Check that packed-refs file exists
  952. self.assertTrue(
  953. os.path.exists(os.path.join(self.repo_path, ".git", "packed-refs"))
  954. )
  955. class SubmoduleCommandTest(DulwichCliTestCase):
  956. """Tests for submodule commands."""
  957. def test_submodule_list(self):
  958. # Create an initial commit so repo has a HEAD
  959. test_file = os.path.join(self.repo_path, "test.txt")
  960. with open(test_file, "w") as f:
  961. f.write("test")
  962. self._run_cli("add", "test.txt")
  963. self._run_cli("commit", "--message=Initial")
  964. result, stdout, stderr = self._run_cli("submodule")
  965. # Should not crash on repo without submodules
  966. def test_submodule_init(self):
  967. # Create .gitmodules file for init to work
  968. gitmodules = os.path.join(self.repo_path, ".gitmodules")
  969. with open(gitmodules, "w") as f:
  970. f.write("") # Empty .gitmodules file
  971. result, stdout, stderr = self._run_cli("submodule", "init")
  972. # Should not crash
  973. class StashCommandTest(DulwichCliTestCase):
  974. """Tests for stash commands."""
  975. def test_stash_list_empty(self):
  976. result, stdout, stderr = self._run_cli("stash", "list")
  977. # Should not crash on empty stash
  978. def test_stash_push_pop(self):
  979. # Create a file and modify it
  980. test_file = os.path.join(self.repo_path, "test.txt")
  981. with open(test_file, "w") as f:
  982. f.write("initial")
  983. self._run_cli("add", "test.txt")
  984. self._run_cli("commit", "--message=Initial")
  985. # Modify file
  986. with open(test_file, "w") as f:
  987. f.write("modified")
  988. # Stash changes
  989. result, stdout, stderr = self._run_cli("stash", "push")
  990. self.assertIn("Saved working directory", stdout)
  991. # Note: Dulwich stash doesn't currently update the working tree
  992. # so the file remains modified after stash push
  993. # Note: stash pop is not fully implemented in Dulwich yet
  994. # so we only test stash push here
  995. class MergeCommandTest(DulwichCliTestCase):
  996. """Tests for merge command."""
  997. def test_merge_basic(self):
  998. # Create initial commit
  999. test_file = os.path.join(self.repo_path, "test.txt")
  1000. with open(test_file, "w") as f:
  1001. f.write("initial")
  1002. self._run_cli("add", "test.txt")
  1003. self._run_cli("commit", "--message=Initial")
  1004. # Create and checkout new branch
  1005. self._run_cli("branch", "feature")
  1006. self._run_cli("checkout", "feature")
  1007. # Make changes in feature branch
  1008. with open(test_file, "w") as f:
  1009. f.write("feature changes")
  1010. self._run_cli("add", "test.txt")
  1011. self._run_cli("commit", "--message=Feature commit")
  1012. # Go back to main
  1013. self._run_cli("checkout", "master")
  1014. # Merge feature branch
  1015. result, stdout, stderr = self._run_cli("merge", "feature")
  1016. class HelpCommandTest(DulwichCliTestCase):
  1017. """Tests for help command."""
  1018. def test_help_basic(self):
  1019. result, stdout, stderr = self._run_cli("help")
  1020. self.assertIn("dulwich command line tool", stdout)
  1021. def test_help_all(self):
  1022. result, stdout, stderr = self._run_cli("help", "-a")
  1023. self.assertIn("Available commands:", stdout)
  1024. self.assertIn("add", stdout)
  1025. self.assertIn("commit", stdout)
  1026. class RemoteCommandTest(DulwichCliTestCase):
  1027. """Tests for remote commands."""
  1028. def test_remote_add(self):
  1029. result, stdout, stderr = self._run_cli(
  1030. "remote", "add", "origin", "https://github.com/example/repo.git"
  1031. )
  1032. # Check remote was added to config
  1033. config = self.repo.get_config()
  1034. self.assertEqual(
  1035. config.get((b"remote", b"origin"), b"url"),
  1036. b"https://github.com/example/repo.git",
  1037. )
  1038. class CheckIgnoreCommandTest(DulwichCliTestCase):
  1039. """Tests for check-ignore command."""
  1040. def test_check_ignore(self):
  1041. # Create .gitignore
  1042. gitignore = os.path.join(self.repo_path, ".gitignore")
  1043. with open(gitignore, "w") as f:
  1044. f.write("*.log\n")
  1045. result, stdout, stderr = self._run_cli("check-ignore", "test.log", "test.txt")
  1046. self.assertIn("test.log", stdout)
  1047. self.assertNotIn("test.txt", stdout)
  1048. class LsFilesCommandTest(DulwichCliTestCase):
  1049. """Tests for ls-files command."""
  1050. def test_ls_files(self):
  1051. # Add some files
  1052. for name in ["a.txt", "b.txt", "c.txt"]:
  1053. path = os.path.join(self.repo_path, name)
  1054. with open(path, "w") as f:
  1055. f.write(f"content of {name}")
  1056. self._run_cli("add", "a.txt", "b.txt", "c.txt")
  1057. result, stdout, stderr = self._run_cli("ls-files")
  1058. self.assertIn("a.txt", stdout)
  1059. self.assertIn("b.txt", stdout)
  1060. self.assertIn("c.txt", stdout)
  1061. class LsTreeCommandTest(DulwichCliTestCase):
  1062. """Tests for ls-tree command."""
  1063. def test_ls_tree(self):
  1064. # Create a directory structure
  1065. os.mkdir(os.path.join(self.repo_path, "subdir"))
  1066. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  1067. f.write("file content")
  1068. with open(os.path.join(self.repo_path, "subdir", "nested.txt"), "w") as f:
  1069. f.write("nested content")
  1070. self._run_cli("add", ".")
  1071. self._run_cli("commit", "--message=Initial")
  1072. result, stdout, stderr = self._run_cli("ls-tree", "HEAD")
  1073. self.assertIn("file.txt", stdout)
  1074. self.assertIn("subdir", stdout)
  1075. def test_ls_tree_recursive(self):
  1076. # Create nested structure
  1077. os.mkdir(os.path.join(self.repo_path, "subdir"))
  1078. with open(os.path.join(self.repo_path, "subdir", "nested.txt"), "w") as f:
  1079. f.write("nested")
  1080. self._run_cli("add", ".")
  1081. self._run_cli("commit", "--message=Initial")
  1082. result, stdout, stderr = self._run_cli("ls-tree", "-r", "HEAD")
  1083. self.assertIn("subdir/nested.txt", stdout)
  1084. class DescribeCommandTest(DulwichCliTestCase):
  1085. """Tests for describe command."""
  1086. def test_describe(self):
  1087. # Create tagged commit
  1088. test_file = os.path.join(self.repo_path, "test.txt")
  1089. with open(test_file, "w") as f:
  1090. f.write("test")
  1091. self._run_cli("add", "test.txt")
  1092. self._run_cli("commit", "--message=Initial")
  1093. self._run_cli("tag", "v1.0")
  1094. result, stdout, stderr = self._run_cli("describe")
  1095. self.assertIn("v1.0", stdout)
  1096. class FsckCommandTest(DulwichCliTestCase):
  1097. """Tests for fsck command."""
  1098. def test_fsck(self):
  1099. # Create a commit
  1100. test_file = os.path.join(self.repo_path, "test.txt")
  1101. with open(test_file, "w") as f:
  1102. f.write("test")
  1103. self._run_cli("add", "test.txt")
  1104. self._run_cli("commit", "--message=Initial")
  1105. result, stdout, stderr = self._run_cli("fsck")
  1106. # Should complete without errors
  1107. class RepackCommandTest(DulwichCliTestCase):
  1108. """Tests for repack command."""
  1109. def test_repack(self):
  1110. # Create some objects
  1111. for i in range(5):
  1112. test_file = os.path.join(self.repo_path, f"test{i}.txt")
  1113. with open(test_file, "w") as f:
  1114. f.write(f"content {i}")
  1115. self._run_cli("add", f"test{i}.txt")
  1116. self._run_cli("commit", f"--message=Commit {i}")
  1117. result, stdout, stderr = self._run_cli("repack")
  1118. # Should create pack files
  1119. pack_dir = os.path.join(self.repo_path, ".git", "objects", "pack")
  1120. self.assertTrue(any(f.endswith(".pack") for f in os.listdir(pack_dir)))
  1121. class ResetCommandTest(DulwichCliTestCase):
  1122. """Tests for reset command."""
  1123. def test_reset_soft(self):
  1124. # Create commits
  1125. test_file = os.path.join(self.repo_path, "test.txt")
  1126. with open(test_file, "w") as f:
  1127. f.write("first")
  1128. self._run_cli("add", "test.txt")
  1129. self._run_cli("commit", "--message=First")
  1130. first_commit = self.repo.head()
  1131. with open(test_file, "w") as f:
  1132. f.write("second")
  1133. self._run_cli("add", "test.txt")
  1134. self._run_cli("commit", "--message=Second")
  1135. # Reset soft
  1136. result, stdout, stderr = self._run_cli("reset", "--soft", first_commit.decode())
  1137. # HEAD should be at first commit
  1138. self.assertEqual(self.repo.head(), first_commit)
  1139. class WriteTreeCommandTest(DulwichCliTestCase):
  1140. """Tests for write-tree command."""
  1141. def test_write_tree(self):
  1142. # Create and add files
  1143. test_file = os.path.join(self.repo_path, "test.txt")
  1144. with open(test_file, "w") as f:
  1145. f.write("test")
  1146. self._run_cli("add", "test.txt")
  1147. result, stdout, stderr = self._run_cli("write-tree")
  1148. # Should output tree SHA
  1149. self.assertEqual(len(stdout.strip()), 40)
  1150. class UpdateServerInfoCommandTest(DulwichCliTestCase):
  1151. """Tests for update-server-info command."""
  1152. def test_update_server_info(self):
  1153. result, stdout, stderr = self._run_cli("update-server-info")
  1154. # Should create info/refs file
  1155. info_refs = os.path.join(self.repo_path, ".git", "info", "refs")
  1156. self.assertTrue(os.path.exists(info_refs))
  1157. class SymbolicRefCommandTest(DulwichCliTestCase):
  1158. """Tests for symbolic-ref command."""
  1159. def test_symbolic_ref(self):
  1160. # Create a branch
  1161. test_file = os.path.join(self.repo_path, "test.txt")
  1162. with open(test_file, "w") as f:
  1163. f.write("test")
  1164. self._run_cli("add", "test.txt")
  1165. self._run_cli("commit", "--message=Initial")
  1166. self._run_cli("branch", "test-branch")
  1167. result, stdout, stderr = self._run_cli(
  1168. "symbolic-ref", "HEAD", "refs/heads/test-branch"
  1169. )
  1170. # HEAD should now point to test-branch
  1171. self.assertEqual(
  1172. self.repo.refs.read_ref(b"HEAD"), b"ref: refs/heads/test-branch"
  1173. )
  1174. class BundleCommandTest(DulwichCliTestCase):
  1175. """Tests for bundle commands."""
  1176. def setUp(self):
  1177. super().setUp()
  1178. # Create a basic repository with some commits for bundle testing
  1179. # Create initial commit
  1180. test_file = os.path.join(self.repo_path, "file1.txt")
  1181. with open(test_file, "w") as f:
  1182. f.write("Content of file1\n")
  1183. self._run_cli("add", "file1.txt")
  1184. self._run_cli("commit", "--message=Initial commit")
  1185. # Create second commit
  1186. test_file2 = os.path.join(self.repo_path, "file2.txt")
  1187. with open(test_file2, "w") as f:
  1188. f.write("Content of file2\n")
  1189. self._run_cli("add", "file2.txt")
  1190. self._run_cli("commit", "--message=Add file2")
  1191. # Create a branch and tag for testing
  1192. self._run_cli("branch", "feature")
  1193. self._run_cli("tag", "v1.0")
  1194. def test_bundle_create_basic(self):
  1195. """Test basic bundle creation."""
  1196. bundle_file = os.path.join(self.test_dir, "test.bundle")
  1197. result, stdout, stderr = self._run_cli("bundle", "create", bundle_file, "HEAD")
  1198. self.assertEqual(result, 0)
  1199. self.assertTrue(os.path.exists(bundle_file))
  1200. self.assertGreater(os.path.getsize(bundle_file), 0)
  1201. def test_bundle_create_all_refs(self):
  1202. """Test bundle creation with --all flag."""
  1203. bundle_file = os.path.join(self.test_dir, "all.bundle")
  1204. result, stdout, stderr = self._run_cli("bundle", "create", "--all", bundle_file)
  1205. self.assertEqual(result, 0)
  1206. self.assertTrue(os.path.exists(bundle_file))
  1207. def test_bundle_create_specific_refs(self):
  1208. """Test bundle creation with specific refs."""
  1209. bundle_file = os.path.join(self.test_dir, "refs.bundle")
  1210. # Only use HEAD since feature branch may not exist
  1211. result, stdout, stderr = self._run_cli("bundle", "create", bundle_file, "HEAD")
  1212. self.assertEqual(result, 0)
  1213. self.assertTrue(os.path.exists(bundle_file))
  1214. def test_bundle_create_with_range(self):
  1215. """Test bundle creation with commit range."""
  1216. # Get the first commit SHA by looking at the log
  1217. result, stdout, stderr = self._run_cli("log", "--reverse")
  1218. lines = stdout.strip().split("\n")
  1219. # Find first commit line that contains a SHA
  1220. first_commit = None
  1221. for line in lines:
  1222. if line.startswith("commit "):
  1223. first_commit = line.split()[1][:8] # Get short SHA
  1224. break
  1225. if first_commit:
  1226. bundle_file = os.path.join(self.test_dir, "range.bundle")
  1227. result, stdout, stderr = self._run_cli(
  1228. "bundle", "create", bundle_file, f"{first_commit}..HEAD"
  1229. )
  1230. self.assertEqual(result, 0)
  1231. self.assertTrue(os.path.exists(bundle_file))
  1232. else:
  1233. self.skipTest("Could not determine first commit SHA")
  1234. def test_bundle_create_to_stdout(self):
  1235. """Test bundle creation to stdout."""
  1236. result, stdout, stderr = self._run_cli("bundle", "create", "-", "HEAD")
  1237. self.assertEqual(result, 0)
  1238. self.assertGreater(len(stdout), 0)
  1239. # Bundle output is binary, so check it's not empty
  1240. self.assertIsInstance(stdout, (str, bytes))
  1241. def test_bundle_create_no_refs(self):
  1242. """Test bundle creation with no refs specified."""
  1243. bundle_file = os.path.join(self.test_dir, "noref.bundle")
  1244. result, stdout, stderr = self._run_cli("bundle", "create", bundle_file)
  1245. self.assertEqual(result, 1)
  1246. self.assertIn("No refs specified", stdout)
  1247. def test_bundle_create_empty_bundle_refused(self):
  1248. """Test that empty bundles are refused."""
  1249. bundle_file = os.path.join(self.test_dir, "empty.bundle")
  1250. # Try to create bundle with non-existent ref - this should fail with KeyError
  1251. with self.assertRaises(KeyError):
  1252. result, stdout, stderr = self._run_cli(
  1253. "bundle", "create", bundle_file, "nonexistent-ref"
  1254. )
  1255. def test_bundle_verify_valid(self):
  1256. """Test bundle verification of valid bundle."""
  1257. bundle_file = os.path.join(self.test_dir, "valid.bundle")
  1258. # First create a bundle
  1259. result, stdout, stderr = self._run_cli("bundle", "create", bundle_file, "HEAD")
  1260. self.assertEqual(result, 0)
  1261. # Now verify it
  1262. result, stdout, stderr = self._run_cli("bundle", "verify", bundle_file)
  1263. self.assertEqual(result, 0)
  1264. self.assertIn("valid and can be applied", stdout)
  1265. def test_bundle_verify_quiet(self):
  1266. """Test bundle verification with quiet flag."""
  1267. bundle_file = os.path.join(self.test_dir, "quiet.bundle")
  1268. # Create bundle
  1269. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1270. # Verify quietly
  1271. result, stdout, stderr = self._run_cli(
  1272. "bundle", "verify", "--quiet", bundle_file
  1273. )
  1274. self.assertEqual(result, 0)
  1275. self.assertEqual(stdout.strip(), "")
  1276. def test_bundle_verify_from_stdin(self):
  1277. """Test bundle verification from stdin."""
  1278. bundle_file = os.path.join(self.test_dir, "stdin.bundle")
  1279. # Create bundle
  1280. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1281. # Read bundle content
  1282. with open(bundle_file, "rb") as f:
  1283. bundle_content = f.read()
  1284. # Mock stdin with bundle content
  1285. old_stdin = sys.stdin
  1286. try:
  1287. sys.stdin = io.BytesIO(bundle_content)
  1288. sys.stdin.buffer = sys.stdin
  1289. result, stdout, stderr = self._run_cli("bundle", "verify", "-")
  1290. self.assertEqual(result, 0)
  1291. finally:
  1292. sys.stdin = old_stdin
  1293. def test_bundle_list_heads(self):
  1294. """Test listing bundle heads."""
  1295. bundle_file = os.path.join(self.test_dir, "heads.bundle")
  1296. # Create bundle with HEAD only
  1297. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1298. # List heads
  1299. result, stdout, stderr = self._run_cli("bundle", "list-heads", bundle_file)
  1300. self.assertEqual(result, 0)
  1301. # Should contain at least the HEAD reference
  1302. self.assertTrue(len(stdout.strip()) > 0)
  1303. def test_bundle_list_heads_specific_refs(self):
  1304. """Test listing specific bundle heads."""
  1305. bundle_file = os.path.join(self.test_dir, "specific.bundle")
  1306. # Create bundle with HEAD
  1307. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1308. # List heads without filtering
  1309. result, stdout, stderr = self._run_cli("bundle", "list-heads", bundle_file)
  1310. self.assertEqual(result, 0)
  1311. # Should contain some reference
  1312. self.assertTrue(len(stdout.strip()) > 0)
  1313. def test_bundle_list_heads_from_stdin(self):
  1314. """Test listing bundle heads from stdin."""
  1315. bundle_file = os.path.join(self.test_dir, "stdin-heads.bundle")
  1316. # Create bundle
  1317. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1318. # Read bundle content
  1319. with open(bundle_file, "rb") as f:
  1320. bundle_content = f.read()
  1321. # Mock stdin
  1322. old_stdin = sys.stdin
  1323. try:
  1324. sys.stdin = io.BytesIO(bundle_content)
  1325. sys.stdin.buffer = sys.stdin
  1326. result, stdout, stderr = self._run_cli("bundle", "list-heads", "-")
  1327. self.assertEqual(result, 0)
  1328. finally:
  1329. sys.stdin = old_stdin
  1330. def test_bundle_unbundle(self):
  1331. """Test bundle unbundling."""
  1332. bundle_file = os.path.join(self.test_dir, "unbundle.bundle")
  1333. # Create bundle
  1334. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1335. # Unbundle
  1336. result, stdout, stderr = self._run_cli("bundle", "unbundle", bundle_file)
  1337. self.assertEqual(result, 0)
  1338. def test_bundle_unbundle_specific_refs(self):
  1339. """Test unbundling specific refs."""
  1340. bundle_file = os.path.join(self.test_dir, "unbundle-specific.bundle")
  1341. # Create bundle with HEAD
  1342. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1343. # Unbundle only HEAD
  1344. result, stdout, stderr = self._run_cli(
  1345. "bundle", "unbundle", bundle_file, "HEAD"
  1346. )
  1347. self.assertEqual(result, 0)
  1348. def test_bundle_unbundle_from_stdin(self):
  1349. """Test unbundling from stdin."""
  1350. bundle_file = os.path.join(self.test_dir, "stdin-unbundle.bundle")
  1351. # Create bundle
  1352. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1353. # Read bundle content to simulate stdin
  1354. with open(bundle_file, "rb") as f:
  1355. bundle_content = f.read()
  1356. # Mock stdin with bundle content
  1357. old_stdin = sys.stdin
  1358. try:
  1359. # Create a BytesIO object with buffer attribute
  1360. mock_stdin = io.BytesIO(bundle_content)
  1361. mock_stdin.buffer = mock_stdin
  1362. sys.stdin = mock_stdin
  1363. result, stdout, stderr = self._run_cli("bundle", "unbundle", "-")
  1364. self.assertEqual(result, 0)
  1365. finally:
  1366. sys.stdin = old_stdin
  1367. def test_bundle_unbundle_with_progress(self):
  1368. """Test unbundling with progress output."""
  1369. bundle_file = os.path.join(self.test_dir, "progress.bundle")
  1370. # Create bundle
  1371. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1372. # Unbundle with progress
  1373. result, stdout, stderr = self._run_cli(
  1374. "bundle", "unbundle", "--progress", bundle_file
  1375. )
  1376. self.assertEqual(result, 0)
  1377. def test_bundle_create_with_progress(self):
  1378. """Test bundle creation with progress output."""
  1379. bundle_file = os.path.join(self.test_dir, "create-progress.bundle")
  1380. result, stdout, stderr = self._run_cli(
  1381. "bundle", "create", "--progress", bundle_file, "HEAD"
  1382. )
  1383. self.assertEqual(result, 0)
  1384. self.assertTrue(os.path.exists(bundle_file))
  1385. def test_bundle_create_with_quiet(self):
  1386. """Test bundle creation with quiet flag."""
  1387. bundle_file = os.path.join(self.test_dir, "quiet-create.bundle")
  1388. result, stdout, stderr = self._run_cli(
  1389. "bundle", "create", "--quiet", bundle_file, "HEAD"
  1390. )
  1391. self.assertEqual(result, 0)
  1392. self.assertTrue(os.path.exists(bundle_file))
  1393. def test_bundle_create_version_2(self):
  1394. """Test bundle creation with specific version."""
  1395. bundle_file = os.path.join(self.test_dir, "v2.bundle")
  1396. result, stdout, stderr = self._run_cli(
  1397. "bundle", "create", "--version", "2", bundle_file, "HEAD"
  1398. )
  1399. self.assertEqual(result, 0)
  1400. self.assertTrue(os.path.exists(bundle_file))
  1401. def test_bundle_create_version_3(self):
  1402. """Test bundle creation with version 3."""
  1403. bundle_file = os.path.join(self.test_dir, "v3.bundle")
  1404. result, stdout, stderr = self._run_cli(
  1405. "bundle", "create", "--version", "3", bundle_file, "HEAD"
  1406. )
  1407. self.assertEqual(result, 0)
  1408. self.assertTrue(os.path.exists(bundle_file))
  1409. def test_bundle_invalid_subcommand(self):
  1410. """Test invalid bundle subcommand."""
  1411. result, stdout, stderr = self._run_cli("bundle", "invalid-command")
  1412. self.assertEqual(result, 1)
  1413. self.assertIn("Unknown bundle subcommand", stdout)
  1414. def test_bundle_no_subcommand(self):
  1415. """Test bundle command with no subcommand."""
  1416. result, stdout, stderr = self._run_cli("bundle")
  1417. self.assertEqual(result, 1)
  1418. self.assertIn("Usage: bundle", stdout)
  1419. def test_bundle_create_with_stdin_refs(self):
  1420. """Test bundle creation reading refs from stdin."""
  1421. bundle_file = os.path.join(self.test_dir, "stdin-refs.bundle")
  1422. # Mock stdin with refs
  1423. old_stdin = sys.stdin
  1424. try:
  1425. sys.stdin = io.StringIO("master\nfeature\n")
  1426. result, stdout, stderr = self._run_cli(
  1427. "bundle", "create", "--stdin", bundle_file
  1428. )
  1429. self.assertEqual(result, 0)
  1430. self.assertTrue(os.path.exists(bundle_file))
  1431. finally:
  1432. sys.stdin = old_stdin
  1433. def test_bundle_verify_missing_prerequisites(self):
  1434. """Test bundle verification with missing prerequisites."""
  1435. # Create a simple bundle first
  1436. bundle_file = os.path.join(self.test_dir, "prereq.bundle")
  1437. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1438. # Create a new repo to simulate missing objects
  1439. new_repo_path = os.path.join(self.test_dir, "new_repo")
  1440. os.mkdir(new_repo_path)
  1441. new_repo = Repo.init(new_repo_path)
  1442. new_repo.close()
  1443. # Try to verify in new repo
  1444. old_cwd = os.getcwd()
  1445. try:
  1446. os.chdir(new_repo_path)
  1447. result, stdout, stderr = self._run_cli("bundle", "verify", bundle_file)
  1448. # Just check that verification runs - result depends on bundle content
  1449. self.assertIn(result, [0, 1])
  1450. finally:
  1451. os.chdir(old_cwd)
  1452. def test_bundle_create_with_committish_range(self):
  1453. """Test bundle creation with commit range using parse_committish_range."""
  1454. # Create additional commits for range testing
  1455. test_file3 = os.path.join(self.repo_path, "file3.txt")
  1456. with open(test_file3, "w") as f:
  1457. f.write("Content of file3\n")
  1458. self._run_cli("add", "file3.txt")
  1459. self._run_cli("commit", "--message=Add file3")
  1460. # Get commit SHAs
  1461. result, stdout, stderr = self._run_cli("log")
  1462. lines = stdout.strip().split("\n")
  1463. # Extract SHAs from commit lines
  1464. commits = []
  1465. for line in lines:
  1466. if line.startswith("commit:"):
  1467. sha = line.split()[1]
  1468. commits.append(sha[:8]) # Get short SHA
  1469. # We should have exactly 3 commits: Add file3, Add file2, Initial commit
  1470. self.assertEqual(len(commits), 3)
  1471. bundle_file = os.path.join(self.test_dir, "range-test.bundle")
  1472. # Test with commit range using .. syntax
  1473. # Create a bundle containing commits reachable from commits[0] but not from commits[2]
  1474. result, stdout, stderr = self._run_cli(
  1475. "bundle", "create", bundle_file, f"{commits[2]}..HEAD"
  1476. )
  1477. if result != 0:
  1478. self.fail(
  1479. f"Bundle create failed with exit code {result}. stdout: {stdout!r}, stderr: {stderr!r}"
  1480. )
  1481. self.assertEqual(result, 0)
  1482. self.assertTrue(os.path.exists(bundle_file))
  1483. # Verify the bundle was created
  1484. result, stdout, stderr = self._run_cli("bundle", "verify", bundle_file)
  1485. self.assertEqual(result, 0)
  1486. self.assertIn("valid and can be applied", stdout)
  1487. class FormatBytesTestCase(TestCase):
  1488. """Tests for format_bytes function."""
  1489. def test_bytes(self):
  1490. """Test formatting bytes."""
  1491. self.assertEqual("0.0 B", format_bytes(0))
  1492. self.assertEqual("1.0 B", format_bytes(1))
  1493. self.assertEqual("512.0 B", format_bytes(512))
  1494. self.assertEqual("1023.0 B", format_bytes(1023))
  1495. def test_kilobytes(self):
  1496. """Test formatting kilobytes."""
  1497. self.assertEqual("1.0 KB", format_bytes(1024))
  1498. self.assertEqual("1.5 KB", format_bytes(1536))
  1499. self.assertEqual("2.0 KB", format_bytes(2048))
  1500. self.assertEqual("1023.0 KB", format_bytes(1024 * 1023))
  1501. def test_megabytes(self):
  1502. """Test formatting megabytes."""
  1503. self.assertEqual("1.0 MB", format_bytes(1024 * 1024))
  1504. self.assertEqual("1.5 MB", format_bytes(1024 * 1024 * 1.5))
  1505. self.assertEqual("10.0 MB", format_bytes(1024 * 1024 * 10))
  1506. self.assertEqual("1023.0 MB", format_bytes(1024 * 1024 * 1023))
  1507. def test_gigabytes(self):
  1508. """Test formatting gigabytes."""
  1509. self.assertEqual("1.0 GB", format_bytes(1024 * 1024 * 1024))
  1510. self.assertEqual("2.5 GB", format_bytes(1024 * 1024 * 1024 * 2.5))
  1511. self.assertEqual("1023.0 GB", format_bytes(1024 * 1024 * 1024 * 1023))
  1512. def test_terabytes(self):
  1513. """Test formatting terabytes."""
  1514. self.assertEqual("1.0 TB", format_bytes(1024 * 1024 * 1024 * 1024))
  1515. self.assertEqual("5.0 TB", format_bytes(1024 * 1024 * 1024 * 1024 * 5))
  1516. self.assertEqual("1000.0 TB", format_bytes(1024 * 1024 * 1024 * 1024 * 1000))
  1517. class ParseRelativeTimeTestCase(TestCase):
  1518. """Tests for parse_relative_time function."""
  1519. def test_now(self):
  1520. """Test parsing 'now'."""
  1521. self.assertEqual(0, parse_relative_time("now"))
  1522. def test_seconds(self):
  1523. """Test parsing seconds."""
  1524. self.assertEqual(1, parse_relative_time("1 second ago"))
  1525. self.assertEqual(5, parse_relative_time("5 seconds ago"))
  1526. self.assertEqual(30, parse_relative_time("30 seconds ago"))
  1527. def test_minutes(self):
  1528. """Test parsing minutes."""
  1529. self.assertEqual(60, parse_relative_time("1 minute ago"))
  1530. self.assertEqual(300, parse_relative_time("5 minutes ago"))
  1531. self.assertEqual(1800, parse_relative_time("30 minutes ago"))
  1532. def test_hours(self):
  1533. """Test parsing hours."""
  1534. self.assertEqual(3600, parse_relative_time("1 hour ago"))
  1535. self.assertEqual(7200, parse_relative_time("2 hours ago"))
  1536. self.assertEqual(86400, parse_relative_time("24 hours ago"))
  1537. def test_days(self):
  1538. """Test parsing days."""
  1539. self.assertEqual(86400, parse_relative_time("1 day ago"))
  1540. self.assertEqual(604800, parse_relative_time("7 days ago"))
  1541. self.assertEqual(2592000, parse_relative_time("30 days ago"))
  1542. def test_weeks(self):
  1543. """Test parsing weeks."""
  1544. self.assertEqual(604800, parse_relative_time("1 week ago"))
  1545. self.assertEqual(1209600, parse_relative_time("2 weeks ago"))
  1546. self.assertEqual(
  1547. 36288000, parse_relative_time("60 weeks ago")
  1548. ) # 60 * 7 * 24 * 60 * 60
  1549. def test_invalid_format(self):
  1550. """Test invalid time formats."""
  1551. with self.assertRaises(ValueError) as cm:
  1552. parse_relative_time("invalid")
  1553. self.assertIn("Invalid relative time format", str(cm.exception))
  1554. with self.assertRaises(ValueError) as cm:
  1555. parse_relative_time("2 weeks")
  1556. self.assertIn("Invalid relative time format", str(cm.exception))
  1557. with self.assertRaises(ValueError) as cm:
  1558. parse_relative_time("ago")
  1559. self.assertIn("Invalid relative time format", str(cm.exception))
  1560. with self.assertRaises(ValueError) as cm:
  1561. parse_relative_time("two weeks ago")
  1562. self.assertIn("Invalid number in relative time", str(cm.exception))
  1563. def test_invalid_unit(self):
  1564. """Test invalid time units."""
  1565. with self.assertRaises(ValueError) as cm:
  1566. parse_relative_time("5 months ago")
  1567. self.assertIn("Unknown time unit: months", str(cm.exception))
  1568. with self.assertRaises(ValueError) as cm:
  1569. parse_relative_time("2 years ago")
  1570. self.assertIn("Unknown time unit: years", str(cm.exception))
  1571. def test_singular_plural(self):
  1572. """Test that both singular and plural forms work."""
  1573. self.assertEqual(
  1574. parse_relative_time("1 second ago"), parse_relative_time("1 seconds ago")
  1575. )
  1576. self.assertEqual(
  1577. parse_relative_time("1 minute ago"), parse_relative_time("1 minutes ago")
  1578. )
  1579. self.assertEqual(
  1580. parse_relative_time("1 hour ago"), parse_relative_time("1 hours ago")
  1581. )
  1582. self.assertEqual(
  1583. parse_relative_time("1 day ago"), parse_relative_time("1 days ago")
  1584. )
  1585. self.assertEqual(
  1586. parse_relative_time("1 week ago"), parse_relative_time("1 weeks ago")
  1587. )
  1588. if __name__ == "__main__":
  1589. unittest.main()