|
| 1 | +package read |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + |
| 9 | + "github.com/moov-io/ach" |
| 10 | +) |
| 11 | + |
| 12 | +type Format string |
| 13 | + |
| 14 | +var ( |
| 15 | + FormatUnknown Format = "unknown" |
| 16 | + FormatNacha Format = "nacha" |
| 17 | + FormatJSON Format = "json" |
| 18 | +) |
| 19 | + |
| 20 | +func Filepath(path string, validateOptsPath *string, skipAll *bool) (*ach.File, Format, error) { |
| 21 | + validateOpts, err := readValidationOpts(validateOptsPath, skipAll) |
| 22 | + if err != nil { |
| 23 | + return nil, FormatUnknown, err |
| 24 | + } |
| 25 | + return readFile(path, validateOpts) |
| 26 | +} |
| 27 | + |
| 28 | +func readValidationOpts(path *string, skipAll *bool) (*ach.ValidateOpts, error) { |
| 29 | + var opts ach.ValidateOpts |
| 30 | + |
| 31 | + if skipAll != nil && *skipAll { |
| 32 | + opts.SkipAll = true |
| 33 | + return &opts, nil |
| 34 | + } |
| 35 | + |
| 36 | + if path != nil && *path != "" { |
| 37 | + // read config file |
| 38 | + bs, readErr := os.ReadFile(*path) |
| 39 | + if readErr != nil { |
| 40 | + return nil, fmt.Errorf("reading %s for validate opts failed: %w", *path, readErr) |
| 41 | + } |
| 42 | + |
| 43 | + if err := json.Unmarshal(bs, &opts); err != nil { |
| 44 | + return nil, fmt.Errorf("unmarshal of validate opts failed: %v", err) |
| 45 | + } |
| 46 | + return &opts, nil |
| 47 | + } |
| 48 | + |
| 49 | + return nil, nil |
| 50 | +} |
| 51 | + |
| 52 | +func readFile(path string, validateOpts *ach.ValidateOpts) (*ach.File, Format, error) { |
| 53 | + bs, err := os.ReadFile(path) |
| 54 | + if err != nil { |
| 55 | + return nil, FormatUnknown, err |
| 56 | + } |
| 57 | + if json.Valid(bs) { |
| 58 | + return readJsonFile(bs, validateOpts) |
| 59 | + } |
| 60 | + return readACHFile(bs, validateOpts) |
| 61 | +} |
| 62 | + |
| 63 | +func readACHFile(input []byte, validateOpts *ach.ValidateOpts) (*ach.File, Format, error) { |
| 64 | + r := ach.NewReader(bytes.NewReader(input)) |
| 65 | + r.SetValidation(validateOpts) |
| 66 | + |
| 67 | + f, err := r.Read() |
| 68 | + |
| 69 | + return &f, FormatNacha, err |
| 70 | +} |
| 71 | + |
| 72 | +func readJsonFile(input []byte, validateOpts *ach.ValidateOpts) (*ach.File, Format, error) { |
| 73 | + file, err := ach.FileFromJSONWith(input, validateOpts) |
| 74 | + return file, FormatJSON, err |
| 75 | +} |
0 commit comments