diff --git a/dulwich/patch.py b/dulwich/patch.py index ea1bdfe1..3cc4eba2 100644 --- a/dulwich/patch.py +++ b/dulwich/patch.py @@ -1,374 +1,374 @@ # patch.py -- For dealing with packed-style patches. # Copyright (C) 2009-2013 Jelmer Vernooij # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public 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 # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Classes for dealing with git am-style patches. These patches are basically unified diffs with some extra metadata tacked on. """ from difflib import SequenceMatcher import email.parser import time from dulwich.objects import ( Blob, Commit, S_ISGITLINK, ) FIRST_FEW_BYTES = 8000 def write_commit_patch(f, commit, contents, progress, version=None, encoding=None): """Write a individual file patch. Args: commit: Commit object progress: Tuple with current patch number and total. Returns: tuple with filename and contents """ encoding = encoding or getattr(f, "encoding", "ascii") if isinstance(contents, str): contents = contents.encode(encoding) (num, total) = progress f.write(b"From " + commit.id + b" " + time.ctime(commit.commit_time).encode(encoding) + b"\n") f.write(b"From: " + commit.author + b"\n") f.write(b"Date: " + time.strftime("%a, %d %b %Y %H:%M:%S %Z").encode(encoding) + b"\n") f.write(("Subject: [PATCH %d/%d] " % (num, total)).encode(encoding) + commit.message + b"\n") f.write(b"\n") f.write(b"---\n") try: import subprocess p = subprocess.Popen(["diffstat"], stdout=subprocess.PIPE, stdin=subprocess.PIPE) except (ImportError, OSError): pass # diffstat not available? else: (diffstat, _) = p.communicate(contents) f.write(diffstat) f.write(b"\n") f.write(contents) f.write(b"-- \n") if version is None: from dulwich import __version__ as dulwich_version f.write(b"Dulwich %d.%d.%d\n" % dulwich_version) else: f.write(version.encode(encoding) + b"\n") def get_summary(commit): """Determine the summary line for use in a filename. Args: commit: Commit Returns: Summary string """ decoded = commit.message.decode(errors='replace') return decoded.splitlines()[0].replace(" ", "-") # Unified Diff def _format_range_unified(start, stop): 'Convert range to the "ed" format' # Per the diff spec at http://www.unix.org/single_unix_specification/ beginning = start + 1 # lines start numbering with one length = stop - start if length == 1: return '{}'.format(beginning) if not length: beginning -= 1 # empty ranges begin at line just before the range return '{},{}'.format(beginning, length) def unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n'): """difflib.unified_diff that can detect "No newline at end of file" as original "git diff" does. Based on the same function in Python2.7 difflib.py """ started = False for group in SequenceMatcher(None, a, b).get_grouped_opcodes(n): if not started: started = True fromdate = '\t{}'.format(fromfiledate) if fromfiledate else '' todate = '\t{}'.format(tofiledate) if tofiledate else '' yield '--- {}{}{}'.format( fromfile.decode("ascii"), fromdate, lineterm ).encode('ascii') yield '+++ {}{}{}'.format( tofile.decode("ascii"), todate, lineterm ).encode('ascii') first, last = group[0], group[-1] file1_range = _format_range_unified(first[1], last[2]) file2_range = _format_range_unified(first[3], last[4]) yield '@@ -{} +{} @@{}'.format( file1_range, file2_range, lineterm ).encode('ascii') for tag, i1, i2, j1, j2 in group: if tag == 'equal': for line in a[i1:i2]: yield b' ' + line continue if tag in ('replace', 'delete'): for line in a[i1:i2]: if not line[-1:] == b'\n': line += b'\n\\ No newline at end of file\n' yield b'-' + line if tag in ('replace', 'insert'): for line in b[j1:j2]: if not line[-1:] == b'\n': line += b'\n\\ No newline at end of file\n' yield b'+' + line def is_binary(content): """See if the first few bytes contain any null characters. Args: content: Bytestring to check for binary content """ return b'\0' in content[:FIRST_FEW_BYTES] def shortid(hexsha): if hexsha is None: return b"0" * 7 else: return hexsha[:7] def patch_filename(p, root): if p is None: return b"/dev/null" else: return root + b"/" + p def write_object_diff(f, store, old_file, new_file, diff_binary=False): """Write the diff for an object. Args: f: File-like object to write to store: Store to retrieve objects from, if necessary old_file: (path, mode, hexsha) tuple new_file: (path, mode, hexsha) tuple diff_binary: Whether to diff files even if they are considered binary files by is_binary(). Note: the tuple elements should be None for nonexistant files """ (old_path, old_mode, old_id) = old_file (new_path, new_mode, new_id) = new_file patched_old_path = patch_filename(old_path, b"a") patched_new_path = patch_filename(new_path, b"b") def content(mode, hexsha): if hexsha is None: return Blob.from_string(b'') elif S_ISGITLINK(mode): - return Blob.from_string(b"Submodule commit " + hexsha + b"\n") + return Blob.from_string(b"Subproject commit " + hexsha + b"\n") else: return store[hexsha] def lines(content): if not content: return [] else: return content.splitlines() f.writelines(gen_diff_header( (old_path, new_path), (old_mode, new_mode), (old_id, new_id))) old_content = content(old_mode, old_id) new_content = content(new_mode, new_id) if not diff_binary and ( is_binary(old_content.data) or is_binary(new_content.data)): binary_diff = ( b"Binary files " + patched_old_path + b" and " + patched_new_path + b" differ\n" ) f.write(binary_diff) else: f.writelines(unified_diff(lines(old_content), lines(new_content), patched_old_path, patched_new_path)) # TODO(jelmer): Support writing unicode, rather than bytes. def gen_diff_header(paths, modes, shas): """Write a blob diff header. Args: paths: Tuple with old and new path modes: Tuple with old and new modes shas: Tuple with old and new shas """ (old_path, new_path) = paths (old_mode, new_mode) = modes (old_sha, new_sha) = shas if old_path is None and new_path is not None: old_path = new_path if new_path is None and old_path is not None: new_path = old_path old_path = patch_filename(old_path, b"a") new_path = patch_filename(new_path, b"b") yield b"diff --git " + old_path + b" " + new_path + b"\n" if old_mode != new_mode: if new_mode is not None: if old_mode is not None: yield ("old file mode %o\n" % old_mode).encode('ascii') yield ("new file mode %o\n" % new_mode).encode('ascii') else: yield ("deleted file mode %o\n" % old_mode).encode('ascii') yield b"index " + shortid(old_sha) + b".." + shortid(new_sha) if new_mode is not None and old_mode is not None: yield (" %o" % new_mode).encode('ascii') yield b"\n" # TODO(jelmer): Support writing unicode, rather than bytes. def write_blob_diff(f, old_file, new_file): """Write blob diff. Args: f: File-like object to write to old_file: (path, mode, hexsha) tuple (None if nonexisting) new_file: (path, mode, hexsha) tuple (None if nonexisting) Note: The use of write_object_diff is recommended over this function. """ (old_path, old_mode, old_blob) = old_file (new_path, new_mode, new_blob) = new_file patched_old_path = patch_filename(old_path, b"a") patched_new_path = patch_filename(new_path, b"b") def lines(blob): if blob is not None: return blob.splitlines() else: return [] f.writelines(gen_diff_header( (old_path, new_path), (old_mode, new_mode), (getattr(old_blob, "id", None), getattr(new_blob, "id", None)))) old_contents = lines(old_blob) new_contents = lines(new_blob) f.writelines(unified_diff(old_contents, new_contents, patched_old_path, patched_new_path)) def write_tree_diff(f, store, old_tree, new_tree, diff_binary=False): """Write tree diff. Args: f: File-like object to write to. old_tree: Old tree id new_tree: New tree id diff_binary: Whether to diff files even if they are considered binary files by is_binary(). """ changes = store.tree_changes(old_tree, new_tree) for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes: write_object_diff(f, store, (oldpath, oldmode, oldsha), (newpath, newmode, newsha), diff_binary=diff_binary) def git_am_patch_split(f, encoding=None): """Parse a git-am-style patch and split it up into bits. Args: f: File-like object to parse encoding: Encoding to use when creating Git objects Returns: Tuple with commit object, diff contents and git version """ encoding = encoding or getattr(f, "encoding", "ascii") encoding = encoding or "ascii" contents = f.read() if (isinstance(contents, bytes) and getattr(email.parser, "BytesParser", None)): parser = email.parser.BytesParser() msg = parser.parsebytes(contents) else: parser = email.parser.Parser() msg = parser.parsestr(contents) return parse_patch_message(msg, encoding) def parse_patch_message(msg, encoding=None): """Extract a Commit object and patch from an e-mail message. Args: msg: An email message (email.message.Message) encoding: Encoding to use to encode Git commits Returns: Tuple with commit object, diff contents and git version """ c = Commit() c.author = msg["from"].encode(encoding) c.committer = msg["from"].encode(encoding) try: patch_tag_start = msg["subject"].index("[PATCH") except ValueError: subject = msg["subject"] else: close = msg["subject"].index("] ", patch_tag_start) subject = msg["subject"][close+2:] c.message = (subject.replace("\n", "") + "\n").encode(encoding) first = True body = msg.get_payload(decode=True) lines = body.splitlines(True) line_iter = iter(lines) for line in line_iter: if line == b"---\n": break if first: if line.startswith(b"From: "): c.author = line[len(b"From: "):].rstrip() else: c.message += b"\n" + line first = False else: c.message += line diff = b"" for line in line_iter: if line == b"-- \n": break diff += line try: version = next(line_iter).rstrip(b"\n") except StopIteration: version = None return c, diff, version diff --git a/dulwich/tests/test_patch.py b/dulwich/tests/test_patch.py index 0c407277..8deeab81 100644 --- a/dulwich/tests/test_patch.py +++ b/dulwich/tests/test_patch.py @@ -1,552 +1,552 @@ # test_patch.py -- tests for patch.py # Copyright (C) 2010 Jelmer Vernooij # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public 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 # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for patch.py.""" from io import BytesIO, StringIO from dulwich.objects import ( Blob, Commit, S_IFGITLINK, Tree, ) from dulwich.object_store import ( MemoryObjectStore, ) from dulwich.patch import ( get_summary, git_am_patch_split, write_blob_diff, write_commit_patch, write_object_diff, write_tree_diff, ) from dulwich.tests import ( SkipTest, TestCase, ) class WriteCommitPatchTests(TestCase): def test_simple_bytesio(self): f = BytesIO() c = Commit() c.committer = c.author = b"Jelmer " c.commit_time = c.author_time = 1271350201 c.commit_timezone = c.author_timezone = 0 c.message = b"This is the first line\nAnd this is the second line.\n" c.tree = Tree().id write_commit_patch(f, c, b"CONTENTS", (1, 1), version="custom") f.seek(0) lines = f.readlines() self.assertTrue(lines[0].startswith( b"From 0b0d34d1b5b596c928adc9a727a4b9e03d025298")) self.assertEqual(lines[1], b"From: Jelmer \n") self.assertTrue(lines[2].startswith(b"Date: ")) self.assertEqual([ b"Subject: [PATCH 1/1] This is the first line\n", b"And this is the second line.\n", b"\n", b"\n", b"---\n"], lines[3:8]) self.assertEqual([ b"CONTENTS-- \n", b"custom\n"], lines[-2:]) if len(lines) >= 12: # diffstat may not be present self.assertEqual(lines[8], b" 0 files changed\n") class ReadGitAmPatch(TestCase): def test_extract_string(self): text = b"""\ From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [PATCH 1/2] Remove executable bit from prey.ico (triggers a warning). --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico -- 1.7.0.4 """ # noqa: W291 c, diff, version = git_am_patch_split( StringIO(text.decode("utf-8")), "utf-8") self.assertEqual(b"Jelmer Vernooij ", c.committer) self.assertEqual(b"Jelmer Vernooij ", c.author) self.assertEqual(b"Remove executable bit from prey.ico " b"(triggers a warning).\n", c.message) self.assertEqual(b""" pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico """, diff) self.assertEqual(b"1.7.0.4", version) def test_extract_bytes(self): text = b"""\ From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [PATCH 1/2] Remove executable bit from prey.ico (triggers a warning). --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico -- 1.7.0.4 """ # noqa: W291 c, diff, version = git_am_patch_split(BytesIO(text)) self.assertEqual(b"Jelmer Vernooij ", c.committer) self.assertEqual(b"Jelmer Vernooij ", c.author) self.assertEqual(b"Remove executable bit from prey.ico " b"(triggers a warning).\n", c.message) self.assertEqual(b""" pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico """, diff) self.assertEqual(b"1.7.0.4", version) def test_extract_spaces(self): text = b"""From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [Dulwich-users] [PATCH] Added unit tests for dulwich.object_store.tree_lookup_path. * dulwich/tests/test_object_store.py (TreeLookupPathTests): This test case contains a few tests that ensure the tree_lookup_path function works as expected. --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico -- 1.7.0.4 """ # noqa: W291 c, diff, version = git_am_patch_split(BytesIO(text), "utf-8") self.assertEqual(b'''\ Added unit tests for dulwich.object_store.tree_lookup_path. * dulwich/tests/test_object_store.py (TreeLookupPathTests): This test case contains a few tests that ensure the tree_lookup_path function works as expected. ''', c.message) def test_extract_pseudo_from_header(self): text = b"""From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [Dulwich-users] [PATCH] Added unit tests for dulwich.object_store.tree_lookup_path. From: Jelmer Vernooij * dulwich/tests/test_object_store.py (TreeLookupPathTests): This test case contains a few tests that ensure the tree_lookup_path function works as expected. --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico -- 1.7.0.4 """ # noqa: W291 c, diff, version = git_am_patch_split(BytesIO(text), "utf-8") self.assertEqual(b"Jelmer Vernooij ", c.author) self.assertEqual(b'''\ Added unit tests for dulwich.object_store.tree_lookup_path. * dulwich/tests/test_object_store.py (TreeLookupPathTests): This test case contains a few tests that ensure the tree_lookup_path function works as expected. ''', c.message) def test_extract_no_version_tail(self): text = b"""\ From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [Dulwich-users] [PATCH] Added unit tests for dulwich.object_store.tree_lookup_path. From: Jelmer Vernooij --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico """ c, diff, version = git_am_patch_split(BytesIO(text), "utf-8") self.assertEqual(None, version) def test_extract_mercurial(self): raise SkipTest( "git_am_patch_split doesn't handle Mercurial patches " "properly yet") expected_diff = """\ diff --git a/dulwich/tests/test_patch.py b/dulwich/tests/test_patch.py --- a/dulwich/tests/test_patch.py +++ b/dulwich/tests/test_patch.py @@ -158,7 +158,7 @@ ''' c, diff, version = git_am_patch_split(BytesIO(text)) - self.assertIs(None, version) + self.assertEqual(None, version) class DiffTests(TestCase): """ # noqa: W291,W293 text = """\ From dulwich-users-bounces+jelmer=samba.org@lists.launchpad.net \ Mon Nov 29 00:58:18 2010 Date: Sun, 28 Nov 2010 17:57:27 -0600 From: Augie Fackler To: dulwich-users Subject: [Dulwich-users] [PATCH] test_patch: fix tests on Python 2.6 Content-Transfer-Encoding: 8bit Change-Id: I5e51313d4ae3a65c3f00c665002a7489121bb0d6 %s _______________________________________________ Mailing list: https://launchpad.net/~dulwich-users Post to : dulwich-users@lists.launchpad.net Unsubscribe : https://launchpad.net/~dulwich-users More help : https://help.launchpad.net/ListHelp """ % expected_diff # noqa: W291 c, diff, version = git_am_patch_split(BytesIO(text)) self.assertEqual(expected_diff, diff) self.assertEqual(None, version) class DiffTests(TestCase): """Tests for write_blob_diff and write_tree_diff.""" def test_blob_diff(self): f = BytesIO() write_blob_diff( f, (b"foo.txt", 0o644, Blob.from_string(b"old\nsame\n")), (b"bar.txt", 0o644, Blob.from_string(b"new\nsame\n"))) self.assertEqual([ b"diff --git a/foo.txt b/bar.txt", b"index 3b0f961..a116b51 644", b"--- a/foo.txt", b"+++ b/bar.txt", b"@@ -1,2 +1,2 @@", b"-old", b"+new", b" same" ], f.getvalue().splitlines()) def test_blob_add(self): f = BytesIO() write_blob_diff( f, (None, None, None), (b"bar.txt", 0o644, Blob.from_string(b"new\nsame\n"))) self.assertEqual([ b'diff --git a/bar.txt b/bar.txt', b'new file mode 644', b'index 0000000..a116b51', b'--- /dev/null', b'+++ b/bar.txt', b'@@ -0,0 +1,2 @@', b'+new', b'+same' ], f.getvalue().splitlines()) def test_blob_remove(self): f = BytesIO() write_blob_diff( f, (b"bar.txt", 0o644, Blob.from_string(b"new\nsame\n")), (None, None, None)) self.assertEqual([ b'diff --git a/bar.txt b/bar.txt', b'deleted file mode 644', b'index a116b51..0000000', b'--- a/bar.txt', b'+++ /dev/null', b'@@ -1,2 +0,0 @@', b'-new', b'-same' ], f.getvalue().splitlines()) def test_tree_diff(self): f = BytesIO() store = MemoryObjectStore() added = Blob.from_string(b"add\n") removed = Blob.from_string(b"removed\n") changed1 = Blob.from_string(b"unchanged\nremoved\n") changed2 = Blob.from_string(b"unchanged\nadded\n") unchanged = Blob.from_string(b"unchanged\n") tree1 = Tree() tree1.add(b"removed.txt", 0o644, removed.id) tree1.add(b"changed.txt", 0o644, changed1.id) tree1.add(b"unchanged.txt", 0o644, changed1.id) tree2 = Tree() tree2.add(b"added.txt", 0o644, added.id) tree2.add(b"changed.txt", 0o644, changed2.id) tree2.add(b"unchanged.txt", 0o644, changed1.id) store.add_objects([(o, None) for o in [ tree1, tree2, added, removed, changed1, changed2, unchanged]]) write_tree_diff(f, store, tree1.id, tree2.id) self.assertEqual([ b'diff --git a/added.txt b/added.txt', b'new file mode 644', b'index 0000000..76d4bb8', b'--- /dev/null', b'+++ b/added.txt', b'@@ -0,0 +1 @@', b'+add', b'diff --git a/changed.txt b/changed.txt', b'index bf84e48..1be2436 644', b'--- a/changed.txt', b'+++ b/changed.txt', b'@@ -1,2 +1,2 @@', b' unchanged', b'-removed', b'+added', b'diff --git a/removed.txt b/removed.txt', b'deleted file mode 644', b'index 2c3f0b3..0000000', b'--- a/removed.txt', b'+++ /dev/null', b'@@ -1 +0,0 @@', b'-removed', ], f.getvalue().splitlines()) def test_tree_diff_submodule(self): f = BytesIO() store = MemoryObjectStore() tree1 = Tree() tree1.add(b"asubmodule", S_IFGITLINK, b"06d0bdd9e2e20377b3180e4986b14c8549b393e4") tree2 = Tree() tree2.add(b"asubmodule", S_IFGITLINK, b"cc975646af69f279396d4d5e1379ac6af80ee637") store.add_objects([(o, None) for o in [tree1, tree2]]) write_tree_diff(f, store, tree1.id, tree2.id) self.assertEqual([ b'diff --git a/asubmodule b/asubmodule', b'index 06d0bdd..cc97564 160000', b'--- a/asubmodule', b'+++ b/asubmodule', b'@@ -1 +1 @@', - b'-Submodule commit 06d0bdd9e2e20377b3180e4986b14c8549b393e4', - b'+Submodule commit cc975646af69f279396d4d5e1379ac6af80ee637', + b'-Subproject commit 06d0bdd9e2e20377b3180e4986b14c8549b393e4', + b'+Subproject commit cc975646af69f279396d4d5e1379ac6af80ee637', ], f.getvalue().splitlines()) def test_object_diff_blob(self): f = BytesIO() b1 = Blob.from_string(b"old\nsame\n") b2 = Blob.from_string(b"new\nsame\n") store = MemoryObjectStore() store.add_objects([(b1, None), (b2, None)]) write_object_diff(f, store, (b"foo.txt", 0o644, b1.id), (b"bar.txt", 0o644, b2.id)) self.assertEqual([ b"diff --git a/foo.txt b/bar.txt", b"index 3b0f961..a116b51 644", b"--- a/foo.txt", b"+++ b/bar.txt", b"@@ -1,2 +1,2 @@", b"-old", b"+new", b" same" ], f.getvalue().splitlines()) def test_object_diff_add_blob(self): f = BytesIO() store = MemoryObjectStore() b2 = Blob.from_string(b"new\nsame\n") store.add_object(b2) write_object_diff(f, store, (None, None, None), (b"bar.txt", 0o644, b2.id)) self.assertEqual([ b'diff --git a/bar.txt b/bar.txt', b'new file mode 644', b'index 0000000..a116b51', b'--- /dev/null', b'+++ b/bar.txt', b'@@ -0,0 +1,2 @@', b'+new', b'+same' ], f.getvalue().splitlines()) def test_object_diff_remove_blob(self): f = BytesIO() b1 = Blob.from_string(b"new\nsame\n") store = MemoryObjectStore() store.add_object(b1) write_object_diff(f, store, (b"bar.txt", 0o644, b1.id), (None, None, None)) self.assertEqual([ b'diff --git a/bar.txt b/bar.txt', b'deleted file mode 644', b'index a116b51..0000000', b'--- a/bar.txt', b'+++ /dev/null', b'@@ -1,2 +0,0 @@', b'-new', b'-same' ], f.getvalue().splitlines()) def test_object_diff_bin_blob_force(self): f = BytesIO() # Prepare two slightly different PNG headers b1 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x04\x00\x00\x00\x05\x04\x8b") b2 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x03\x00\x00\x00\x98\xd3\xb3") store = MemoryObjectStore() store.add_objects([(b1, None), (b2, None)]) write_object_diff( f, store, (b'foo.png', 0o644, b1.id), (b'bar.png', 0o644, b2.id), diff_binary=True) self.assertEqual([ b'diff --git a/foo.png b/bar.png', b'index f73e47d..06364b7 644', b'--- a/foo.png', b'+++ b/bar.png', b'@@ -1,4 +1,4 @@', b' \x89PNG', b' \x1a', b' \x00\x00\x00', b'-IHDR\x00\x00\x01\xd5\x00\x00\x00' b'\x9f\x08\x04\x00\x00\x00\x05\x04\x8b', b'\\ No newline at end of file', b'+IHDR\x00\x00\x01\xd5\x00\x00\x00\x9f' b'\x08\x03\x00\x00\x00\x98\xd3\xb3', b'\\ No newline at end of file' ], f.getvalue().splitlines()) def test_object_diff_bin_blob(self): f = BytesIO() # Prepare two slightly different PNG headers b1 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x04\x00\x00\x00\x05\x04\x8b") b2 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x03\x00\x00\x00\x98\xd3\xb3") store = MemoryObjectStore() store.add_objects([(b1, None), (b2, None)]) write_object_diff(f, store, (b'foo.png', 0o644, b1.id), (b'bar.png', 0o644, b2.id)) self.assertEqual([ b'diff --git a/foo.png b/bar.png', b'index f73e47d..06364b7 644', b'Binary files a/foo.png and b/bar.png differ' ], f.getvalue().splitlines()) def test_object_diff_add_bin_blob(self): f = BytesIO() b2 = Blob.from_string( b'\x89\x50\x4e\x47\x0d\x0a\x1a\x0a' b'\x00\x00\x00\x0d\x49\x48\x44\x52' b'\x00\x00\x01\xd5\x00\x00\x00\x9f' b'\x08\x03\x00\x00\x00\x98\xd3\xb3') store = MemoryObjectStore() store.add_object(b2) write_object_diff(f, store, (None, None, None), (b'bar.png', 0o644, b2.id)) self.assertEqual([ b'diff --git a/bar.png b/bar.png', b'new file mode 644', b'index 0000000..06364b7', b'Binary files /dev/null and b/bar.png differ' ], f.getvalue().splitlines()) def test_object_diff_remove_bin_blob(self): f = BytesIO() b1 = Blob.from_string( b'\x89\x50\x4e\x47\x0d\x0a\x1a\x0a' b'\x00\x00\x00\x0d\x49\x48\x44\x52' b'\x00\x00\x01\xd5\x00\x00\x00\x9f' b'\x08\x04\x00\x00\x00\x05\x04\x8b') store = MemoryObjectStore() store.add_object(b1) write_object_diff(f, store, (b'foo.png', 0o644, b1.id), (None, None, None)) self.assertEqual([ b'diff --git a/foo.png b/foo.png', b'deleted file mode 644', b'index f73e47d..0000000', b'Binary files a/foo.png and /dev/null differ' ], f.getvalue().splitlines()) def test_object_diff_kind_change(self): f = BytesIO() b1 = Blob.from_string(b"new\nsame\n") store = MemoryObjectStore() store.add_object(b1) write_object_diff( f, store, (b"bar.txt", 0o644, b1.id), (b"bar.txt", 0o160000, b"06d0bdd9e2e20377b3180e4986b14c8549b393e4")) self.assertEqual([ b'diff --git a/bar.txt b/bar.txt', b'old file mode 644', b'new file mode 160000', b'index a116b51..06d0bdd 160000', b'--- a/bar.txt', b'+++ b/bar.txt', b'@@ -1,2 +1 @@', b'-new', b'-same', - b'+Submodule commit 06d0bdd9e2e20377b3180e4986b14c8549b393e4', + b'+Subproject commit 06d0bdd9e2e20377b3180e4986b14c8549b393e4', ], f.getvalue().splitlines()) class GetSummaryTests(TestCase): def test_simple(self): c = Commit() c.committer = c.author = b"Jelmer " c.commit_time = c.author_time = 1271350201 c.commit_timezone = c.author_timezone = 0 c.message = b"This is the first line\nAnd this is the second line.\n" c.tree = Tree().id self.assertEqual('This-is-the-first-line', get_summary(c))