-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconverter.go
338 lines (311 loc) · 10.9 KB
/
converter.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package main
import (
"bytes"
"flag"
"fmt"
"github.com/atotto/clipboard"
"github.com/nuclearcookie/stringparsehelper"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
func main() {
var inputFilePath string
var outputFilePath string
ProcessArgs(&inputFilePath, &outputFilePath)
inputFilePath, outputFilePath = ValidatePaths(&inputFilePath, &outputFilePath)
text := Input(inputFilePath)
outputText := ConvertOfflineToOnline(text)
//permission 0644
Output(outputFilePath, outputText)
}
func ProcessArgs(input, output *string) {
flag.StringVar(input, "input", "", "The input file to convert")
flag.StringVar(output, "output", "", "The converted output file")
flag.Parse()
if *input == "" {
println("Please specify an input file by using the -input flag")
os.Exit(0)
}
}
func Input(inputFile string) string {
Format(inputFile)
buffer, err := ioutil.ReadFile(inputFile)
if err != nil {
log.Fatal(err)
}
return string(buffer)
}
func Output(path, text string) {
//First write to file, then call fmt on the file, then copy the filecontent!
ioutil.WriteFile(path, []byte(text), 0644)
Format(path)
Build(path)
buffer, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
err = clipboard.WriteAll(string(buffer))
if err != nil {
log.Fatal(err)
}
println("Output file generated at ", path, "! Copied online code to clipboard!")
}
func ValidatePaths(input, output *string) (string, string) {
//convert symbolic links to the real path
var newInput string
var newOutput string
var err error
newInput, err = filepath.EvalSymlinks(*input)
if err != nil {
log.Fatal(err)
}
newInput = *input
//check if the file exists
file, err := os.Open(newInput)
if err != nil {
log.Fatal(err)
}
err = file.Close()
if err != nil {
log.Fatal(err)
}
if *output == "" {
newOutput = filepath.Join(filepath.Dir(newInput), "OnlineCGCode.go")
} else {
newOutput = *output
/*newOutput, err = filepath.EvalSymlinks(*output)
if err != nil {
log.Fatal(err)
}*/
if filepath.Ext(*output) != ".go" {
println("Please make the output file a .go file to allow us to format and test it!")
}
}
return newInput, newOutput
}
func ConvertOfflineToOnline(text string) string {
inputChannelName := GetInputChannelName(text)
outputChannelName := GetOutputChannelName(text)
text = RemoveImport(text)
text = RemoveCGReaderMainFunction(text)
text = ImportMissingPackages(text)
text = ReplaceOutputCalls(text, outputChannelName)
text = ReplaceInputCalls(text, inputChannelName)
//println(text)
return text
}
//******************************************
// GETTERS
//******************************************
func GetInputChannelName(data string) string {
start, _ := stringparsehelper.FindFirstOfSubString(data, "<-chan string", true)
return stringparsehelper.GetLastWord(data[:start])
}
func GetOutputChannelName(data string) string {
//go fmt removes spaces between string and )
start, _ := stringparsehelper.FindFirstOfSubString(data, "chan string)", true)
return stringparsehelper.GetLastWord(data[:start])
}
//******************************************
// IMPORT BLOCK
//******************************************
func RemoveImport(data string) string {
start, end := GetImportBlock(data)
//end + 1 to include the last found rune
//note: reslicing does not copy over the data!
imports := data[start : end+1]
//make a copy by adding 1 char and taking a slice of all -1
originalImportsBlock := imports
originalImportsBlock += " "
originalImportsBlock = originalImportsBlock[:len(originalImportsBlock)-1]
//remove the cgreader import
start, end = stringparsehelper.FindIndicesBetweenRunesContaining(imports, '"', '"', "cgreader")
if start != -1 && end != -1 {
start = strings.LastIndex(imports[:start], "\n")
imports = imports[:start] + imports[end+1:]
}
data = strings.Replace(data, originalImportsBlock, imports, 1)
return data
}
func GetImportBlock(data string) (int, int) {
start, end := stringparsehelper.FindFirstOfSubString(data, "import", true)
if start != -1 && end != -1 {
if strings.IndexRune(data[start:], '(') < strings.IndexRune(data[start:], '"') {
//import structure surrounded by brackets
_, end = stringparsehelper.FindIndicesBetweenRunesWithStartingIndex(data, '(', ')', end)
} else {
_, end = stringparsehelper.FindIndicesBetweenRunesWithStartingIndex(data, '"', '"', end)
}
}
if start == -1 || end == -1 {
println("Something went wrong while finding the import block. Terminating..")
os.Exit(0)
}
return start, end
}
//******************************************
// MAIN FUNCTION REMOVAL BLOCK
//******************************************
func RemoveCGReaderMainFunction(data string) string {
start, end := GetCGReaderMainFunction(data)
if start != -1 && end != -1 {
mainString := data[start : end+1]
originalMainString := mainString
originalMainString += " "
originalMainString = originalMainString[:len(originalMainString)-1]
start, end = stringparsehelper.FindIndicesBetweenMatchingRunes(mainString, '{', '}', true)
if start != -1 && end != -1 {
mainString = mainString[start+1 : end]
data = strings.Replace(data, originalMainString, mainString, 1)
}
}
return data
}
func GetCGReaderMainFunction(data string) (int, int) {
start, end := -1, -1
start, end = stringparsehelper.FindFirstOfSubString(data, "cgreader.RunStaticPrograms", true)
if start == -1 {
start, end = stringparsehelper.FindFirstOfSubString(data, "cgreader.RunStaticProgram", true)
}
if start == -1 {
start, end = stringparsehelper.FindFirstOfSubString(data, "cgreader.RunInteractivePrograms", true)
println("Interactive challenges not yet supported!")
os.Exit(0)
}
if start == -1 {
start, end = stringparsehelper.FindFirstOfSubString(data, "cgreader.RunInteractiveProgram", true)
println("Interactive challenges not yet supported!")
os.Exit(0)
}
if start == -1 {
println("Unknown cgreader main function.. cannot remove it!")
os.Exit(0)
}
//Isolate the function
_, end = stringparsehelper.FindIndicesBetweenMatchingRunesWithStartingIndex(data, '(', ')', end+1, true)
return start, end
}
func ImportMissingPackages(data string) string {
//add log to the imports block if it's not there already
data = AddPackage(data, "log")
data = AddPackage(data, "fmt")
data = AddPackage(data, "bufio")
data = AddPackage(data, "os")
return data
}
func AddPackage(fileContent, packageName string) string {
start, end := GetImportBlock(fileContent)
importsBlock := fileContent[start : end+1]
packageName = "\"" + packageName + "\""
start, end = stringparsehelper.FindFirstOfSubString(importsBlock, packageName, false)
//block not found: add it here
if start == -1 && end == -1 {
//copy a string..
originalImportsBlock := importsBlock
originalImportsBlock += " "
originalImportsBlock = originalImportsBlock[:len(originalImportsBlock)-1]
start, end = stringparsehelper.FindIndicesBetweenRunes(importsBlock, '(', ')')
importsBlock = importsBlock[:end] + packageName + "\n" + importsBlock[end:]
fileContent = strings.Replace(fileContent, originalImportsBlock, importsBlock, 1)
}
return fileContent
}
//******************************************
// DEBUG OUTPUT REPLACE BLOCK
//******************************************
func ReplaceOutputCalls(data, outputChannelName string) string {
data = strings.Replace(data, "cgreader.Traceln", "log.Println", -1)
data = strings.Replace(data, "cgreader.Tracef", "log.Printf", -1)
data = strings.Replace(data, "cgreader.Trace", "log.Print", -1)
outputChannelName += " <- "
data = strings.Replace(data, outputChannelName+"fmt.Sprintf(", "fmt.Printf(", -1)
start, end := 0, 0
for ; start != -1 && end != -1; start, end = stringparsehelper.FindFirstOfSubStringWithStartingIndex(data, outputChannelName, end, true) {
endLine := strings.Index(data[end:], "\n")
endLine += end
subStart, subEnd := stringparsehelper.FindIndicesBetweenRunes(data[end:endLine], '"', '"')
if subStart != -1 && subEnd != -1 {
startUnimplBrackets, endUnimplBrackets := stringparsehelper.FindIndicesBetweenRunes(data[end:endLine], '(', ')')
if startUnimplBrackets != -1 && endUnimplBrackets != -1 && startUnimplBrackets < subStart && endUnimplBrackets > subEnd {
fmt.Printf("Probably Unimplemented output function found at: %s\n", data[end:endLine])
}
data = data[:start] + "fmt.Printf(" + data[end+subStart:end+subEnd+1] + ")" + data[end+subEnd+1:]
} else if start > 0 && end > 0 /*might be just a string that is being assigned to output? */ {
data = data[:start] + "fmt.Print(" + data[end:endLine] + ")" + data[endLine:]
}
}
return data
}
func ReplaceInputCalls(data string, inputChannelName string) string {
/*originalString := "fmt.Sscanln(<-"
originalString += inputChannelName
originalString += ","
data = strings.Replace(data, originalString, "fmt.Scanln(", -1)*/
scannerMade := false
start, end := stringparsehelper.FindFirstOfSubString(data, inputChannelName, true)
for start != -1 && end != -1 {
if stringparsehelper.IsWholeWord(data, start, end) {
//<-inputchannelname == read a whole line from input
if start > 2 {
//go fmt makes sure there are no spaces between <- and input
if data[start-2:start] == "<-" {
//take everything left of this operation and save it...
newLineIndex := strings.LastIndex(data[:start-2], "\n") + 1
variableName := data[newLineIndex : start-2]
//check if we have already made a scanner... we have to assume the user handles all input in the same function..
left, right := stringparsehelper.FindIndicesOfSurroundingRunesOfSubString(data, newLineIndex, end+1, '{', '}')
var newScannerString string
if !scannerMade {
newScannerString = "scanner := bufio.NewScanner(os.Stdin)"
left, right = stringparsehelper.FindFirstOfSubString(data[left+1:right], newScannerString, true)
if left == -1 && right == -1 {
newScannerString += "\n"
scannerMade = true
} else {
newScannerString = ""
}
} else {
newScannerString = ""
}
//remove the old line
data = data[:newLineIndex] + newScannerString + "scanner.Scan()\n" + variableName + "scanner.Text()" + data[end+1:]
}
}
}
start, end = stringparsehelper.FindFirstOfSubStringWithStartingIndex(data, inputChannelName, end+1, true)
}
return data
}
//******************************************
// COMMAND BLOCK
//******************************************
func Build(file string) {
if filepath.Ext(file) == ".go" {
cmd := exec.Command("go", "build", file)
cmd.Stdin = strings.NewReader(file)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
println(out.String())
if err != nil {
println("Error building the output file.. Sorry, there must still be a little error in the converter!")
}
}
}
func Format(file string) {
if filepath.Ext(file) == ".go" {
cmd := exec.Command("go", "fmt", file)
cmd.Stdin = strings.NewReader(file)
// var out bytes.Buffer
// cmd.Stdout = &out
err := cmd.Run()
// println(out.String())
if err != nil {
log.Fatal(err)
}
}
}