Skip to content

Commit

Permalink
Add overlay locking (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
retr0h committed Nov 23, 2023
1 parent 665bbd9 commit 8827f6d
Show file tree
Hide file tree
Showing 8 changed files with 153 additions and 63 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ This project is a port of [Gilt][], it is not 100% compatible with the python
version, and aims to correct poor decisions made in the python version of
Gilt.

This version of Gilt does not provide built in locking, branches, tags, and
post commands unlike our python friend. However, these features will be added
in the future.
This version of Gilt does not provide built in branches, tags, and post
commands unlike our python friend. However, those features will be added
soon enough.

## Installation

Expand Down
34 changes: 33 additions & 1 deletion cmd/overlay.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,42 @@
package cmd

import (
"errors"
"fmt"
"log/slog"
"path/filepath"
"strconv"

"github.com/danjacques/gofslock/fslock"
"github.com/spf13/cobra"

giltpath "github.com/retr0h/go-gilt/internal/path"
)

// withLock is a convenience function to create a lock, execute a function while
// holding that lock, and then release the lock on completion.
func withLock(fn func() error) error {
expandedLockDir, err := giltpath.ExpandUser(appConfig.GiltDir)
if err != nil {
return err
}
lockFile := filepath.Join(expandedLockDir, "gilt.lock")

logger.Info(
"acquiring lock",
slog.String("lockfile", lockFile),
)

err = fslock.With(lockFile, fn)
if err != nil {
if errors.Is(err, fslock.ErrLockHeld) {
return fmt.Errorf("could not acquire lock on %s: %s", lockFile, err)
}
}

return err
}

func logRepositoriesGroup() []any {
logGroups := make([]any, 0, len(appConfig.Repositories))

Expand Down Expand Up @@ -72,7 +102,9 @@ var overlayCmd = &cobra.Command{
slog.Group("Repository", logRepositoriesGroup()...),
)

if err := repos.Overlay(); err != nil {
if err := withLock(func() error {
return repos.Overlay()
}); err != nil {
logger.Error(
"error overlaying repositories",
slog.String("err", err.Error()),
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/retr0h/go-gilt
go 1.21.0

require (
github.com/danjacques/gofslock v0.0.0-20230728142113-ae8f59f9e88b
github.com/golang/mock v1.4.4
github.com/lmittmann/tint v1.0.3
github.com/spf13/afero v1.10.0
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/danjacques/gofslock v0.0.0-20230728142113-ae8f59f9e88b h1:BBkZ6LZYtzMQ2Oo5LkovMmUp0gxAD+AnXzfknZlFTBo=
github.com/danjacques/gofslock v0.0.0-20230728142113-ae8f59f9e88b/go.mod h1:9LABMmUSkKzt6FVQNEWdUTM0bz8Bt8MPyEcuZe0Sr8c=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
Expand Down Expand Up @@ -419,6 +421,7 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
Expand Down
45 changes: 45 additions & 0 deletions internal/path/path.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright (c) 2023 John Dewey

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

package path

import (
"os/user"
"path/filepath"
)

var currentUser = user.Current

// ExpandUser on Unix and Windows, return the argument with an initial
// component of ~ or ~user replaced by that user’s home directory.
func ExpandUser(
path string,
) (string, error) {
if len(path) == 0 || path[0] != '~' {
return path, nil
}

usr, err := currentUser()
if err != nil {
return "", err
}

return filepath.Join(usr.HomeDir, path[1:]), nil
}
66 changes: 66 additions & 0 deletions internal/path/path_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright (c) 2023 John Dewey

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// TODO(retr0h): move to public testing pattern
package path

import (
"fmt"
"os/user"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)

type PathTestSuite struct {
suite.Suite
}

func (suite *PathTestSuite) TestexpandUserOk() {
originalCurrentUser := currentUser
currentUser = func() (*user.User, error) {
return &user.User{
HomeDir: "/testUser",
}, nil
}
defer func() { currentUser = originalCurrentUser }()

got, err := ExpandUser("~/foo/bar")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), got, "/testUser/foo/bar")
}

func (suite *PathTestSuite) TestexpandUserReturnsError() {
originalCurrentUser := currentUser
currentUser = func() (*user.User, error) {
return nil, fmt.Errorf("failed to get current user")
}
defer func() { currentUser = originalCurrentUser }()

_, err := ExpandUser("~/foo/bar")
assert.Error(suite.T(), err)
}

// In order for `go test` to run this suite, we need to create
// a normal test function and pass our suite to suite.Run.
func TestPathTestSuite(t *testing.T) {
suite.Run(t, new(PathTestSuite))
}
21 changes: 2 additions & 19 deletions internal/repositories/repositories.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,16 @@ import (
"fmt"
"log/slog"
"os"
"os/user"
"path/filepath"
"strings"

"github.com/spf13/afero"

"github.com/retr0h/go-gilt/internal"
"github.com/retr0h/go-gilt/internal/config"
giltpath "github.com/retr0h/go-gilt/internal/path"
)

var currentUser = user.Current

// New factory to create a new Repository instance.
func New(
appFs afero.Fs,
Expand All @@ -51,21 +49,6 @@ func New(
}
}

func expandUser(
path string,
) (string, error) {
if len(path) == 0 || path[0] != '~' {
return path, nil
}

usr, err := currentUser()
if err != nil {
return "", err
}

return filepath.Join(usr.HomeDir, path[1:]), nil
}

// getCloneDir returns the path to the Repository's clone directory.
func (r *Repositories) getCloneDir(
giltDir string,
Expand All @@ -88,7 +71,7 @@ func (r *Repositories) getCloneHash(

// getGiltDir create the GiltDir if it doesn't exist.
func (r *Repositories) getGiltDir() (string, error) {
expandedGiltDir, err := expandUser(r.config.GiltDir)
expandedGiltDir, err := giltpath.ExpandUser(r.config.GiltDir)
if err != nil {
return "", err
}
Expand Down
40 changes: 0 additions & 40 deletions internal/repositories/repositories_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,8 @@
package repositories

import (
"fmt"
"log/slog"
"os"
"os/user"
"testing"

"github.com/golang/mock/gomock"
Expand Down Expand Up @@ -76,31 +74,6 @@ func (suite *RepositoriesTestSuite) SetupTest() {
suite.logger = slog.New(slog.NewTextHandler(os.Stdout, nil))
}

func (suite *RepositoriesTestSuite) TestexpandUserOk() {
originalCurrentUser := currentUser
currentUser = func() (*user.User, error) {
return &user.User{
HomeDir: "/testUser",
}, nil
}
defer func() { currentUser = originalCurrentUser }()

got, err := expandUser("~/foo/bar")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), got, "/testUser/foo/bar")
}

func (suite *RepositoriesTestSuite) TestexpandUserReturnsError() {
originalCurrentUser := currentUser
currentUser = func() (*user.User, error) {
return nil, fmt.Errorf("failed to get current user")
}
defer func() { currentUser = originalCurrentUser }()

_, err := expandUser("~/foo/bar")
assert.Error(suite.T(), err)
}

func (suite *RepositoriesTestSuite) TestgetCloneDirOk() {
repos := suite.NewTestRepositories(suite.giltDir)

Expand Down Expand Up @@ -138,19 +111,6 @@ func (suite *RepositoriesTestSuite) TestgetGiltDir() {
assert.True(suite.T(), exists)
}

func (suite *RepositoriesTestSuite) TestgetGiltDirReturnsErrorWhenexpandUserErrors() {
repos := suite.NewTestRepositories("~/foo/bar")

originalCurrentUser := currentUser
currentUser = func() (*user.User, error) {
return nil, fmt.Errorf("failed to get current user")
}
defer func() { currentUser = originalCurrentUser }()

_, err := repos.getGiltDir()
assert.Error(suite.T(), err)
}

// In order for `go test` to run this suite, we need to create
// a normal test function and pass our suite to suite.Run.
func TestRepositoriesTestSuite(t *testing.T) {
Expand Down

0 comments on commit 8827f6d

Please sign in to comment.