Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cap requires names; panics with only default-name #49

Closed
zacharysyoung opened this issue Aug 20, 2023 · 0 comments
Closed

Cap requires names; panics with only default-name #49

zacharysyoung opened this issue Aug 20, 2023 · 0 comments

Comments

@zacharysyoung
Copy link
Contributor

zacharysyoung commented Aug 20, 2023

The bigger logic of Cap (implicitly) allows for the user to leave the --names flag empty and specify only --default-name:

If names happens to be an empty slice, then numNames is 0. The first half of the predicate is true, but if defaultName is not empty then Cap doesn't error-out:

gocsv/cmd/cap.go

Lines 49 to 52 in f9d4372

if numColumns > numNames && defaultName == "" {
fmt.Fprintf(os.Stderr, "Must specify --default-name if there are more columns than column names provided")
os.Exit(1)
}

Then... with nunNames being 0, the code flows through the else statement and builds the header exclusively off of defaultName:

gocsv/cmd/cap.go

Lines 60 to 71 in f9d4372

for i := range firstRow {
if i < numNames {
newHeader[i] = names[i]
} else {
if j == 0 {
newHeader[i] = defaultName
} else {
newHeader[i] = fmt.Sprintf("%s %d", defaultName, j)
}
j++
}
}

And I would like this behavior: if I have a headerless CSV with any number of columns that I want to feed into another GoCSV command I want to easily cap it with --default-name=Col.

But, prior to that, Cap tries to create the slice of strings, names, based on the assumption that the --names flag is not an empty string:

gocsv/cmd/cap.go

Lines 37 to 40 in f9d4372

func (sub *CapSubcommand) RunCap(inputCsv *InputCsv, outputCsvWriter OutputCsvWriter) {
names := GetArrayFromCsvString(sub.namesString)
Cap(inputCsv, outputCsvWriter, names, sub.truncateNames, sub.defaultName)
}

The call to GetArrayFromCsvString(...) will panic if the passed string is empty.

I propose:

  1. marking the --names flag optional in documentation
  2. adding a check in RunCap to make sure at least one the --names or --default-name flags were set on the command line
  3. guarding against passing an empty string to GetArrayFromCsvString() in RunCap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants