How to Download Latest Release of a Package from Gitlab
Gitlab currently lacks a convenient option to download the most recent package from a repository, in contrast to Github. Consequently, one may require a script to obtain the latest package.
Here is the simple script that download latest package.
| #!/usr/bin/python | |
| import requests | |
| import json | |
| # Replace <GITLAB_PROJECT_ID> with the ID of your GitLab project | |
| url = "https://gitlab.com/api/v4/projects/<GITLAB_PROJECT_ID>/releases" | |
| # Get the latest release | |
| response = requests.get(url) | |
| # Check if the request was successful | |
| if response.status_code == 200: | |
| # Load the JSON response | |
| data = json.loads(response.text) | |
| # Get the first (latest) release | |
| latest_release = data[0] | |
| # Get the assets for the latest release | |
| assets = latest_release["assets"]["links"] | |
| # Find the asset with the name starting with "<GITLAB_PROJECT_RELEASE_FILE>" | |
| target_asset = None | |
| for asset in assets: | |
| if asset["name"].startswith("<GITLAB_PROJECT_RELEASE_FILE"): | |
| target_asset = asset | |
| break | |
| # Check if the target asset was found | |
| if target_asset: | |
| # Get the download URL for the target asset | |
| download_url = target_asset["url"] | |
| # Download the file | |
| response = requests.get(download_url) | |
| # Check if the download was successful | |
| if response.status_code == 200: | |
| # Write the file to disk | |
| with open(target_asset["name"], "wb") as f: | |
| f.write(response.content) | |
| print(f"Downloaded {target_asset['name']}") | |
| else: | |
| print(f"Failed to download the file: {response.text}") | |
| else: | |
| print("Failed to find the target asset") | |
| else: | |
| print(f"Failed to get the latest release: {response.text}") |
To execute this script successfully,
it is necessary to customize <GITLAB_PROJECT_ID> and <GITLAB_PROJECT_RELEASE_FILE>.
The <GITLAB_PROJECT_ID> can be found by examining the page source and searching for:
<input type="hidden" name="project_id" id="project_id" value= />
To fill in the <GITLAB_PROJECT_ID> field in the script,
copy the number from the value field.
To identify <GITLAB_PROJECT_RELEASE_FILE>,
navigate to the release page of the repository and look for the pattern that each release follows.
For instance,
if each release contains a number,
copy the initial part of that file,
excluding the number.
In such a scenario,
if the file is named something like project-release-1.3.5,
<GITLAB_PROJECT_RELEASE_FILE> should be substituted with project-release-.
The script will download only the first file with that specific pattern that it discovers.