-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (66 loc) · 1.46 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
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"log"
"os"
"strings"
)
var (
inputFilename string
)
// readLines reads a whole file into memory
// and returns a slice of its lines.
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
// reports whether the named file or directory exists.
func exists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func generateRedisScript(lines []string) string {
var buffer bytes.Buffer
for _, line := range lines {
words := strings.Split(line, " ")
statement := fmt.Sprintf("*%d\r\n", len(words))
for i := 0; i < len(words); i++ {
word := words[i]
statement += fmt.Sprintf("$%d\r\n%s\r\n", len(word), word)
}
buffer.WriteString(statement)
}
return buffer.String()
}
func main() {
flag.StringVar(&inputFilename, "i", "", "input filename")
flag.Parse()
if len(inputFilename) == 0 {
log.Fatal("Please specify an input filename using the -i option")
}
if !exists(inputFilename) {
log.Fatal("Specified filename does not exist")
}
//Read the lines of the source file into a slice
lines, er := readLines(inputFilename)
if er != nil {
log.Fatal(er)
}
fmt.Printf(generateRedisScript(lines))
}