diff --git a/src/cmd/utils/author_file_utils.go b/src/cmd/utils/author_file_utils.go index 2d3986d..0fdd93b 100644 --- a/src/cmd/utils/author_file_utils.go +++ b/src/cmd/utils/author_file_utils.go @@ -3,6 +3,7 @@ package utils import ( "encoding/json" "fmt" + "io" "os" "strings" ) @@ -23,53 +24,55 @@ func Find_authorfile() string { } } -func CheckAuthorFile() string { - var cocommit_folder string - authorfile := Find_authorfile() - if _, err := os.Stat(authorfile); os.IsNotExist(err) { - println("Author file not found at: ", authorfile) - println("Would you like to create one? (y/n)") - var response string - _, err := fmt.Scanln(&response) - if err != nil { - println("Error reading response") - } - if response == "y" { - parts := strings.Split(authorfile, "/") - cocommit_folder = strings.Join(parts[:len(parts)-1], "/") - - // create the author file - if _, dirErr := os.Stat(cocommit_folder); os.IsNotExist(dirErr) { - err := os.Mkdir(cocommit_folder, 0766) - if err != nil { - fmt.Println("Error creating directory: ", err, cocommit_folder) - os.Exit(1) - } - } - file, err := os.Create(authorfile) - if err != nil { - fmt.Println("Error creating file: ", err) - os.Exit(1) +func CheckAuthorFile(input io.Reader, output io.Writer) (string,error) { + var cocommit_folder string + authorfile := Find_authorfile() + + if _, err := os.Stat(authorfile); os.IsNotExist(err) { + fmt.Fprintf(output, "Author file not found at: %s\n", authorfile) + fmt.Fprintf(output, "Would you like to create one? (y/n)\n") + + var response string + _, err := fmt.Fscanln(input, &response) + if err != nil { + fmt.Fprintln(output, "Error reading response") + } + + if response == "y" { + parts := strings.Split(authorfile, "/") + if len(parts) > 1 { + // remove the last part of the path + cocommit_folder = strings.Join(parts[:len(parts)-1], "/") + } else { + cocommit_folder = "." } - defer file.Close() + // create the author file + if _, dirErr := os.Stat(cocommit_folder); os.IsNotExist(dirErr) { + err := os.Mkdir(cocommit_folder, 0766) + if err != nil { + return "", fmt.Errorf("error creating directory: %v %s", err, cocommit_folder) + } + } + + file, err := os.Create(authorfile) + if err != nil { + return "", fmt.Errorf("error creating file: %v", err) + } + defer file.Close() - // write the header to the file - json_string := - `{ - "Authors": { - } + // write the header to the file + json_string := `{ + "Authors": { + } }` - - file.Write([]byte(json_string)) - - fmt.Println("Author file created. To add authors please launch the TUI with -a and press 'C'") - } else { - os.Exit(1) - } - } - // This string output is mostly for convenience can mostly be ignored - return authorfile + file.Write([]byte(json_string)) + fmt.Fprintln(output, "Author file created. To add authors please launch the TUI with -a and press 'C'") + } else { + os.Exit(0) + } + } + return authorfile, nil } func CreateAuthor(user User) {