Incorporate the git commit hash into a Python file during installation

Is there a way to automatically embed the git hash into the version number of a python module when it is installed from a git repository using ./setup.py install? How can this be done?

I am considering defining a function in setup.py that will add the hash and ensuring it is executed after setup has copied the module to its build/lib/ directory, but before it is installed to its final destination. Is it possible to access the build process at that stage?

Edit: I understand how to obtain the current version's hash from the command line, but my question is on how to execute such a command at the appropriate time during the build/install process.

Answer №1

If you're looking for a different approach, you can consider using gitpython. An example of this can be seen in dd/setup.py:

from pkg_resources import parse_version  # included in `setuptools`


def git_version(version):
    """Retrieve version with local version identifier."""
    import git
    repo = git.Repo('.git')
    repo.git.status()
    # ensuring versions are ordered correctly
    latest_tag = repo.git.describe(
        match='v[0-9]*', tags=True, abbrev=0)
    assert parse_version(latest_tag) <= parse_version(version), (
        latest_tag, version)
    sha = repo.head.commit.hexsha
    if repo.is_dirty():
        return f'{version}.dev0+{sha}.dirty'
    # no changes made to the commit
    # is it a release of version?
    try:
        tag = repo.git.describe(
            match='v[0-9]*', exact_match=True,
            tags=True, dirty=True)
    except git.GitCommandError:
        return f'{version}.dev0+{sha}'
    assert tag == f'v{version}', (tag, version)
    return version

You may also want to check out the related conversation at https://github.com/tulip-control/tulip-control/pull/145

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to combine and merge multiple JSON files from a folder into one consolidated JSON file using Python?

Imagine you have 3 JSON files - data1.json, data2.json, and data3.json. Let's take a look at what each file contains: { "Players":[ { "name":"Alexis Sanchez", "club":"Manchester United" }, { "name" ...

Python script for extracting content from iframes without specified sources

Currently, I am attempting to extract the content within an iFrame with the ID "topic" from the following HTML file: https://i.stack.imgur.com/FustQ.png Even after trying methods like Selenium and Beautiful Soup, I am still unable to access the elements i ...

Setting up Python modules with IronPython

After creating a few functions in PyCharm using the Urllib.requests and Numpy packages, I encountered an issue. When attempting to use these functions in code written in IronPython for a GUI application, I received an exception stating that the modules did ...

The dtype attribute of a Pandas DataFrame

Whenever you call the dtypes method on a pandas data frame, the final line of the result typically displays dtype: object. For instance: In [1]: import pandas as pd In [2]: df = pd.DataFrame({'numbers':100,'floats': 5.75,'name&apos ...

The execution of the return statement in the catch block is unsuccessful

Here is a simple example that results in an error because the variable tl was not specified: function allmatches() { SpreadsheetApp.getActive().getSheetByName('data').getRange('A1').setValue(tl) } To track any errors that occur durin ...

divide requests using regular expressions

#When attempting to use regex to split this string, I am encountering incorrect outcomes. import re queries =""" INSERT ignore into persons VALUES (15,'Tom D.', 'Erilchsen', 'Skagen 21', 'Erlangen'); ...

Python: Array of Arrays

As a Python beginner, I am currently working on a project that involves a List of lists. My goal is to display specific lists by searching for one of their elements. In this particular case, the List contains user information such as name, username, age, ...

Using a Python dataframe to extract a specific set of values from one column based on criteria met in another column

diff = [10,15,20,25,20,15, 10, 10, 15, 21, 24, 19, 15, 10, 10, 15, 20, 21, 26, 20, 10,15, 20, 25, 20, 15, 10] df_data = pd.DataFrame(diff, columns=['data']) df_data.insert(0, 'slno', [ d for d in range(0, df_data.shape[0])]) max = { ...

Unlock autofill suggestions when modifying methods from parent Python class within VS code

In IntelliJ, there is a feature that provides autocomplete and assistance for adding an inherited function. Is it possible to achieve the same behavior in VS Code using the built-in Python interpreter? This feature allows us to override specific function ...

I am constantly encountering the issue where I receive the error message: Element cannot be found: {"method":"css selector","selector":".user-profile-link"}

For some reason, I am encountering an error message that says: Unable to locate element: {"method":"css selector","selector":".user-profile-link"} - Everything seems to be working fine except for this issue and despite my efforts to find a solution, I ha ...

Is there a way for me to retrieve randomly generated id values?

I've been grappling with extracting randomly generated ID values from the mentioned website. Despite trying to combine various find_element options, I haven't had any success in retrieving these ID values. Can someone suggest an appropriate optio ...

Tips for isolating the central object within an image using OpenCV

Struggling to isolate the center rectangle in the image using cv2.connectedComponentsWithStats. Unsure of how to achieve this. https://i.stack.imgur.com/ZXo3i.png This was my approach: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, bw = cv2.threshold( ...

Having difficulty in clicking the "load more" button using Selenium

I am in the process of developing a web scraper that will utilize both Selenium and BeautifulSoup. I am encountering difficulties with clicking the load more button using Selenium. While I have been able to detect the button, scroll to it, etc., I am stru ...

How to programmatically interact with a dropdown menu without a select element in Python using Selenium

Hey there, I'm currently practicing my skills with Selenium on a practice forum. If you're interested in checking it out, here's the link: click here When you visit the page and inspect the dropdown menu for state and city, you'll noti ...

Finding the average time from a given list of times

Hey there! I'm currently facing an issue with calculating the average time from a list of times for each test. Can you help? Here's the output: test1 ['0:02:30.000000', '0:02:28.000000', '0:02:31.000000', '0:02 ...

Unable to interact with multiple buttons in a loop using Python Selenium

How do I collect a list of button elements and click on each one, but encounter issues when trying to go back to the previous page using execute_script()? After clicking on the first button successfully, I am unable to click on any other buttons. btnContai ...

Tips for transforming gridded temperature data in CSV format (organized by latitude and longitude) into a raster map

Recently, I acquired a dataset that shows the average temperature change across the entire US, but it is formatted with lat/long range. The original csv file can be found here: original csv I am attempting to convert this data into a raster for visualizat ...

Python: Changing the format of a file to base64 representation

Here is the code I am having trouble with: import base64 with open('/Users/Bob/test.txt') as f: encoded = base64.b64encode(f.readlines()) print(encoded) This code was inspired by the information found in the base64 documentation. Howev ...

What is the process for defining the path while utilizing pdb within emacs?

Trying to utilize pdb in emacs, I encountered the need to adjust the path to PYTHONPATH=lib. However, upon entering the command Run pdb (like this): PYTHONPATH=lib pdb ./pychess. I received an error from Emacs stating that the file PYTHONPATH=lib could n ...

How to transform a list (row) into JSON format using Python

class ConvertToJSON: def convert(data:list): data_dict = {item[0]: item[1] for item in data} json_data = json.dumps(data_dict, indent=4) return json_data I am attempting to retrieve data from a database using the select method and converting i ...