githead

1.2.2 · active · verified Thu Apr 16

Githead is a lightweight Python utility library designed to retrieve the current Git commit hash (HEAD) of a repository. It provides a straightforward function to get this information, making it useful for embedding version data in applications or scripts. The library is currently at version 1.2.2 and is actively maintained, with updates released as needed for its focused functionality. It requires Python 3.9 or higher.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import and use the `githead` function to retrieve the current Git commit hash. The example includes robust error handling for environments that may not be within an initialized Git repository, creating a temporary one for demonstration purposes.

import os
from githead import githead

def get_current_commit_hash():
    try:
        # Ensure we are in a directory that is a git repository
        # For demonstration, we'll try to create a dummy git repo if not found
        # In a real application, you'd assume a git repo or handle the error.
        
        # Check if .git directory exists in current or parent directory
        current_dir = os.getcwd()
        is_git_repo = False
        for _ in range(5): # Check up to 5 parent directories
            if os.path.exists(os.path.join(current_dir, '.git')):
                is_git_repo = True
                break
            parent_dir = os.path.dirname(current_dir)
            if parent_dir == current_dir: # Reached root
                break
            current_dir = parent_dir

        if not is_git_repo:
            # This block is for demonstration; normally, you'd expect a repo.
            # For a quickstart to run, we mock a git repo for a moment.
            print("Not in a Git repository. Initializing a temporary one for demonstration...")
            os.makedirs("temp_git_repo", exist_ok=True)
            original_cwd = os.getcwd()
            os.chdir("temp_git_repo")
            os.system("git init > /dev/null 2>&1")
            with open("test_file.txt", "w") as f:
                f.write("Hello Githead!")
            os.system("git add . > /dev/null 2>&1")
            os.system("git commit -m \"Initial commit\" > /dev/null 2>&1")
            
            commit_hash = githead()
            os.chdir(original_cwd)
            import shutil
            shutil.rmtree("temp_git_repo")
            return commit_hash
        else:
            return githead()

    except Exception as e:
        return f"Error getting commit hash: {e}"

print(f"Current Git HEAD commit hash: {get_current_commit_hash()}")

view raw JSON →