From 5fffb1783a1e70c71349a4be91c490fa84dcb16d Mon Sep 17 00:00:00 2001 From: Jarkko Linnanvirta Date: Mon, 13 Jan 2020 13:07:23 +0200 Subject: [PATCH] GitRepository: Create isFileCommitted() method. --- src/GitRepository.php | 37 +++++++++++++++++++++++++++++++++++++ src/IGit.php | 8 ++++++++ 2 files changed, 45 insertions(+) diff --git a/src/GitRepository.php b/src/GitRepository.php index 91968d5..c42530d 100644 --- a/src/GitRepository.php +++ b/src/GitRepository.php @@ -958,5 +958,42 @@ public function getCommitData($commit) return $data; } + + /** + * Checks whether the given file is committed to the git repository. Staged files are not counted as committed + * files - unless they are both staged an committed previously. + * + * Uses `git ls-files --error-unmatch ` + * + * @param string $filename + * @return bool + * @throws GitException + */ + public function isFileCommitted($filename) + { + $this->begin(); + try { + $this->run('git ls-files --error-unmatch', [$filename]); + } + catch (GitException $git_exception) { + switch ($git_exception->getCode()) { + case 1: + // The `git ls-files --error-unmatch` command didn't find the given file in git and has yelled an error + // number 1. This exception can be considered normal. We can just report that the file is not in git and + // continue execution normally. + $this->end(); + return FALSE; + break; + default: + // An unrecognised error has occurred. Rethrow the exception. + $this->end(); + throw $git_exception; + break; + } + } + // As the command didn't give any error code when exiting, it's a sign for us to know that the file _does_ exist in git. + $this->end(); + return TRUE; + } } diff --git a/src/IGit.php b/src/IGit.php index 200f096..0928533 100644 --- a/src/IGit.php +++ b/src/IGit.php @@ -230,6 +230,14 @@ static function init($directory, array $params = NULL); * @return self */ static function cloneRepository($url, $directory = NULL); + + /** + * Checks whether the given file is committed to the git repository. + * + * @param string $filename + * @return bool + */ + public function isFileCommitted($filename); }