Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use os.UserHomeDir() for Go version 1.12+ #853

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,6 @@ import (
"fmt"
"os"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
Expand All @@ -238,7 +237,7 @@ func initConfig() {
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
home, err := os.UserHomeDir()
if err != nil {
fmt.Println(err)
os.Exit(1)
Expand Down
51 changes: 51 additions & 0 deletions cobra/cmd/init_go1.10_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// +build !go1.12

package cmd

import (
"fmt"
"os"
"path/filepath"
"testing"
)

func TestGoldenInitCmd(t *testing.T) {

wd, _ := os.Getwd()
project := &Project{
AbsolutePath: fmt.Sprintf("%s/testproject", wd),
PkgName: "github.com/spf13/testproject",
Legal: getLicense(),
Copyright: copyrightLine(),
Viper: true,
AppName: "testproject",
}

err := project.Create()
if err != nil {
t.Fatal(err)
}

defer func() {
if _, err := os.Stat(project.AbsolutePath); err == nil {
os.RemoveAll(project.AbsolutePath)
}
}()

expectedFiles := []string{"LICENSE", "main.go"}
for _, f := range expectedFiles {
generatedFile := fmt.Sprintf("%s/%s", project.AbsolutePath, f)
goldenFile := fmt.Sprintf("testdata/%s.golden", filepath.Base(f))
err := compareFiles(generatedFile, goldenFile)
if err != nil {
t.Fatal(err)
}
}

rootCmd := "cmd/root.go"
generatedFile := fmt.Sprintf("%s/%s", project.AbsolutePath, rootCmd)
goldenFile := fmt.Sprintf("testdata/%s1.10.golden", filepath.Base(rootCmd))
if err = compareFiles(generatedFile, goldenFile); err != nil {
t.Fatal(err)
}
}
11 changes: 10 additions & 1 deletion cobra/cmd/init_test.go → cobra/cmd/init_go1.12_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// +build go1.12

package cmd

import (
Expand Down Expand Up @@ -30,7 +32,7 @@ func TestGoldenInitCmd(t *testing.T) {
}
}()

expectedFiles := []string{"LICENSE", "main.go", "cmd/root.go"}
expectedFiles := []string{"LICENSE", "main.go"}
for _, f := range expectedFiles {
generatedFile := fmt.Sprintf("%s/%s", project.AbsolutePath, f)
goldenFile := fmt.Sprintf("testdata/%s.golden", filepath.Base(f))
Expand All @@ -39,4 +41,11 @@ func TestGoldenInitCmd(t *testing.T) {
t.Fatal(err)
}
}

rootCmd := "cmd/root.go"
generatedFile := fmt.Sprintf("%s/%s", project.AbsolutePath, rootCmd)
goldenFile := fmt.Sprintf("testdata/%s1.12.golden", filepath.Base(rootCmd))
if err = compareFiles(generatedFile, goldenFile); err != nil {
t.Fatal(err)
}
}
2 changes: 2 additions & 0 deletions cobra/cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// +build !go1.12

// Copyright © 2015 Steve Francia <[email protected]>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
82 changes: 82 additions & 0 deletions cobra/cmd/root_go1.12.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// +build go1.12

// Copyright © 2015 Steve Francia <[email protected]>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
"fmt"
"os"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var (
// Used for flags.
cfgFile string
userLicense string

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() {
rootCmd.Execute()
}

func init() {
cobra.OnInitialize(initConfig)

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
viper.SetDefault("license", "apache")

rootCmd.AddCommand(addCmd)
rootCmd.AddCommand(initCmd)
}

func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := os.UserHomeDir()
if err != nil {
er(err)
}

// Search config in home directory with name ".cobra" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".cobra")
}

viper.AutomaticEnv()

if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,8 @@ import (
"fmt"
"os"
"github.com/spf13/cobra"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/viper"

)


Expand Down
94 changes: 94 additions & 0 deletions cobra/cmd/testdata/root.go1.12.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
Copyright © 2019 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd

import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)


var cfgFile string


// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "testproject",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

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.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

func init() {
cobra.OnInitialize(initConfig)

// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.testproject.yaml)")


// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}


// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := os.UserHomeDir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}

// Search config in home directory with name ".testproject" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".testproject")
}

viper.AutomaticEnv() // read in environment variables that match

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}

Loading