commit 587457304e4818e048cbc9f4efbfc2b31dea10b3
parent 2e66dd61afbb2963c1d773aa59d88c8b96d3411b
Author: Sean Enck <sean@ttypty.com>
Date: Sun, 6 Oct 2024 07:27:11 -0400
this is a better way to handle user input
Diffstat:
2 files changed, 7 insertions(+), 20 deletions(-)
diff --git a/internal/app/pwgen.go b/internal/app/pwgen.go
@@ -90,19 +90,6 @@ func GeneratePassword(cmd CommandOptions) error {
}
choices = append(choices, use)
}
- found := len(choices)
- if found < length {
- return errors.New("choices <= word count requested")
- }
- if found > 1 {
- l := found - 1
- for i := 0; i <= l; i++ {
- n := rand.Intn(l)
- x := choices[i]
- choices[i] = choices[n]
- choices[n] = x
- }
- }
type position struct {
Start int
End int
@@ -111,17 +98,17 @@ func GeneratePassword(cmd CommandOptions) error {
Text string
Position position
}
+ found := len(choices)
+ if found == 0 {
+ return errors.New("no sources given")
+ }
var selected []word
cnt := 0
totalLength := 0
for cnt < length {
- choice := choices[cnt]
+ choice := choices[rand.Intn(found)]
textLength := len(choice)
- pos := position{}
- pos.Start = totalLength
- pos.End = pos.Start + textLength
- w := word{choices[cnt], pos}
- selected = append(selected, w)
+ selected = append(selected, word{choice, position{totalLength, totalLength + textLength}})
totalLength += textLength
cnt++
}
diff --git a/internal/app/pwgen_test.go b/internal/app/pwgen_test.go
@@ -39,7 +39,7 @@ func TestGenerateError(t *testing.T) {
t.Errorf("invalid error: %v", err)
}
os.Setenv("LOCKBOX_PWGEN_WORDLIST", pwgenPath)
- if err := app.GeneratePassword(m); err == nil || err.Error() != "choices <= word count requested" {
+ if err := app.GeneratePassword(m); err == nil || err.Error() != "no sources given" {
t.Errorf("invalid error: %v", err)
}
os.Setenv("LOCKBOX_PWGEN_WORDLIST", fmt.Sprintf("%s 1", pwgenPath))