-
Notifications
You must be signed in to change notification settings - Fork 146
/
reformat.go
69 lines (57 loc) · 1.3 KB
/
reformat.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
// Copyright 2019 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"github.com/moov-io/ach"
)
func reformat(as string, filepath string) error {
if _, err := os.Stat(filepath); err != nil {
return err
}
file, err := readIncomingFile(filepath)
if err != nil {
return err
}
switch as {
case "ach":
w := ach.NewWriter(os.Stdout)
if err := w.Write(file); err != nil {
return err
}
case "json":
if err := json.NewEncoder(os.Stdout).Encode(file); err != nil {
return err
}
default:
return fmt.Errorf("unknown format %s", as)
}
return nil
}
func readIncomingFile(path string) (*ach.File, error) {
file, err := readJsonFile(path)
if file != nil && err == nil {
return file, nil
}
file, err = readACHFile(path)
if file != nil && err == nil {
return file, nil
}
return nil, fmt.Errorf("unable to read %s:\n %v", path, err)
}
func readJsonFile(path string) (*ach.File, error) {
fd, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("problem opening %s: %v", path, err)
}
defer fd.Close()
bs, err := ioutil.ReadAll(fd)
if err != nil {
return nil, fmt.Errorf("problem reading %s: %v", path, err)
}
return ach.FileFromJSON(bs)
}