Skip to content
This repository has been archived by the owner on Dec 5, 2024. It is now read-only.

Commit

Permalink
[bugfix] Improve git version parsing (gopasspw#2690)
Browse files Browse the repository at this point in the history
* [bugfix] Improve git version parsing

See gopasspw#2686

Signed-off-by: Dominik Schulz <[email protected]>

* Fix lint issues

Signed-off-by: Dominik Schulz <[email protected]>

---------

Signed-off-by: Dominik Schulz <[email protected]>
  • Loading branch information
dominikschulz authored Nov 18, 2023
1 parent a5dce30 commit edb272a
Show file tree
Hide file tree
Showing 3 changed files with 149 additions and 81 deletions.
22 changes: 22 additions & 0 deletions internal/backend/storage/gitfs/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -190,6 +191,27 @@ func (g *Git) Version(ctx context.Context) semver.Version {
return sv
}

var reLeadingNumber = regexp.MustCompile(`^\s*(\d+)\D*`)

func parseVersion(sv string) (semver.Version, error) {
if sv, err := semver.ParseTolerant(sv); err == nil {
return sv, nil
}

parts := strings.SplitN(sv, ".", 3)
if len(parts) == 3 {
// try to extract the number-only prefix from the patch level
// e.g. "windwows.2" from "2.42.0.windows.2"
matches := reLeadingNumber.FindStringSubmatch(parts[2])
if len(matches) > 0 {
parts[2] = matches[1]
sv = strings.Join(parts, ".")
}
}

return semver.ParseTolerant(sv)
}

// IsInitialized returns true if this stores has an (probably) initialized .git folder.
func (g *Git) IsInitialized() bool {
return fsutil.IsFile(filepath.Join(g.fs.Path(), ".git", "config"))
Expand Down
41 changes: 41 additions & 0 deletions internal/backend/storage/gitfs/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"path/filepath"
"testing"

"github.com/blang/semver/v4"
"github.com/gopasspw/gopass/internal/out"
"github.com/gopasspw/gopass/pkg/ctxutil"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -80,3 +81,43 @@ func TestGit(t *testing.T) {
assert.Equal(t, "foobar", string(content))
})
}

func TestParseVersion(t *testing.T) {
for _, tc := range []struct {
name string
in string
sv semver.Version
wantErr bool
}{
{
name: "empty",
in: "",
wantErr: true,
},
{
name: "invalid",
in: "foo",
wantErr: true,
},
{
name: "valid",
in: "2.30.0",
sv: semver.MustParse("2.30.0"),
},
{
name: "invalid-recovered", // GH-2686
in: "2.42.0.windows.2",
sv: semver.MustParse("2.42.0"),
},
} {
t.Run(tc.name, func(t *testing.T) {
sv, err := parseVersion(tc.in)
assert.Equal(t, tc.sv, sv)
if tc.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}
}
Loading

0 comments on commit edb272a

Please sign in to comment.