diff --git a/presubmit_support.py b/presubmit_support.py index 7e06021ea..c6e71beb7 100755 --- a/presubmit_support.py +++ b/presubmit_support.py @@ -584,6 +584,10 @@ class _DiffCache(object): """Get the diff for a particular path.""" raise NotImplementedError() + def GetOldContents(self, path, local_root): + """Get the old version for a particular path.""" + raise NotImplementedError() + class _GitDiffCache(_DiffCache): """DiffCache implementation for git; gets all file diffs at once.""" @@ -626,6 +630,9 @@ class _GitDiffCache(_DiffCache): return self._diffs_by_file[path] + def GetOldContents(self, path, local_root): + return scm.GIT.GetOldContents(local_root, path, branch=self._upstream) + class AffectedFile(object): """Representation of a file in a change.""" @@ -670,6 +677,18 @@ class AffectedFile(object): """An alias to IsTestableFile for backwards compatibility.""" return self.IsTestableFile() + def OldContents(self): + """Returns an iterator over the lines in the old version of file. + + The new version is the file in the user's workspace, i.e. the "right hand + side". + + Contents will be empty if the file is a directory or does not exist. + Note: The carriage returns (LF or CR) are stripped off. + """ + return self._diff_cache.GetOldContents(self.LocalPath(), + self._local_root).splitlines() + def NewContents(self): """Returns an iterator over the lines in the new version of file. diff --git a/scm.py b/scm.py index e08a6e051..613284556 100644 --- a/scm.py +++ b/scm.py @@ -254,6 +254,13 @@ class GIT(object): upstream_branch = ''.join(remote_ref) return upstream_branch + @staticmethod + def GetOldContents(cwd, filename, branch=None): + if not branch: + branch = GIT.GetUpstreamBranch(cwd) + command = ['show', '%s:%s' % (branch, filename)] + return GIT.Capture(command, cwd=cwd, strip_out=False) + @staticmethod def GenerateDiff(cwd, branch=None, branch_head='HEAD', full_move=False, files=None): diff --git a/tests/presubmit_unittest.py b/tests/presubmit_unittest.py index 831651a58..47ae63f93 100755 --- a/tests/presubmit_unittest.py +++ b/tests/presubmit_unittest.py @@ -1482,7 +1482,7 @@ class AffectedFileUnittest(PresubmitTestsBase): members = [ 'AbsoluteLocalPath', 'Action', 'ChangedContents', 'DIFF_CACHE', 'GenerateScmDiff', 'IsTestableFile', 'IsTextFile', 'LocalPath', - 'NewContents', + 'NewContents', 'OldContents', ] # If this test fails, you should add the relevant test. self.compareMembers( diff --git a/tests/scm_unittest.py b/tests/scm_unittest.py index 0ce422e34..400ca18c1 100755 --- a/tests/scm_unittest.py +++ b/tests/scm_unittest.py @@ -86,6 +86,7 @@ class GitWrapperTestCase(BaseSCMTestCase): 'GetDifferentFiles', 'GetEmail', 'GetGitDir', + 'GetOldContents', 'GetPatchName', 'GetUpstreamBranch', 'IsDirectoryVersioned',