-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathextract_strings_from_source.go
More file actions
60 lines (57 loc) · 1.33 KB
/
extract_strings_from_source.go
File metadata and controls
60 lines (57 loc) · 1.33 KB
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
package extract
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
)
// StringsFromSource parses the Go files (recursively) contained in the given
// dir, and returns any string literals contained therein.
func StringsFromSource(dir string) ([]string, error) {
var strs []string
if err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() || strings.Contains(path, ".git") {
return nil
}
pkgs, err := parser.ParseDir(new(token.FileSet), path, nil, 0)
if err != nil {
return err
}
for _, pkg := range pkgs {
ast.Inspect(pkg, func(n ast.Node) bool {
lit, ok := n.(*ast.BasicLit)
if !ok || lit.Kind != token.STRING {
return true
}
unquoted, err := strconv.Unquote(lit.Value)
if !ok {
// Shouldn't ever happen because we've validated that it's a string literal.
panic(fmt.Sprintf("could not unquote string '%s' from AST: %v", lit.Value, err))
}
strs = append(strs, unquoted)
return true
})
}
return nil
}); err != nil {
return nil, err
}
strSet := map[string]struct{}{}
for _, s := range strs {
strSet[strings.TrimSpace(s)] = struct{}{}
}
strs = strs[:0]
for s := range strSet {
strs = append(strs, s)
}
sort.Strings(strs)
return strs, nil
}