简体   繁体   中英

How to clone latest tag in a Git repo

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

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.
...

It's an old question, but not answered to my satisfaction (ie 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.

# Clone repo
$ git clone <url>

# Go into repo folder
$ cd <reponame>

# Get new tags from the remote
$ git fetch --tags

# Get the latest tag name, assign it to a variable
$ latestTag=$(git describe --tags `git rev-list --tags --max-count=1`)

# Checkout the latest tag
$ git checkout $latestTag

Found this solution here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM