Add check to verify output file directory exists. (#131)

* Add check to verify output file directory exists.
* Change (and test) the error handling of the CheckDir function
* Add ADIF arguments tests 
* Add CSV arguments tests

---------

Co-authored-by: Jean-Marc MEESSEN <jean-marc@meessen-web.org>
pull/134/head
Nic Heath 8 months ago committed by GitHub
parent 92ae396b68
commit 5560c5a68a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -52,6 +52,14 @@ var adifCmd = &cobra.Command{
return fmt.Errorf("Too many arguments.%s", "") return fmt.Errorf("Too many arguments.%s", "")
} }
// Verify given output directory exists. This check should be performed
// Before running any long process so as to not make the user wait and
// then be notified the file cannot be written.
dirErr := CheckDir(outputFilename)
if dirErr != nil {
return dirErr
}
var adifParam = new(fleprocess.AdifParams) var adifParam = new(fleprocess.AdifParams)
adifParam.InputFilename = inputFilename adifParam.InputFilename = inputFilename
adifParam.OutputFilename = outputFilename adifParam.OutputFilename = outputFilename

@ -0,0 +1,75 @@
/*
Copyright © 2024 Jean-Marc Meessen jean-marc@meessen-web.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package flecmd
import (
"bytes"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_AdifWithoutParmMustFail(t *testing.T) {
actual := new(bytes.Buffer)
rootCmd.SetOut(actual)
rootCmd.SetErr(actual)
rootCmd.SetArgs([]string{"adif"})
error := rootCmd.Execute()
assert.Error(t, error, "Function call should have failed")
// Error is expected
expectedMsg := "Error: missing input file "
lines := strings.Split(actual.String(), "\n")
assert.Equal(t, expectedMsg, lines[0], "Function did not fail for the expected cause")
}
func Test_AdifWithToManyParmMustFail(t *testing.T) {
actual := new(bytes.Buffer)
rootCmd.SetOut(actual)
rootCmd.SetErr(actual)
rootCmd.SetArgs([]string{"adif", "param1", "param2", "param3"})
error := rootCmd.Execute()
assert.Error(t, error, "Function call should have failed")
// Error is expected
expectedMsg := "Error: Too many arguments."
lines := strings.Split(actual.String(), "\n")
assert.Equal(t, expectedMsg, lines[0], "Function did not fail for the expected cause")
}
func Test_AdifBadOutpoutDirMustFail(t *testing.T) {
actual := new(bytes.Buffer)
rootCmd.SetOut(actual)
rootCmd.SetErr(actual)
rootCmd.SetArgs([]string{"adif", "../test/data/fle-1.txt", "badDirectory/outputfile.adi"})
error := rootCmd.Execute()
assert.Error(t, error, "Function call should have failed")
// Error is expected
expectedMsg := "Error: The directory of specified output file (badDirectory) does not exist."
lines := strings.Split(actual.String(), "\n")
assert.Equal(t, expectedMsg, lines[0], "Function did not fail for the expected cause")
}

@ -51,6 +51,14 @@ func csvCmdConstructor() *cobra.Command {
return fmt.Errorf("Too many arguments.%s", "") return fmt.Errorf("Too many arguments.%s", "")
} }
// Verify given output directory exists. This check should be performed
// Before running any long process so as to not make the user wait and
// then be notified the file cannot be written.
dirErr := CheckDir(outputCsvFilename)
if dirErr != nil {
return dirErr
}
if err := fleprocess.ProcessCsvCommand(inputFilename, outputCsvFilename, isInterpolateTime, isOverwriteCsv); err != nil { if err := fleprocess.ProcessCsvCommand(inputFilename, outputCsvFilename, isInterpolateTime, isOverwriteCsv); err != nil {
fmt.Println("\nUnable to generate CSV file:") fmt.Println("\nUnable to generate CSV file:")
fmt.Println(err) fmt.Println(err)

@ -0,0 +1,75 @@
/*
Copyright © 2024 Jean-Marc Meessen jean-marc@meessen-web.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package flecmd
import (
"bytes"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_CsvWithoutParmMustFail(t *testing.T) {
actual := new(bytes.Buffer)
rootCmd.SetOut(actual)
rootCmd.SetErr(actual)
rootCmd.SetArgs([]string{"csv"})
error := rootCmd.Execute()
assert.Error(t, error, "Function call should have failed")
// Error is expected
expectedMsg := "Error: Missing input file "
lines := strings.Split(actual.String(), "\n")
assert.Equal(t, expectedMsg, lines[0], "Function did not fail for the expected cause")
}
func Test_CsvWithToManyParmMustFail(t *testing.T) {
actual := new(bytes.Buffer)
rootCmd.SetOut(actual)
rootCmd.SetErr(actual)
rootCmd.SetArgs([]string{"csv", "param1", "param2", "param3"})
error := rootCmd.Execute()
assert.Error(t, error, "Function call should have failed")
// Error is expected
expectedMsg := "Error: Too many arguments."
lines := strings.Split(actual.String(), "\n")
assert.Equal(t, expectedMsg, lines[0], "Function did not fail for the expected cause")
}
func Test_CsvBadOutpoutDirMustFail(t *testing.T) {
actual := new(bytes.Buffer)
rootCmd.SetOut(actual)
rootCmd.SetErr(actual)
rootCmd.SetArgs([]string{"csv", "../test/data/fle-1.txt", "badDirectory/outputfile.adi"})
error := rootCmd.Execute()
assert.Error(t, error, "Function call should have failed")
// Error is expected
expectedMsg := "Error: The directory of specified output file (badDirectory) does not exist."
lines := strings.Split(actual.String(), "\n")
assert.Equal(t, expectedMsg, lines[0], "Function did not fail for the expected cause")
}

@ -25,6 +25,7 @@ THE SOFTWARE.
import ( import (
"fmt" "fmt"
"os" "os"
"path/filepath"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -83,3 +84,15 @@ func initConfig() {
fmt.Println("Using config file:", viper.ConfigFileUsed()) fmt.Println("Using config file:", viper.ConfigFileUsed())
} }
} }
// CheckDir verifies a given path/file string actually exists. If it does not
// then exit with an error.
func CheckDir(file string) error {
path := filepath.Dir(file)
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("The directory of specified output file (%s) does not exist.", path)
}
}
return nil
}

@ -0,0 +1,53 @@
/*
Copyright © 2024 Jean-Marc Meessen jean-marc@meessen-web.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package flecmd
import "testing"
func TestCheckDir(t *testing.T) {
type args struct {
file string
}
tests := []struct {
name string
args args
wantErr bool
}{
{
"Valid directory",
args{file: "../test/data/fle-1.txt"},
false,
},
{
"Invalid directory",
args{file: "../junkDir/fle-1.txt"},
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := CheckDir(tt.args.file); (err != nil) != tt.wantErr {
t.Errorf("CheckDir() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}

@ -99,7 +99,7 @@ func buildAdif(fullLog []LogLine, adifParams AdifParams) (adifList []string) {
} }
if logLine.MyLon != "" { if logLine.MyLon != "" {
adifLine.WriteString(adifElement("MY_LON", logLine.MyLon)) adifLine.WriteString(adifElement("MY_LON", logLine.MyLon))
} }
if logLine.MyCounty != "" { if logLine.MyCounty != "" {
adifLine.WriteString(adifElement("MY_CNTY", logLine.MyCounty)) adifLine.WriteString(adifElement("MY_CNTY", logLine.MyCounty))
} }

@ -78,15 +78,15 @@ func SprintHeaderValues(logLine LogLine) string {
if logLine.MyGrid != "" { if logLine.MyGrid != "" {
output.WriteString("MyGrid " + logLine.MyGrid + "\n") output.WriteString("MyGrid " + logLine.MyGrid + "\n")
} }
if logLine.MyLat != "" { if logLine.MyLat != "" {
output.WriteString("MyLat " + logLine.MyLat + "\n") output.WriteString("MyLat " + logLine.MyLat + "\n")
} }
if logLine.MyLon != "" { if logLine.MyLon != "" {
output.WriteString("MyLon " + logLine.MyLon + "\n") output.WriteString("MyLon " + logLine.MyLon + "\n")
} }
if logLine.MyCounty != "" { if logLine.MyCounty != "" {
output.WriteString("MyCounty " + logLine.MyCounty + "\n") output.WriteString("MyCounty " + logLine.MyCounty + "\n")
} }

@ -284,11 +284,11 @@ func LoadFile(inputFilename string, isInterpolateTime bool) (filleFullLog []LogL
if len(errorMsg) != 0 { if len(errorMsg) != 0 {
errorLog = append(errorLog, fmt.Sprintf("Invalid \"My Lon\" at line %d: %s (%s)", lineCount, myLonList[1], errorMsg)) errorLog = append(errorLog, fmt.Sprintf("Invalid \"My Lon\" at line %d: %s (%s)", lineCount, myLonList[1], errorMsg))
} }
} }
//If there is no data after the marker, we just skip the data. //If there is no data after the marker, we just skip the data.
continue continue
} }
//My County //My County
if regexpHeaderMyCounty.MatchString(eachline) { if regexpHeaderMyCounty.MatchString(eachline) {
myMyCountyList := regexpHeaderMyCounty.Split(eachline, -1) myMyCountyList := regexpHeaderMyCounty.Split(eachline, -1)

@ -19,9 +19,9 @@ limitations under the License.
import ( import (
"fmt" "fmt"
"regexp" "regexp"
"strconv"
"strings" "strings"
"time" "time"
"strconv"
) )
// ValidateLat checks if value is within range of +-90 degrees inclusive. // ValidateLat checks if value is within range of +-90 degrees inclusive.

@ -6,15 +6,18 @@ require (
github.com/mitchellh/go-homedir v1.1.0 github.com/mitchellh/go-homedir v1.1.0
github.com/spf13/cobra v1.8.0 github.com/spf13/cobra v1.8.0
github.com/spf13/viper v1.18.2 github.com/spf13/viper v1.18.2
github.com/stretchr/testify v1.8.4
) )
require ( require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect github.com/magiconair/properties v1.8.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect github.com/sourcegraph/conc v0.3.0 // indirect

@ -2,6 +2,7 @@ github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46t
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
@ -22,6 +23,7 @@ github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=

Loading…
Cancel
Save