From 4cdb38c072b86bf795d2c81de50784d9fdd6eb77 Mon Sep 17 00:00:00 2001 From: Albert Nigmatzianov Date: Mon, 15 May 2017 09:49:18 +0200 Subject: [PATCH] cmd: Use correct HasPrefix function for paths Updates #448 --- cobra/cmd/project.go | 17 +++++++++++++++-- cobra/cmd/project_test.go | 3 +-- cobra/cmd/root.go | 15 +++++++++------ 3 files changed, 25 insertions(+), 10 deletions(-) diff --git a/cobra/cmd/project.go b/cobra/cmd/project.go index 80643898..de1168a1 100644 --- a/cobra/cmd/project.go +++ b/cobra/cmd/project.go @@ -3,6 +3,7 @@ package cmd import ( "os" "path/filepath" + "runtime" "strings" ) @@ -37,7 +38,7 @@ func NewProject(projectName string) *Project { } for _, srcPath := range srcPaths { goPath := filepath.Dir(srcPath) - if strings.HasPrefix(wd, goPath) { + if filepathHasPrefix(wd, goPath) { p.absPath = filepath.Join(srcPath, projectName) break } @@ -172,7 +173,7 @@ func (p *Project) SrcPath() string { } for _, srcPath := range srcPaths { - if strings.HasPrefix(p.absPath, srcPath) { + if filepathHasPrefix(p.absPath, srcPath) { p.srcPath = srcPath break } @@ -180,3 +181,15 @@ func (p *Project) SrcPath() string { return p.srcPath } + +func filepathHasPrefix(path string, prefix string) bool { + if len(path) <= len(prefix) { + return false + } + if runtime.GOOS == "windows" { + // Paths in windows are case-insensitive. + return strings.EqualFold(path[0:len(prefix)], prefix) + } + return path[0:len(prefix)] == prefix + +} diff --git a/cobra/cmd/project_test.go b/cobra/cmd/project_test.go index 0900b8cc..037f7c55 100644 --- a/cobra/cmd/project_test.go +++ b/cobra/cmd/project_test.go @@ -1,7 +1,6 @@ package cmd import ( - "strings" "testing" ) @@ -17,7 +16,7 @@ func TestFindExistingPackage(t *testing.T) { func hasGoPathPrefix(path string) bool { for _, srcPath := range srcPaths { - if strings.HasPrefix(path, srcPath) { + if filepathHasPrefix(path, srcPath) { return true } } diff --git a/cobra/cmd/root.go b/cobra/cmd/root.go index 545cd1ff..cfc78522 100644 --- a/cobra/cmd/root.go +++ b/cobra/cmd/root.go @@ -21,15 +21,18 @@ import ( "github.com/spf13/viper" ) -var cfgFile, projectBase, userLicense string // are used for flags +var ( + // Used for flags. + cfgFile, projectBase, userLicense string -var rootCmd = &cobra.Command{ - Use: "cobra", - Short: "A generator for Cobra based Applications", - Long: `Cobra is a CLI library for Go that empowers applications. + rootCmd = &cobra.Command{ + Use: "cobra", + Short: "A generator for Cobra based Applications", + Long: `Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, -} + } +) // Execute executes the root command. func Execute() {