-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathfsql.go
55 lines (48 loc) · 1.09 KB
/
fsql.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
package fsql
import (
"bytes"
"fmt"
"os"
"github.com/kashav/fsql/parser"
)
// Run parses the input and executes the resultant query.
func Run(input string) error {
q, err := parser.Run(input)
if err != nil {
return err
}
// Find length of the longest name to normalize name output.
var max = 0
var results = make([]map[string]interface{}, 0)
err = q.Execute(
func(path string, info os.FileInfo, result map[string]interface{}) {
results = append(results, result)
if !q.HasAttribute("name") {
return
}
if s, ok := result["name"].(string); ok && len(s) > max {
max = len(s)
}
},
)
if err != nil {
return err
}
for _, result := range results {
var buf bytes.Buffer
for j, attribute := range q.Attributes {
// If the current attribute is "name", pad the output string by `max`
// spaces.
format := "%v"
if attribute == "name" {
format = fmt.Sprintf("%%-%ds", max)
}
buf.WriteString(fmt.Sprintf(format, result[attribute]))
if j != len(q.Attributes)-1 {
buf.WriteString("\t")
}
}
fmt.Printf("%s\n", buf.String())
}
return nil
}