Skip to content

Commit

Permalink
Merge pull request #26 from stuartleeks/sl/workspace-folder-default
Browse files Browse the repository at this point in the history
Add git repo handling to default workspace path
Fixes incorrect path error when devcontainer folder isn't in the repo root
  • Loading branch information
stuartleeks authored Aug 23, 2020
2 parents 81c8aa5 + 1770f59 commit 0a9bc6d
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
31 changes: 29 additions & 2 deletions internal/pkg/devcontainers/remoteuri.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"regexp"
"strings"

"github.com/stuartleeks/devcontainer-cli/internal/pkg/git"
"github.com/stuartleeks/devcontainer-cli/internal/pkg/wsl"
)

Expand Down Expand Up @@ -72,8 +73,11 @@ func GetWorkspaceMountPath(folderPath string) (string, error) {
}

// No `workspaceFolder` found in devcontainer.json - use default
_, folderName := filepath.Split(folderPath)
return fmt.Sprintf("/workspaces/%s", folderName), nil
devcontainerPath, err := getDefaultWorkspaceFolderForPath(folderPath)
if err != nil {
return "", fmt.Errorf("Error getting default workspace path: %s", err)
}
return fmt.Sprintf("/workspaces/%s", devcontainerPath), nil
}

// TODO: add tests (and implementation) to handle JSON parsing with comments
Expand All @@ -92,3 +96,26 @@ func getWorkspaceMountPathFromDevcontainerDefinition(definition []byte) (string,
}
return "", nil
}

func getDefaultWorkspaceFolderForPath(path string) (string, error) {

// get the git repo-root
rootPath, err := git.GetTopLevelPath(path)
if err != nil {
return "", err
}
if rootPath == "" {
// not a git repo, default to path
rootPath = path
}

// get parent to root
rootParent, _ := filepath.Split(rootPath)

// return path relative to rootParent
relativePath, err := filepath.Rel(rootParent, path)
if err != nil {
return "", err
}
return relativePath, nil
}
29 changes: 29 additions & 0 deletions internal/pkg/git/git.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package git

import (
"fmt"
"os/exec"
"strings"
"syscall"
)

// GetTopLevelPath returns the top-level folder for the git-repo that contains path, or empty string if not a repo
func GetTopLevelPath(path string) (string, error) {
cmd := exec.Command("git", "rev-parse", "--show-toplevel")

buf, err := cmd.Output()
if err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
// The program has exited with an exit code != 0
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
if status.ExitStatus() == 128 {
// exit code 128 indictates not a git repo
return "", nil
}
}
return "", fmt.Errorf("Error git rev-parse --show-toplevel: %s", err)
}
return "", fmt.Errorf("Error git rev-parse --show-toplevel: %s", err)
}
return strings.TrimSpace(string(buf)), nil
}

0 comments on commit 0a9bc6d

Please sign in to comment.