-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpassword.go
93 lines (83 loc) · 2.08 KB
/
password.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package csvutil
import (
"io"
"github.com/icrowley/fake"
"github.com/pkg/errors"
)
// PasswordOption is option holder for Password.
type PasswordOption struct {
// Source file does not have header line. (default false)
NoHeader bool
// Encoding of source file. (default utf8)
Encoding string
// Encoding for output.
OutputEncoding string
// Target column symbol.
Column string
// MinLength of password
MinLength int
// MaxLength of password
MaxLength int
// NoNumeric not using number flag
NoNumeric bool
// NoUpeer not using upper alphabets flag
NoUpper bool
// NoSpecial not using marks flag
NoSpecial bool
}
func (o PasswordOption) validate() error {
if o.Column == "" {
return errors.New("no column")
}
if o.NoHeader {
if !isDigit(o.Column) {
return errors.New("not number column symbol")
}
}
if o.MinLength <= 0 {
return errors.New("not positive min length")
}
if o.MaxLength <= 0 {
return errors.New("not positive max length")
}
if o.MinLength > o.MaxLength {
return errors.New("max length less than min length")
}
return nil
}
func (o PasswordOption) outputEncoding() string {
if o.OutputEncoding != "" {
return o.OutputEncoding
}
return o.Encoding
}
// Password overwrite value of given column by dummy password address.
func Password(r io.Reader, w io.Writer, o PasswordOption) error {
if err := o.validate(); err != nil {
return errors.Wrap(err, "invalid option")
}
cr, bom := reader(r, o.Encoding)
cw := writer(w, bom, o.outputEncoding())
defer cw.Flush()
var col *column
csvp := NewCSVProcessor(cr, cw)
if o.NoHeader {
csvp.SetPreBodyRead(func() error {
col = newColumnWithIndex(o.Column, nil)
return col.err
})
} else {
csvp.SetHeaderHanlder(func(hdr []string) ([]string, error) {
col = newColumnWithIndex(o.Column, hdr)
return hdr, col.err
})
}
csvp.SetRecordHandler(func(rec []string) ([]string, error) {
rec[col.index] = fakePassword(o)
return rec, nil
})
return csvp.Process()
}
func fakePassword(o PasswordOption) string {
return fake.Password(o.MinLength, o.MaxLength, !o.NoUpper, !o.NoNumeric, !o.NoSpecial)
}