def stagedChangesRevertFileContent(path): """Check whether the staged changes revert the changes of the HEAD commit for the given file.""" try: # By using the --exit-code option git will return 1 in case the diff # is not empty and 0 if it is. execute(GIT, "diff", "--staged", "--quiet", "--exit-code", "HEAD^", path) # If the git invocation succeeded the diff was empty and the # currently staged changes for the given file revert the ones made # in the HEAD commit. return True except ProcessError: # The diff was not empty or the command failed for some other # reason (e.g., because there is no HEAD^ commit). In any case, we # should go ahead with the commit. return False
def git(self, *args, **kwargs): """Run a git command.""" # If not requested otherwise we always start git with an empty # environment. We do not want any of the global/user-specific # configuration to have effect on the commands. kwargs.setdefault("env", {}) return execute(self._git, *args, **kwargs)
def changedFiles(): """Retrieve a list of changed files.""" # We only care for Added (A) and Modified (M) files. cmd = [ GIT, "diff", "--staged", "--name-only", "--diff-filter=AM", "--no-color", "--no-prefix" ] out, _ = execute(*cmd, stdout=b"") return out.decode("utf-8").splitlines()
def retrieveConfigValue(key, *args): """Retrieve a git configuration value associated with a key.""" try: name = "%s.%s" % (SECTION, key) cmd = [GIT, "config", "--null"] + list(args) + [name] out, _ = execute(*cmd, stdout=b"") # The output is guaranteed to be terminated by a NUL byte. We want # to discard that. return out[:-1].decode("utf-8") except ProcessError: # In case the configuration value is not set we just return None. return None
def testFileHeaderCheck(self): """Verify that incorrect file headers are flagged properly.""" with NamedTemporaryFile(buffering=0) as f1,\ NamedTemporaryFile(buffering=0) as f2,\ NamedTemporaryFile(buffering=0) as f3: # A binary file. f1.write( bytes("".join(chr(randint(0, 255)) for _ in range(512)), "utf-8")) # Some text file without correct header. f2.write(bytes("# Copyright (C) 2016", "utf-8")) # Some text file with correct header. f3.write( bytes("# %s\n# Copyright (C) 2016" % (basename(f3.name)), "utf-8")) regex = r"%s does not contain" % basename(f1.name) with self.assertRaisesRegex(ProcessError, regex): execute(executable, FILE_HEADER, f1.name, f2.name, f3.name) regex = r"%s does not contain" % basename(f2.name) with self.assertRaisesRegex(ProcessError, regex): execute(executable, FILE_HEADER, f2.name, f3.name) execute(executable, FILE_HEADER, f3.name)
def stageFile(path): """Stage a file in git.""" execute(GIT, "add", path)
def stagedFileContent(path): """Retrieve the file content of a file in a git repository including any staged changes.""" out, _ = execute(GIT, "cat-file", "--textconv", ":%s" % path, stdout=b"") return out.decode("utf-8")