File: test_lfs.py

package info (click to toggle)
dulwich 1.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 7,388 kB
  • sloc: python: 99,991; makefile: 163; sh: 67
file content (478 lines) | stat: -rw-r--r-- 18,675 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
#!/usr/bin/python
# test_lfs.py -- Compatibility tests for LFS.
# Copyright (C) 2025 Dulwich contributors
#
# Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
# General Public License as published by the Free Software Foundation; version 2.0
# or (at your option) any later version. You can redistribute it and/or
# modify it under the terms of either of these two licenses.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# You should have received a copy of the licenses; if not, see
# <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
# and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
# License, Version 2.0.
#

"""Compatibility tests for LFS functionality between dulwich and git-lfs."""

import os
import subprocess
import tempfile
from unittest import skipUnless

from dulwich import porcelain
from dulwich.lfs import LFSPointer
from dulwich.porcelain import lfs_clean, lfs_init, lfs_smudge, lfs_track

from .utils import CompatTestCase, rmtree_ro, run_git_or_fail


def git_lfs_version():
    """Get git-lfs version tuple."""
    try:
        output = run_git_or_fail(["lfs", "version"])
        # Example output: "git-lfs/3.0.2 (GitHub; linux amd64; go 1.17.2)"
        version_str = output.split(b"/")[1].split()[0]
        return tuple(map(int, version_str.decode().split(".")))
    except (OSError, subprocess.CalledProcessError, AssertionError):
        return None


class LFSCompatTestCase(CompatTestCase):
    """Base class for LFS compatibility tests."""

    min_git_version = (2, 0, 0)  # git-lfs requires git 2.0+

    def setUp(self):
        super().setUp()
        if git_lfs_version() is None:
            self.skipTest("git-lfs not available")

    def assertPointerEquals(self, pointer1, pointer2):
        """Assert two LFS pointers are equivalent."""
        self.assertEqual(pointer1.oid, pointer2.oid)
        self.assertEqual(pointer1.size, pointer2.size)

    def make_temp_dir(self):
        """Create a temporary directory that will be cleaned up."""
        temp_dir = tempfile.mkdtemp()
        self.addCleanup(rmtree_ro, temp_dir)
        return temp_dir


class LFSInitCompatTest(LFSCompatTestCase):
    """Tests for LFS initialization compatibility."""

    def test_lfs_init_dulwich(self):
        """Test that dulwich lfs_init is compatible with git-lfs."""
        # Initialize with dulwich
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        lfs_init(repo_dir)

        # Verify with git-lfs
        output = run_git_or_fail(["lfs", "env"], cwd=repo_dir)
        self.assertIn(b"git config filter.lfs.clean", output)
        self.assertIn(b"git config filter.lfs.smudge", output)

    def test_lfs_init_git(self):
        """Test that git-lfs init is compatible with dulwich."""
        # Initialize with git-lfs
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        run_git_or_fail(["lfs", "install", "--local"], cwd=repo_dir)

        # Verify with dulwich
        repo = porcelain.open_repo(repo_dir)
        self.addCleanup(repo.close)
        config = repo.get_config_stack()
        self.assertEqual(
            config.get(("filter", "lfs"), "clean").decode(), "git-lfs clean -- %f"
        )
        self.assertEqual(
            config.get(("filter", "lfs"), "smudge").decode(), "git-lfs smudge -- %f"
        )


class LFSTrackCompatTest(LFSCompatTestCase):
    """Tests for LFS tracking compatibility."""

    def test_track_dulwich(self):
        """Test that dulwich lfs_track is compatible with git-lfs."""
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        lfs_init(repo_dir)

        # Track with dulwich
        lfs_track(repo_dir, ["*.bin", "*.dat"])

        # Verify with git-lfs
        output = run_git_or_fail(["lfs", "track"], cwd=repo_dir)
        self.assertIn(b"*.bin", output)
        self.assertIn(b"*.dat", output)

    def test_track_git(self):
        """Test that git-lfs track is compatible with dulwich."""
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        run_git_or_fail(["lfs", "install", "--local"], cwd=repo_dir)

        # Track with git-lfs
        run_git_or_fail(["lfs", "track", "*.bin"], cwd=repo_dir)
        run_git_or_fail(["lfs", "track", "*.dat"], cwd=repo_dir)

        # Verify with dulwich
        gitattributes_path = os.path.join(repo_dir, ".gitattributes")
        with open(gitattributes_path, "rb") as f:
            content = f.read().decode()
        self.assertIn("*.bin filter=lfs", content)
        self.assertIn("*.dat filter=lfs", content)


class LFSFileOperationsCompatTest(LFSCompatTestCase):
    """Tests for LFS file operations compatibility."""

    def test_add_commit_dulwich(self):
        """Test adding and committing LFS files with dulwich."""
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        lfs_init(repo_dir)
        lfs_track(repo_dir, ["*.bin"])

        # Create and add a large file
        test_file = os.path.join(repo_dir, "test.bin")
        test_content = b"x" * 1024 * 1024  # 1MB
        with open(test_file, "wb") as f:
            f.write(test_content)

        # Add with dulwich
        porcelain.add(repo_dir, [test_file])
        porcelain.commit(repo_dir, message=b"Add LFS file")

        # Verify with git-lfs
        output = run_git_or_fail(["lfs", "ls-files"], cwd=repo_dir)
        self.assertIn(b"test.bin", output)

        # Check pointer file in git
        output = run_git_or_fail(["show", "HEAD:test.bin"], cwd=repo_dir)
        self.assertIn(b"version https://git-lfs.github.com/spec/v1", output)
        self.assertIn(b"oid sha256:", output)
        self.assertIn(b"size 1048576", output)

    def test_add_commit_git(self):
        """Test adding and committing LFS files with git-lfs."""
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        run_git_or_fail(["lfs", "install", "--local"], cwd=repo_dir)
        run_git_or_fail(["lfs", "track", "*.bin"], cwd=repo_dir)
        run_git_or_fail(["add", ".gitattributes"], cwd=repo_dir)
        run_git_or_fail(["commit", "-m", "Track .bin files"], cwd=repo_dir)

        # Create and add a large file
        test_file = os.path.join(repo_dir, "test.bin")
        test_content = b"y" * 1024 * 1024  # 1MB
        with open(test_file, "wb") as f:
            f.write(test_content)

        # Add with git-lfs
        run_git_or_fail(["add", "test.bin"], cwd=repo_dir)
        run_git_or_fail(["commit", "-m", "Add LFS file"], cwd=repo_dir)

        # Verify with dulwich
        repo = porcelain.open_repo(repo_dir)
        self.addCleanup(repo.close)
        tree = repo[repo.head()].tree
        _mode, sha = repo.object_store[tree][b"test.bin"]
        blob = repo.object_store[sha]
        pointer = LFSPointer.from_bytes(blob.data)
        self.assertEqual(pointer.size, 1048576)

    def test_checkout_dulwich(self):
        """Test checking out LFS files with dulwich."""
        # Create repo with git-lfs
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        run_git_or_fail(["lfs", "install", "--local"], cwd=repo_dir)
        run_git_or_fail(["lfs", "track", "*.bin"], cwd=repo_dir)
        run_git_or_fail(["add", ".gitattributes"], cwd=repo_dir)
        run_git_or_fail(["commit", "-m", "Track .bin files"], cwd=repo_dir)

        # Add LFS file
        test_file = os.path.join(repo_dir, "test.bin")
        test_content = b"z" * 1024 * 1024  # 1MB
        with open(test_file, "wb") as f:
            f.write(test_content)
        run_git_or_fail(["add", "test.bin"], cwd=repo_dir)
        run_git_or_fail(["commit", "-m", "Add LFS file"], cwd=repo_dir)

        # Remove working copy
        os.remove(test_file)

        # Checkout with dulwich
        porcelain.reset(repo_dir, mode="hard")

        # Verify file contents
        with open(test_file, "rb") as f:
            content = f.read()
        self.assertEqual(content, test_content)


class LFSPointerCompatTest(LFSCompatTestCase):
    """Tests for LFS pointer file compatibility."""

    def test_pointer_format_dulwich(self):
        """Test that dulwich creates git-lfs compatible pointers."""
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        lfs_init(repo_dir)

        test_content = b"test content for LFS"
        test_file = os.path.join(repo_dir, "test.txt")
        with open(test_file, "wb") as f:
            f.write(test_content)

        # Create pointer with dulwich
        pointer_data = lfs_clean(repo_dir, "test.txt")

        # Parse with git-lfs (create a file and check)
        test_file = os.path.join(repo_dir, "test_pointer")
        with open(test_file, "wb") as f:
            f.write(pointer_data)

        # Verify pointer format
        with open(test_file, "rb") as f:
            lines = f.read().decode().strip().split("\n")

        self.assertEqual(lines[0], "version https://git-lfs.github.com/spec/v1")
        self.assertTrue(lines[1].startswith("oid sha256:"))
        self.assertTrue(lines[2].startswith("size "))

    def test_pointer_format_git(self):
        """Test that dulwich can parse git-lfs pointers."""
        # Create a git-lfs pointer manually
        oid = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        size = 12345
        pointer_content = f"version https://git-lfs.github.com/spec/v1\noid sha256:{oid}\nsize {size}\n"

        # Parse with dulwich
        pointer = LFSPointer.from_bytes(pointer_content.encode())

        self.assertEqual(pointer.oid, oid)
        self.assertEqual(pointer.size, size)


class LFSFilterCompatTest(LFSCompatTestCase):
    """Tests for LFS filter operations compatibility."""

    def test_clean_filter_compat(self):
        """Test clean filter compatibility between dulwich and git-lfs."""
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        lfs_init(repo_dir)

        test_content = b"x" * 1000
        test_file = os.path.join(repo_dir, "test.txt")
        with open(test_file, "wb") as f:
            f.write(test_content)

        # Clean with dulwich
        dulwich_pointer = lfs_clean(repo_dir, "test.txt")

        # Clean with git-lfs (simulate)
        # Since we can't easily invoke git-lfs clean directly,
        # we'll test that the pointer format is correct
        self.assertIn(b"version https://git-lfs.github.com/spec/v1", dulwich_pointer)
        self.assertIn(b"oid sha256:", dulwich_pointer)
        self.assertIn(b"size 1000", dulwich_pointer)

    def test_smudge_filter_compat(self):
        """Test smudge filter compatibility between dulwich and git-lfs."""
        # Create a test repo with LFS
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        lfs_init(repo_dir)

        # Create test content
        test_content = b"test data for smudge filter"
        test_file = os.path.join(repo_dir, "test.txt")
        with open(test_file, "wb") as f:
            f.write(test_content)

        pointer_data = lfs_clean(repo_dir, "test.txt")

        # Store object in LFS
        lfs_dir = os.path.join(repo_dir, ".git", "lfs")
        os.makedirs(lfs_dir, exist_ok=True)

        # Parse pointer to get oid
        pointer = LFSPointer.from_bytes(pointer_data)

        # Store object
        obj_dir = os.path.join(lfs_dir, "objects", pointer.oid[:2], pointer.oid[2:4])
        os.makedirs(obj_dir, exist_ok=True)
        obj_path = os.path.join(obj_dir, pointer.oid)
        with open(obj_path, "wb") as f:
            f.write(test_content)

        # Test smudge
        smudged = lfs_smudge(repo_dir, pointer_data)
        self.assertEqual(smudged, test_content)


class LFSStatusCompatTest(LFSCompatTestCase):
    """Tests for git status with LFS files (issue #1889)."""

    def test_status_with_lfs_files(self):
        """Test git status works correctly with LFS files.

        This reproduces issue #1889 where git status with LFS files
        would fail due to incorrect handling of the two-phase filter
        protocol response.
        """
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        # Disable autocrlf to avoid line ending issues on Windows
        run_git_or_fail(["config", "core.autocrlf", "false"], cwd=repo_dir)
        run_git_or_fail(["lfs", "install", "--local"], cwd=repo_dir)
        run_git_or_fail(["lfs", "track", "*.bin"], cwd=repo_dir)
        run_git_or_fail(["add", ".gitattributes"], cwd=repo_dir)
        run_git_or_fail(["commit", "-m", "Track .bin files"], cwd=repo_dir)

        # Add an LFS file
        test_file = os.path.join(repo_dir, "test.bin")
        test_content = b"x" * 1024 * 1024  # 1MB
        with open(test_file, "wb") as f:
            f.write(test_content)
        run_git_or_fail(["add", "test.bin"], cwd=repo_dir)
        run_git_or_fail(["commit", "-m", "Add LFS file"], cwd=repo_dir)

        # Now check status with dulwich - this should not raise FilterError
        # This should work without raising FilterError
        # Before the fix, this would fail with:
        # dulwich.filters.FilterError: Process filter smudge failed: error
        status = porcelain.status(repo_dir, untracked_files="no")

        # Verify status shows clean working tree
        self.assertEqual(status.staged["add"], [])
        self.assertEqual(status.staged["delete"], [])
        self.assertEqual(status.staged["modify"], [])
        self.assertEqual(status.unstaged, [])

    def test_status_with_modified_lfs_file(self):
        """Test git status with modified LFS files."""
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        # Disable autocrlf to avoid line ending issues on Windows
        run_git_or_fail(["config", "core.autocrlf", "false"], cwd=repo_dir)
        run_git_or_fail(["lfs", "install", "--local"], cwd=repo_dir)
        run_git_or_fail(["lfs", "track", "*.bin"], cwd=repo_dir)
        run_git_or_fail(["add", ".gitattributes"], cwd=repo_dir)
        run_git_or_fail(["commit", "-m", "Track .bin files"], cwd=repo_dir)

        # Add an LFS file
        test_file = os.path.join(repo_dir, "test.bin")
        with open(test_file, "wb") as f:
            f.write(b"original content\n")
        run_git_or_fail(["add", "test.bin"], cwd=repo_dir)
        run_git_or_fail(["commit", "-m", "Add LFS file"], cwd=repo_dir)

        # Modify the file
        with open(test_file, "wb") as f:
            f.write(b"slightly modified content\n")

        # Check status - should show file as modified
        status = porcelain.status(repo_dir, untracked_files="no")

        # File should be in unstaged changes
        self.assertIn(b"test.bin", status.unstaged)

    def test_status_with_multiple_lfs_files(self):
        """Test git status with multiple LFS files."""
        repo_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=repo_dir)
        # Disable autocrlf to avoid line ending issues on Windows
        run_git_or_fail(["config", "core.autocrlf", "false"], cwd=repo_dir)
        run_git_or_fail(["lfs", "install", "--local"], cwd=repo_dir)
        run_git_or_fail(["lfs", "track", "*.bin"], cwd=repo_dir)
        run_git_or_fail(["add", ".gitattributes"], cwd=repo_dir)
        run_git_or_fail(["commit", "-m", "Track .bin files"], cwd=repo_dir)

        # Add multiple LFS files
        for i in range(3):
            test_file = os.path.join(repo_dir, f"test{i}.bin")
            with open(test_file, "wb") as f:
                f.write(b"content" * 1000)
        run_git_or_fail(["add", "*.bin"], cwd=repo_dir)
        run_git_or_fail(["commit", "-m", "Add LFS files"], cwd=repo_dir)

        # Check status - should handle multiple files correctly
        status = porcelain.status(repo_dir, untracked_files="no")

        # All files should be clean
        self.assertEqual(status.staged["add"], [])
        self.assertEqual(status.staged["delete"], [])
        self.assertEqual(status.staged["modify"], [])
        self.assertEqual(status.unstaged, [])


class LFSCloneCompatTest(LFSCompatTestCase):
    """Tests for cloning repositories with LFS files."""

    @skipUnless(
        git_lfs_version() and git_lfs_version() >= (2, 0, 0),
        "git-lfs 2.0+ required for clone tests",
    )
    def test_clone_with_lfs(self):
        """Test cloning a repository with LFS files."""
        # Create source repo with LFS
        source_dir = self.make_temp_dir()
        run_git_or_fail(["init"], cwd=source_dir)
        run_git_or_fail(["lfs", "install", "--local"], cwd=source_dir)
        run_git_or_fail(["lfs", "track", "*.bin"], cwd=source_dir)
        run_git_or_fail(["add", ".gitattributes"], cwd=source_dir)
        run_git_or_fail(["commit", "-m", "Track .bin files"], cwd=source_dir)

        # Add LFS file
        test_file = os.path.join(source_dir, "test.bin")
        test_content = b"w" * 1024 * 1024  # 1MB
        with open(test_file, "wb") as f:
            f.write(test_content)
        run_git_or_fail(["add", "test.bin"], cwd=source_dir)
        run_git_or_fail(["commit", "-m", "Add LFS file"], cwd=source_dir)

        # Clone with dulwich
        target_dir = self.make_temp_dir()
        cloned_repo = porcelain.clone(source_dir, target_dir)
        self.addCleanup(cloned_repo.close)

        # Verify LFS file exists
        cloned_file = os.path.join(target_dir, "test.bin")
        with open(cloned_file, "rb") as f:
            content = f.read()

        # Check if filter.lfs.smudge is configured
        cloned_config = cloned_repo.get_config()
        try:
            lfs_smudge = cloned_config.get((b"filter", b"lfs"), b"smudge")
            has_lfs_config = bool(lfs_smudge)
        except KeyError:
            has_lfs_config = False

        if has_lfs_config:
            # git-lfs smudge filter should have converted it
            self.assertEqual(content, test_content)
        else:
            # No git-lfs config (uses built-in filter), should be a pointer
            self.assertIn(b"version https://git-lfs.github.com/spec/v1", content)


if __name__ == "__main__":
    import unittest

    unittest.main()