Better project generation logic

This commit is contained in:
Lea Anthony
2020-11-10 11:59:29 +11:00
parent c181e4a9a6
commit 6f33b6ede9
3 changed files with 43 additions and 4 deletions

View File

@@ -32,7 +32,7 @@ func AddSubcommand(app *clir.Cli, w io.Writer) error {
command.StringFlag("n", "Name of project", &projectName)
// Setup project directory
projectDirectory := "."
projectDirectory := ""
command.StringFlag("d", "Project directory", &projectDirectory)
// Quiet Init
@@ -110,6 +110,10 @@ func initProject(options *templates.Options) error {
// Output stats
elapsed := time.Since(start)
options.Logger.Println("")
options.Logger.Println("Project Name: " + options.ProjectName)
options.Logger.Println("Project Directory: " + options.TargetDir)
options.Logger.Println("Project Template: " + options.TemplateName)
options.Logger.Println("")
options.Logger.Println(fmt.Sprintf("Initialised project '%s' in %s.", options.ProjectName, elapsed.Round(time.Millisecond).String()))
options.Logger.Println("")

View File

@@ -180,3 +180,23 @@ func GetSubdirectories(rootDir string) (*slicer.StringSlicer, error) {
})
return &result, err
}
func DirIsEmpty(dir string) (bool, error) {
if !DirExists(dir) {
return false, fmt.Errorf("DirIsEmpty called with a non-existant directory: %s", dir)
}
// CREDIT: https://stackoverflow.com/a/30708914/8325411
f, err := os.Open(dir)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdirnames(1) // Or f.Readdir(1)
if err == io.EOF {
return true, nil
}
return false, err // Either not empty or error, suits both cases
}

View File

@@ -162,9 +162,24 @@ func Install(options *Options) error {
}
// Did the user want to install in current directory?
if options.TargetDir == "." {
// Yes - use cwd
options.TargetDir = cwd
if options.TargetDir == "" {
// If the current directory is empty, use it
isEmpty, err := fs.DirIsEmpty(cwd)
if err != nil {
return err
}
if isEmpty {
// Yes - use cwd
options.TargetDir = cwd
} else {
options.TargetDir = filepath.Join(cwd, options.ProjectName)
if fs.DirExists(options.TargetDir) {
return fmt.Errorf("cannot create project directory. Dir exists: %s", options.TargetDir)
}
}
} else {
// Get the absolute path of the given directory
targetDir, err := filepath.Abs(filepath.Join(cwd, options.TargetDir))