-
Notifications
You must be signed in to change notification settings - Fork 5
/
sol.go
95 lines (77 loc) · 1.81 KB
/
sol.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
94
95
package sol
import (
"fmt"
"github.com/noperator/jqfmt"
)
type SolCfg struct {
Args bool
BinCmd bool
Clause bool
CmdSubst bool
Env bool
ProcSubst bool
Redir bool
MaxWidth int
OneLine bool
Sh bool
Jq bool
JqFmtCfg jqfmt.JqFmtCfg
// JqFuncs []string
}
var Cfg SolCfg
var env *shellEnv
func Format(src string) (string, error) {
var err error
Cmds = make(map[string]string)
if Cfg.Env {
nonstdCmds = []string{}
nonstdCmdDefs = map[string]string{}
env, err = getShellEnv()
if err != nil {
return "", fmt.Errorf("could not get shell environment: %v", err)
}
}
srcFmt, err := fmtProg(src)
if err != nil {
return "", fmt.Errorf("could not format program: %v", err)
}
// First, implode program.
srcMod, err := ImplodeSh(srcFmt)
if err != nil {
return "", fmt.Errorf("could not implode shell: %v", err)
}
// If not one-line mode, explode program.
if !Cfg.OneLine {
srcMod, err = ExplodeSh(srcMod, 0, true)
if err != nil {
return "", fmt.Errorf("could not explode shell: %v", err)
}
}
// Prettify modified program.
srcModFmt, err := fmtProg(srcMod)
if err != nil {
return "", fmt.Errorf("could not format program: %v", err)
}
// Normalize indents.
srcModFmtNml, err := normalizeIndents(srcModFmt)
if err != nil {
return "", fmt.Errorf("could not clean up program: %v", err)
}
// Prepend non-standard command definitions to formatted program.
if Cfg.Env {
for _, cmd := range nonstdCmds {
if _, ok := nonstdCmdDefs[cmd]; ok {
srcModFmtNml = nonstdCmdDefs[cmd] + "\n" + srcModFmtNml
}
}
}
if Cfg.MaxWidth > 0 {
srcModFmtNmlWid, err := enforceMaxWidth(srcModFmtNml)
if err != nil {
return "", fmt.Errorf("could not enforce max width: %v", err)
}
return srcModFmtNmlWid, nil
} else {
return srcModFmtNml, nil
}
}