[layerindex-web,v2,1/3] layerindex/utils.py: add is_commit_ancestor check

Message ID 20220428145834.3046017-1-tim.orling@konsulko.com
State Accepted, archived
Commit ee30a2e03730ccfee7e3099e15f9024385ef3d0f
Delegated to: Tim Orling
Headers show
Series [layerindex-web,v2,1/3] layerindex/utils.py: add is_commit_ancestor check | expand

Commit Message

Tim Orling April 28, 2022, 2:58 p.m. UTC
Add a helper function to check if a given SHA1 hash is an ancestor in
the currently checked out branch, using:

git merge-branch --is-ancestor <commit> HEAD

NOTE: This will not match commits which have been cherry-picked.

Signed-off-by: Tim Orling <tim.orling@konsulko.com>
---
Changes in v2:
  * Fix import of (subprocess.)CalledProcessError

 layerindex/utils.py | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)

Patch

diff --git a/layerindex/utils.py b/layerindex/utils.py
index 32be16d..aaf8c52 100644
--- a/layerindex/utils.py
+++ b/layerindex/utils.py
@@ -229,6 +229,28 @@  def explode_dep_versions2(bitbakepath, deps):
     import bb.utils
     return bb.utils.explode_dep_versions2(deps)
 
+def is_commit_ancestor(repodir, commit, logger):
+    """
+    Check if the given SHA1 hash is an ancestor in the currently checked out branch.
+    NOTE: This will not match commits which have been cherry-picked.
+    """
+    try:
+        # check if commit is a sha1 hash
+        if re.match('[0-9a-f]{40}', commit):
+            # check if the commit is an ancestor
+            contained = runcmd(['git', 'merge-base', '--is-ancestor', '%s' % commit, 'HEAD'], repodir, logger=logger)
+            return True
+        else:
+            raise Exception('is_commit_ancestor: "commit" must be a SHA1 hash')
+    except subprocess.CalledProcessError as e:
+            if e.returncode == 1:
+                # commit is not an ancestor
+                return False
+            else:
+                raise e
+    except Exception as esc:
+        logger.warn(esc)
+
 def checkout_repo(repodir, commit, logger, force=False):
     """
     Check out a revision in a repository, ensuring that untracked/uncommitted