-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
117 lines (93 loc) · 2.25 KB
/
main.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
flag "github.com/spf13/pflag"
ref "github.com/idlephysicist/go-latex/reference"
)
var (
commit, version string
files []string
ext string
versionFlg bool
)
func main() {
// Read file arg
flag.BoolVar(&versionFlg, "v", false, "Print version and exit")
flag.StringVarP(&ext, "ext", "e", "go", "File type to process")
flag.Parse()
fileArg := flag.Arg(0)
if versionFlg {
fmt.Printf("go-latex version: %s\nbuild commit: %s\n", version, commit)
os.Exit(0)
}
// Determine the arg we got i.e. a single .go file or a .
if fileArg == `.` {
err := findFiles(fileArg)
if err != nil {
log.Println(err)
}
} else {
if fileExists(fileArg) && filepath.Ext(fileArg) == `.` + ext {
files = append(files, fileArg)
} else {
log.Println("Error invalid file name")
os.Exit(1)
}
}
// Iterate through the files that we've found
for _, file := range files {
contents, err := ioutil.ReadFile(file)
if err != nil {
log.Println("An Error occured reading %s", err)
continue
}
fmt.Println(`Processing file:`, file)
updatedText := process(string(contents))
err = ioutil.WriteFile(file, []byte(updatedText), 0644)
if err != nil {
log.Fatalln(err)
}
}
}
// process takes the text from the source file, regexes it for LaTeX commands
//
func process(text string) string {
regex := regexp.MustCompile(`\\[A-Za-z][a-z]*[a-z]`)
var unicodedText []string
for _, line := range strings.Split(text, `\n`) {
allIndices := regex.FindAllStringIndex(line, -1)
for _, loc := range allIndices {
latexCmd := text[loc[0]:loc[1]]
unicodeString := ref.Chart[latexCmd]
line = strings.Replace(line, latexCmd, unicodeString, -1)
}
unicodedText = append(unicodedText, line)
}
return strings.Join(unicodedText, `\n`)
}
func findFiles(root string) error {
return filepath.Walk(root,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if filepath.Ext(path) == `.go` {
fmt.Println(`Found`, path)
files = append(files, path)
}
return nil
})
}
func fileExists(name string) bool {
info, err := os.Stat(name)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}