Skip to content

Commit

Permalink
Print fatal messages to standard error. (#127)
Browse files Browse the repository at this point in the history
Co-authored-by: Curtis Schlak <156-curtis@users.noreply.gitlab.galvanize.com>
  • Loading branch information
realistschuckle and Curtis Schlak committed Mar 6, 2024
1 parent ef65ac2 commit bb77eca
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 42 deletions.
8 changes: 4 additions & 4 deletions app/cmd/guide.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,19 +69,19 @@ var guideCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
currentDir, err := os.Getwd()
if err != nil {
fmt.Println("Could not detect a working directory")
fmt.Fprintln(os.Stderr, "Could not detect a working directory")
os.Exit(1)
}

// Does that directory have a config file
hasConfig, _ := doesCurrentDirHaveConfig(currentDir)
if hasConfig {
fmt.Println("WARNING: configuration file detected and cannot continue with `learn walkthrough` command.")
fmt.Fprintln(os.Stderr, "WARNING: configuration file detected and cannot continue with `learn walkthrough` command.")
os.Exit(1)
}
_, dirExists := os.Stat("/" + guideDir)
if dirExists == nil {
fmt.Printf("A directory already exists by the name '%s', rename or move it.\n", guideDir)
fmt.Fprintf(os.Stderr, "A directory already exists by the name '%s', rename or move it.\n", guideDir)
os.Exit(1)
}

Expand All @@ -90,7 +90,7 @@ var guideCmd = &cobra.Command{
// Create contents in the directory
err = generateGuide(currentDir)
if err != nil {
fmt.Println(err)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}

Expand Down
8 changes: 4 additions & 4 deletions app/cmd/markdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ var markdownCmd = &cobra.Command{
if len(args) == 1 {
t, err := getTemp(args[0])
if err != nil {
fmt.Println(err)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if PrintTemplate {
Expand All @@ -41,19 +41,19 @@ var markdownCmd = &cobra.Command{
} else if len(args) == 2 {
t, err := getTemp(args[0])
if err != nil {
fmt.Println(err)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if PrintTemplate {
fmt.Println("-o flag skipped when appending...")
}
if err = t.appendContent(args[1]); err != nil {
fmt.Println(err)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}

} else {
fmt.Println(incorrectNumArgs)
fmt.Fprintln(os.Stderr, incorrectNumArgs)
os.Exit(1)
}

Expand Down
12 changes: 6 additions & 6 deletions app/cmd/preview.go
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,7 @@ func copyDockerPaths(target string, dockerPaths []string) (err error) {
// the directory was found after checking parents, copy contents
ignorePatterns, err := DockerIgnorePatterns(newDirPath)
if err != nil {
fmt.Print(err.Error())
fmt.Fprint(os.Stderr, err.Error())
}

err = CopyDirectoryContents(newDirPath, tmpSingleFileDir+"/"+dirPath, ignorePatterns)
Expand All @@ -596,7 +596,7 @@ func copyDockerPaths(target string, dockerPaths []string) (err error) {
} else {
ignorePatterns, err := DockerIgnorePatterns(dirPath)
if err != nil {
fmt.Print(err.Error())
fmt.Fprint(os.Stderr, err.Error())
}

err = CopyDirectoryContents(dirPath, tmpSingleFileDir+"/"+dirPath, ignorePatterns)
Expand Down Expand Up @@ -675,7 +675,7 @@ func createLinkDirectories(pathArray []string) (linkDirs string, err error) {
// previewCmdError is a small wrapper for all errors within the preview command. It ensures
// artifacts are cleaned up with a call to removeArtifacts
func previewCmdError(msg, tmpZipFile string) {
fmt.Println(msg)
fmt.Fprintln(os.Stderr, msg)
removeArtifacts(tmpZipFile)
learn.API.NotifySlack(errors.New(msg))
os.Exit(1)
Expand Down Expand Up @@ -778,14 +778,14 @@ func createChecksumFromZip(file *os.File) (string, error) {
func removeArtifacts(tmpZipFile string) {
err := os.Remove(tmpZipFile)
if err != nil {
fmt.Println("Sorry, we had trouble cleaning up the zip file created for curriculum preview")
fmt.Fprintln(os.Stderr, "Sorry, we had trouble cleaning up the zip file created for curriculum preview")
}

// Remove tmpSingleFileDir if it exists at this point
if _, err := os.Stat(tmpSingleFileDir); !os.IsNotExist(err) {
err = os.RemoveAll(tmpSingleFileDir)
if err != nil {
fmt.Println("Sorry, we had trouble cleaning up the tmp single file preview directory")
fmt.Fprintln(os.Stderr, "Sorry, we had trouble cleaning up the tmp single file preview directory")
}
}
}
Expand Down Expand Up @@ -865,7 +865,7 @@ func CopyDirectoryContents(src, dst string, ignorePatterns []string) error {
localizedPattern := src + "/" + pattern
matched, err := di.IgnoreMatches(localizedPattern, source)
if err != nil {
fmt.Printf("error while parsing at: %s", err)
fmt.Fprintf(os.Stderr, "error while parsing at: %s", err)
}
if matched {
ignore = matched
Expand Down
38 changes: 19 additions & 19 deletions app/cmd/publish.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ new block. If the block already exists, it will update the existing block.
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
if viper.Get("api_token") == "" || viper.Get("api_token") == nil {
fmt.Println(setAPITokenMessage)
fmt.Fprintln(os.Stderr, setAPITokenMessage)
os.Exit(1)
}

setupLearnAPI(false)

if len(args) != 0 {
fmt.Println("Usage: `learn publish` takes no arguments, merely pushing latest master and releasing a version to Learn. Use the command from inside a block repository.")
fmt.Fprintln(os.Stderr, "Usage: `learn publish` takes no arguments, merely pushing latest master and releasing a version to Learn. Use the command from inside a block repository.")
os.Exit(1)
}

Expand All @@ -50,30 +50,30 @@ new block. If the block already exists, it will update the existing block.

repoPieces, err := remotePieces()
if err != nil {
fmt.Printf("Cannot run git remote detection with command: %s\n%s\n", pushRemoteCommand, err)
fmt.Fprintf(os.Stderr, "Cannot run git remote detection with command: %s\n%s\n", pushRemoteCommand, err)
os.Exit(1)
}
if repoPieces.RepoName == "" {
fmt.Println("no fetch remote detected")
fmt.Fprintln(os.Stderr, "no fetch remote detected")
os.Exit(1)
}

block, err := learn.API.GetBlockByRepoName(repoPieces)
if err != nil {
fmt.Printf("Error fetching block from learn: %s\n", err)
fmt.Fprintf(os.Stderr, "Error fetching block from learn: %s\n", err)
os.Exit(1)
}
if !block.Exists() {
block, err = learn.API.CreateBlockByRepoName(repoPieces)
if err != nil {
fmt.Printf("Error creating block from learn: %s\n", err)
fmt.Fprintf(os.Stderr, "Error creating block from learn: %s\n", err)
os.Exit(1)
}
}

branch, err := currentBranch()
if err != nil {
fmt.Println("Cannot run git branch detection with bash:", err)
fmt.Fprintln(os.Stderr, "Cannot run git branch detection with bash:", err)
os.Exit(1)
}

Expand All @@ -90,21 +90,21 @@ new block. If the block already exists, it will update the existing block.
path, _ := os.Getwd()
createdConfig, err := publishFindOrCreateConfig(path + "/")
if err != nil {
fmt.Printf("%s", fmt.Sprintf("failed to find or create a config file for repo: (%s). Err: %v", branch, err))
fmt.Fprintf(os.Stderr, "%s", fmt.Sprintf("failed to find or create a config file for repo: (%s). Err: %v", branch, err))
os.Exit(1)
}
fmt.Printf("Publishing block with repo name %s from branch %s\n", repoPieces.RepoName, branch)

if createdConfig && CiCdEnvironment {
fmt.Println("\nError: You cannot use autoconfig.yaml from a CI/CD environment.")
fmt.Println("Please create a config.yaml file and commit it.")
fmt.Fprintln(os.Stderr, "\nError: You cannot use autoconfig.yaml from a CI/CD environment.")
fmt.Fprintln(os.Stderr, "Please create a config.yaml file and commit it.")
os.Exit(1)
} else if createdConfig {
fmt.Println("Committing autoconfig.yaml to", branch)
err = addAutoConfigAndCommit()

if err != nil && !strings.Contains(err.Error(), fmt.Sprintf("Your branch is up to date with 'origin/%s'.", branch)) {
fmt.Printf("Error committing the autoconfig.yaml to origin remote on branch, run 'git rm autoconfig.yaml' to remove it from reference then add a new commit: %s", err)
fmt.Fprintf(os.Stderr, "Error committing the autoconfig.yaml to origin remote on branch, run 'git rm autoconfig.yaml' to remove it from reference then add a new commit: %s", err)
os.Exit(1)
}
}
Expand All @@ -115,7 +115,7 @@ new block. If the block already exists, it will update the existing block.

err = pushToRemote(branch)
if err != nil {
fmt.Printf("\nError pushing to origin remote on branch:\n\n%s", err)
fmt.Fprintf(os.Stderr, "\nError pushing to origin remote on branch:\n\n%s", err)
os.Exit(1)
}
}
Expand All @@ -132,7 +132,7 @@ new block. If the block already exists, it will update the existing block.
// Create a release on learn, notify user
releaseID, err := learn.API.CreateBranchRelease(block.ID, branch)
if err != nil || releaseID == 0 {
fmt.Printf("Release failed. releaseID: %d. Error: %s\n", releaseID, err)
fmt.Fprintf(os.Stderr, "Release failed. releaseID: %d. Error: %s\n", releaseID, err)
os.Exit(1)
}

Expand All @@ -142,27 +142,27 @@ new block. If the block already exists, it will update the existing block.
s.Stop()

if p != nil && p.Errors != "" {
fmt.Printf("Release failed: %s\n", p.Errors)
fmt.Fprintf(os.Stderr, "Release failed: %s\n", p.Errors)
os.Exit(1)
}

if p != nil && len(p.SyncWarnings) > 0 {
fmt.Printf("Release warnings:")
fmt.Fprintf(os.Stderr, "Release warnings:")

for _, sw := range p.SyncWarnings {
fmt.Println(sw)
fmt.Fprintln(os.Stderr, sw)
}
}

block, err := learn.API.GetBlockByRepoName(repoPieces)
if err != nil {
fmt.Printf("Release failed. Error fetching block from learn: %s\n", err)
fmt.Fprintf(os.Stderr, "Release failed. Error fetching block from learn: %s\n", err)
os.Exit(1)
}
if len(block.SyncErrors) > 0 {
fmt.Println("Release failed. Errors on block:")
fmt.Fprintln(os.Stderr, "Release failed. Errors on block:")
for _, e := range block.SyncErrors {
fmt.Println(e)
fmt.Fprintln(os.Stderr, e)
}
}
os.Exit(1)
Expand Down
10 changes: 5 additions & 5 deletions app/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ var CiCdEnvironment bool
func init() {
u, err := user.Current()
if err != nil {
fmt.Println("Error retrieving your user path information")
fmt.Fprintln(os.Stderr, "Error retrieving your user path information")
os.Exit(1)
return
}
Expand All @@ -90,13 +90,13 @@ func init() {
// Write a ~/.glearn-config.yaml file with all the needed credential keys to fill in.
err = ioutil.WriteFile(configPath, initialConfig, 0600)
if err != nil {
fmt.Println("Error writing your glearn config file")
fmt.Fprintln(os.Stderr, "Error writing your glearn config file")
os.Exit(1)
return
}
} else {
// Config file was found but another error was produced
fmt.Printf("Error: %s", err)
fmt.Fprintf(os.Stderr, "Error: %s", err)
os.Exit(1)
return
}
Expand Down Expand Up @@ -128,7 +128,7 @@ func init() {
// Execute runs the learn CLI according to the user's command/subcommand/flags
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
Expand All @@ -143,7 +143,7 @@ func setupLearnAPI(getPresignedPostUrl bool) {

api, err := learn.NewAPI(baseURL, &client, getPresignedPostUrl)
if err != nil {
fmt.Printf("Error creating API client. Err: %v", err)
fmt.Fprintf(os.Stderr, "Error creating API client. Err: %v", err)
os.Exit(1)
return
}
Expand Down
6 changes: 3 additions & 3 deletions app/cmd/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ credentials inside ~/.glearn-config.yaml
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 0 {
fmt.Println("The set command does not take any arguments. Instead set variables with set --api_token=value")
fmt.Fprintln(os.Stderr, "The set command does not take any arguments. Instead set variables with set --api_token=value")
os.Exit(1)
}

// If the --api_token=some_value flag was given, set it in viper
if APIToken == "" {
fmt.Println("The set command needs '--api_token' flag.\n\nUse: learn set --api_token=value")
fmt.Fprintln(os.Stderr, "The set command needs '--api_token' flag.\n\nUse: learn set --api_token=value")
os.Exit(1)
} else {
viper.Set("api_token", APIToken)
Expand All @@ -33,7 +33,7 @@ credentials inside ~/.glearn-config.yaml
// Write any changes made above to the config
err := viper.WriteConfig()
if err != nil {
fmt.Printf("There was an error writing credentials to your config: %v", err)
fmt.Fprintf(os.Stderr, "There was an error writing credentials to your config: %v", err)
os.Exit(1)
return
}
Expand Down
2 changes: 1 addition & 1 deletion app/cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ var versionCmd = &cobra.Command{
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 0 {
fmt.Println("The version command does not take any arguments")
fmt.Fprintln(os.Stderr, "The version command does not take any arguments")
os.Exit(1)
}

Expand Down

0 comments on commit bb77eca

Please sign in to comment.