Skip to content

Commit

Permalink
Merge pull request #1448 from twpayne/source-dir-not-root
Browse files Browse the repository at this point in the history
Detect when the source directory is already in a git working copy
  • Loading branch information
twpayne authored Sep 23, 2021
2 parents 96a043b + 9996849 commit c3e9c45
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
24 changes: 18 additions & 6 deletions internal/cmd/initcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"regexp"
"runtime"
Expand Down Expand Up @@ -133,9 +132,24 @@ func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error {
c.init.purgeBinary = true
}

// If the source repo does not exist then init or clone it.
switch _, err := c.baseSystem.Stat(c.SourceDirAbsPath.Join(".git")); {
case errors.Is(err, fs.ErrNotExist):
// Search upwards to find out if we're already in a git repository.
inWorkingCopy := false
workingCopyDirAbsPath := c.SourceDirAbsPath
FOR:
for {
if info, err := c.baseSystem.Stat(workingCopyDirAbsPath.Join(".git")); err == nil && info.IsDir() {
inWorkingCopy = true
break FOR
}
prevWorkingCopyDirAbsPath := workingCopyDirAbsPath
workingCopyDirAbsPath = workingCopyDirAbsPath.Dir()
if len(workingCopyDirAbsPath) >= len(prevWorkingCopyDirAbsPath) {
break FOR
}
}

// If the working copy does not exist then init it or clone it.
if !inWorkingCopy {
rawSourceDir, err := c.baseSystem.RawPath(c.SourceDirAbsPath)
if err != nil {
return err
Expand Down Expand Up @@ -208,8 +222,6 @@ func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error {
}
}
}
case err != nil:
return err
}

// Find config template, execute it, and create config file.
Expand Down
7 changes: 7 additions & 0 deletions internal/cmd/testdata/scripts/init.txt
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ chezmoi init --config-path=$HOME/.chezmoi.toml file://$WORK/home/user/.local/sha
cmp $HOME/.chezmoi.toml golden/chezmoi.toml
! exists $CHEZMOICONFIGDIR/chezmoi.toml

# test chezmoi init when the source dir is already in a git working copy
chhome home11/user
mkgitconfig
exec git init $HOME/.local/share
chezmoi init
! exists $CHEZMOISOURCEDIR/.git

-- golden/chezmoi.toml --
[data]
email = "[email protected]"
Expand Down

0 comments on commit c3e9c45

Please sign in to comment.