|
| 1 | +""" |
| 2 | +vcs_utils.py |
| 3 | +
|
| 4 | +This module provides utility functions to retrieve the version control system |
| 5 | +(VCS) identifier using Git and to write it to a file. |
| 6 | +
|
| 7 | +The functions handle cases where Git is not installed or the current directory |
| 8 | +is not a Git repository, and handle file write failures gracefully. |
| 9 | +""" |
| 10 | + |
| 11 | +import subprocess |
| 12 | +import sys |
| 13 | + |
| 14 | +def get_vcs_id(): |
| 15 | + """ |
| 16 | + Attempts to retrieve the VCS identifier using the 'git describe' command. |
| 17 | + |
| 18 | + Returns: |
| 19 | + str: A string containing the VCS identifier if successful, or an empty |
| 20 | + string if Git is not available or the directory is not a Git repository. |
| 21 | + |
| 22 | + This function handles the following exceptions: |
| 23 | + - subprocess.CalledProcessError: Raised if the 'git' command fails, e.g., |
| 24 | + if the current directory is not a Git repository. |
| 25 | + - FileNotFoundError: Raised if 'git' is not installed or not found in the |
| 26 | + system's PATH. |
| 27 | + |
| 28 | + All warnings are printed to stderr. |
| 29 | + """ |
| 30 | + try: |
| 31 | + vcs_output = subprocess.run( |
| 32 | + ["git", "describe", "--always", "--dirty", "--all", "--long"], |
| 33 | + stdout=subprocess.PIPE, text=True, check=True |
| 34 | + ) |
| 35 | + vcs_string = vcs_output.stdout.strip() |
| 36 | + return vcs_string |
| 37 | + except (subprocess.CalledProcessError, FileNotFoundError) as e: |
| 38 | + # Print the warning to stderr |
| 39 | + print("Warning: Unable to retrieve VCS description. Error:", str(e), file=sys.stderr) |
| 40 | + return "" |
| 41 | + |
| 42 | + |
| 43 | +def write_vcs_id_to_file(vcs_id, file_path): |
| 44 | + """ |
| 45 | + Defines a macro with the given VCS identifier as a string literal to a file. |
| 46 | + |
| 47 | + Args: |
| 48 | + vcs_id (str): The VCS identifier string to write to the file. |
| 49 | + file_path (str): The path to the file to write to. |
| 50 | + |
| 51 | + If the file exists, it will be overwritten. If writing to the file fails, |
| 52 | + a warning will be printed to stderr, but the script will not terminate |
| 53 | + with an error. |
| 54 | + """ |
| 55 | + try: |
| 56 | + # Prepare the C-style string definition |
| 57 | + c_content = f'#define VCS_ID "{vcs_id}"\n' |
| 58 | + |
| 59 | + # Write the content to the file (overwriting if it exists) |
| 60 | + with open(file_path, 'w') as file: |
| 61 | + file.write(c_content) |
| 62 | + |
| 63 | + except IOError as e: |
| 64 | + # If writing to the file fails, print the warning to stderr |
| 65 | + print(f"Warning: Unable to write VCS ID to file '{file_path}'. Error: {str(e)}", file=sys.stderr) |
0 commit comments