1
0
Fork 0
mirror of https://github.com/on4kjm/FLEcli.git synced 2025-02-12 10:32:29 +01:00
FLEcli/cmd/output_filename.go

79 lines
2.1 KiB
Go
Raw Normal View History

2020-06-27 22:53:23 +02:00
package cmd
/*
Copyright © 2020 Jean-Marc Meessen, ON4KJM <on4kjm@gmail.com>
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.
*/
import (
"os"
"fmt"
"path/filepath"
2020-06-27 22:53:23 +02:00
)
// does the target file exist?
// is the file defined
// remove the extention
//returning "" is considered as invalid
2020-07-13 21:25:06 +02:00
func buildOutputFilename(output string, input string, overwrite bool, newExtension string) (outputFilename string, wasOK bool) {
2020-06-27 22:53:23 +02:00
outputFilename = ""
//validate that input is populated (should never happen if properly called)
if input == "" {
return "", false
}
//No output was provided, let's create one from the input file
if output == "" {
extension := filepath.Ext(input)
2020-06-30 22:20:56 +02:00
outputRootPart := input[0 : len(input)-len(extension)]
2020-07-13 21:25:06 +02:00
output = outputRootPart + newExtension
2020-06-30 22:20:56 +02:00
fmt.Println("No output provided, defaulting to \"" + output + "\"")
}
2020-06-27 22:53:23 +02:00
//an output was provided by the user
if output != "" {
info, err := os.Stat(output)
if os.IsNotExist(err) {
2020-07-01 13:53:53 +02:00
//File doesn't exist, so we're good
2020-06-27 22:53:23 +02:00
return output, true
}
//It exisits but is a directory
if info.IsDir() {
fmt.Println("Error: specified output exists and is a directory")
return "", false
}
if overwrite {
//user accepted to overwrite the file
return output, true
}
2020-07-01 13:53:53 +02:00
fmt.Println("File already exists. Use --overwrite flag if necessary.")
return "", false
2020-06-27 22:53:23 +02:00
}
return outputFilename, true
}
// fileExists checks if a file exists and is not a directory before we
// try using it to prevent further errors.
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}