Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone latest tag in a Git repo

Tags:

git

git ls-remote --tags git://github.com/git/git.git

lists the latest tags without cloning. I need a way to be able to clone from the latest tag directly

like image 598
Preetpal Singh Avatar asked Apr 21 '15 18:04

Preetpal Singh


People also ask

How do I get the latest tag from GitHub?

get-latest-tag-on-git.sh # The command finds the most recent tag that is reachable from a commit. # If the tag points to the commit, then only the tag is shown. # and the abbreviated object name of the most recent commit.


2 Answers

Call this ~/bin/git-clone-latest-tag:

#!/bin/bash

set -euo pipefail
basename=${0##*/}

if [[ $# -lt 1 ]]; then
    printf '%s: Clone the latest tag on remote.\n' "$basename" >&2
    printf 'Usage: %s [other args] <remote>\n' "$basename" >&2
    exit 1
fi

remote=${*: -1} # Get last argument

echo "Getting list of tags from: $remote"

tag=$(git ls-remote --tags --exit-code --refs "$remote" \
  | sed -E 's/^[[:xdigit:]]+[[:space:]]+refs\/tags\/(.+)/\1/g' | tail -n1)

echo "Selected tag: $tag"

# Clone as shallowly as possible. Remote is the last argument.
git clone --branch "$tag" --depth 1 --shallow-submodules --recurse-submodules "$@"

Then you can do:

% git clone-latest-tag https://github.com/python/cpython.git
Getting list of tags from: https://github.com/python/cpython.git
Selected tag: v3.8.0b1
Cloning into 'cpython'...
remote: Enumerating objects: 4346, done.
...
like image 80
Tom Hale Avatar answered Oct 12 '22 16:10

Tom Hale


It's an old question, but not answered to my satisfaction (i.e. a readable, mostly-default one-liner :-) ).

This one-liner will get you a clone of a repo of just the latest tag.

REPO=https://github.com/namespace/repo.git && \
git clone $REPO --single-branch --branch \
$(git ls-remote --tags --refs $REPO | tail -n1 | cut -d/ -f3)

Explanation

  1. First we set a REPO variable. We need it twice, this reduces the chance of errors.
  2. Then we use $(git ls-remote --tags --refs $REPO | tail -n1 | cut -d/ -f3) to get the latest tag as a variable.
  3. Finally we specify that as the 'branch' to clone

Tried this with a few repo's. No caveats come to mind (repo's without tags will fail of course), but do let me know if this can be improved.

Add anything you like, such as -c advice.detachedHead=false to not get such a long warning about the detached state.

like image 30
Thermostat Avatar answered Oct 12 '22 15:10

Thermostat