From d83d6ad7230eb27afae4169330681967bb20dcfa Mon Sep 17 00:00:00 2001 From: Richard Maw Date: Mon, 11 Nov 2013 17:25:13 +0000 Subject: GitDir: add store_blob method This is needed for making commits without touching the workspace. --- morphlib/gitdir.py | 15 +++++++++++++++ morphlib/gitdir_tests.py | 13 +++++++++++++ 2 files changed, 28 insertions(+) diff --git a/morphlib/gitdir.py b/morphlib/gitdir.py index b08f69d2..4ba4cd9c 100644 --- a/morphlib/gitdir.py +++ b/morphlib/gitdir.py @@ -257,6 +257,21 @@ class GitDirectory(object): if code not in ('??', '!!'): yield code, to_path, from_path + def store_blob(self, blob_contents): + '''Hash `blob_contents`, store it in git and return the sha1. + + `blob_contents` must either be a string or a value suitable to + pass to subprocess.Popen i.e. a file descriptor or file object + with fileno() method. + + ''' + if isinstance(blob_contents, basestring): + kwargs = {'feed_stdin': blob_contents} + else: + kwargs = {'stdin': blob_contents} + return self._runcmd(['git', 'hash-object', '-t', 'blob', + '-w', '--stdin'], **kwargs).strip() + def init(dirname): '''Initialise a new git repository.''' diff --git a/morphlib/gitdir_tests.py b/morphlib/gitdir_tests.py index a2e530f1..395ee2e5 100644 --- a/morphlib/gitdir_tests.py +++ b/morphlib/gitdir_tests.py @@ -160,6 +160,19 @@ class GitDirectoryContentsTests(unittest.TestCase): self.assertEqual(len(tree), 40) self.assertNotEqual(commit, tree) + def test_store_blob_with_string(self): + gd = morphlib.gitdir.GitDirectory(self.dirname) + sha1 = gd.store_blob('test string') + self.assertEqual('test string', gd.get_blob_contents(sha1)) + + def test_store_blob_with_file(self): + gd = morphlib.gitdir.GitDirectory(self.dirname) + with open(os.path.join(self.tempdir, 'blob'), 'w') as f: + f.write('test string') + with open(os.path.join(self.tempdir, 'blob'), 'r') as f: + sha1 = gd.store_blob(f) + self.assertEqual('test string', gd.get_blob_contents(sha1)) + def test_uncommitted_changes(self): gd = morphlib.gitdir.GitDirectory(self.dirname) self.assertEqual(sorted(gd.get_uncommitted_changes()), -- cgit v1.2.1