Skip to content

Commit

Permalink
refactor: cleaner code structure by using switch
Browse files Browse the repository at this point in the history
  • Loading branch information
nanjiangshu committed Sep 20, 2024
1 parent 4604bdb commit d807608
Showing 1 changed file with 13 additions and 28 deletions.
41 changes: 13 additions & 28 deletions decrypt/decrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,41 +79,26 @@ func Decrypt(args []string) error {
return err
}

var warnings []string
// Check that all the encrypted files exist, and all the unencrypted don't
for _, file := range files {
// check that the input file exists and is readable
if !helpers.FileIsReadable(file.Encrypted) {
warnings = append(warnings, fmt.Sprintf("Warning: cannot read input file %s", file.Encrypted))

continue
}

// check that the output file doesn't exist
if helpers.FileExists(file.Unencrypted) && !*forceOverwrite {
warnings = append(warnings, fmt.Sprintf("Warning: output file %s already exists", file.Unencrypted))
}
}

// Print warnings if any
if len(warnings) > 0 {
for _, warning := range warnings {
fmt.Println(warning)
}
}

// decrypt the input files
numFiles := len(files)
for i, file := range files {
if helpers.FileIsReadable(file.Encrypted) && !helpers.FileExists(file.Unencrypted) || *forceOverwrite {
switch {
case !helpers.FileIsReadable(file.Encrypted):
fmt.Fprintf(os.Stderr, "Warning: cannot read input file %s\n", file.Encrypted)
case *forceOverwrite:
fmt.Printf("Decrypting file %v/%v: %s\n", i+1, numFiles, file.Encrypted)
err := decryptFile(file.Encrypted, file.Unencrypted, *privateKey)
if err != nil {
fmt.Fprintf(os.Stderr, "Error decrypting file %s: %v\n", file.Encrypted, err)
}
case helpers.FileExists(file.Unencrypted):
fmt.Fprintf(os.Stderr, "Warning: file %s is already decrypted, skipping\n", file.Unencrypted)
default:
fmt.Printf("Decrypting file %v/%v: %s\n", i+1, numFiles, file.Encrypted)
err := decryptFile(file.Encrypted, file.Unencrypted, *privateKey)
if err != nil {
fmt.Printf("Error decrypting file %s: %v\n", file.Encrypted, err)
fmt.Fprintf(os.Stderr, "Error decrypting file %s: %v\n", file.Encrypted, err)
}
} else if helpers.FileExists(file.Unencrypted) {
// Skip decrypting if the file already exists and forceOverwrite is not set
fmt.Printf("Skipping decryption for file %s as it already exists and forceOverwrite is not enabled\n", file.Unencrypted)
}
}

Expand Down

0 comments on commit d807608

Please sign in to comment.