27

If you do: git describe --long

you get: 0.3.1-15-g3b885c5

Thats the meaning of the above string:

Tag-CommitDistance-CommitId (http://git-scm.com/docs/git-describe)

How would you split the string to get the first (Tag) and last (CommitId) element?

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
Elisabeth
  • 20,496
  • 52
  • 200
  • 321

3 Answers3

44

By using String.split() with the count parameter to manage dashes in the commitid:

$x = "0.3.1-15-g3b885c5"
$tag = $x.split("-",3)[0]
$commitid = $x.split("-",3)[-1]
Ocaso Protal
  • 19,362
  • 8
  • 76
  • 83
  • 6
    FYI that can be done in a single expression: `$a,$b = "0.3.1-15-g3b885c5".split('-')[0,2]` – Richard Aug 19 '15 at 12:40
  • 4
    @Richard You are right, I just wanted to show the use `-1` to get the last index. – Ocaso Protal Aug 19 '15 at 12:42
  • 3
    Nothing wrong with using a `split()` here vs. regex. I like regex, but sometimes a less "sophisticated" solution is better for future readability & maintenance - the original author may understand regex well, but the next person to take on support for the script may not. For more involved text parsing & handling, I go for regex - but for a simple split like this, I stick with `split()` – alroc Aug 19 '15 at 13:05
  • 1
    We use dot notation for tag and no regex friends here so you get the solution ;-) – Elisabeth Aug 19 '15 at 14:08
15

Note: This answer focuses on improving on the split-into-tokens-by-- approach from Richard's helpful answer, though note that that approach isn't fully robust, because git tag names may themselves contain - characters, so you cannot blindly assume that the first - instance ends the tag name.
To account for that, use Richard's robust solution instead.


Just to offer a more PowerShell-idiomatic variant:

# Stores '0.3.1' in $tag, and 'g3b885c5' in $commitId
$tag, $commitId = ('0.3.1-15-g3b885c5' -split '-')[0, -1]
  • PowerShell's -split operator is used to split the input string into an array of tokens by separator -
    While the [string] type's .Split() method would be sufficient here, -split offers many advantages in general.

  • [0, -1] extracts the first (0) and last (-1) element from the array returned by -split and returns them as a 2-element array.

  • $tag, $commitId = is a destructuring multi-assignment that assigns the elements of the resulting 2-element array to a variable each.

mklement0
  • 382,024
  • 64
  • 607
  • 775
3

I can't recall if dashes are allowed in tags, so I'll assume they are, but will not appear in the last two fields.

Thus:

if ("0.3.1-15-g3b885c5" -match '(.*)-\d+-([^-]+)') {
  $tag = $Matches[1];
  $commitId = $Matches[2]
}
Ocaso Protal
  • 19,362
  • 8
  • 76
  • 83
Richard
  • 106,783
  • 21
  • 203
  • 265
  • Nicely done; indeed, tag names may contain hyphens (dashes); verify with `git check-ref-format --allow-onelevel '0.3.1-pre.1'; $LASTEXITCODE -eq 0` – mklement0 Jul 17 '18 at 17:09