forked from kaycoinsUSA/sourcegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringdata.go
More file actions
69 lines (58 loc) · 1.73 KB
/
Copy pathstringdata.go
File metadata and controls
69 lines (58 loc) · 1.73 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
61
62
63
64
65
66
67
68
69
// +build ignore
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
)
var (
inputFile = flag.String("i", "", "input file")
outputFile = flag.String("o", "", "output file")
constName = flag.String("name", "stringdata", "name of Go const")
pkgName = flag.String("pkg", "main", "Go package name")
)
func main() {
flag.Parse()
if *inputFile == "" || *outputFile == "" {
flag.Usage()
os.Exit(1)
}
data, err := ioutil.ReadFile(*inputFile)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
output := bytes.NewBuffer(nil)
fmt.Fprintln(output, "// Code generated by stringdata. DO NOT EDIT.")
fmt.Fprintln(output)
fmt.Fprintf(output, "package %s\n", *pkgName)
fmt.Fprintln(output)
fmt.Fprintf(output, "// %s is the content of the file %q.\n", *constName, *inputFile)
fmt.Fprintf(output, "const %s = %s", *constName, backtickStringLiteral(string(data)))
fmt.Fprintln(output)
err = writeFileIfDifferent(*outputFile, output.Bytes())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func backtickStringLiteral(data string) string {
return "`" + strings.Replace(data, "`", "` + \"`\" + `", -1) + "`"
}
// writeFileIfDifferent is like ioutil.WriteFile, except it only writes if the
// contents at path are different to data. This is to avoid triggering file
// watchers if there is no change.
func writeFileIfDifferent(path string, data []byte) error {
old, err := ioutil.ReadFile(path)
if err == nil && bytes.Equal(old, data) {
// Skip writing
return nil
}
// err can be non-nil now. The expected error is os.ErrNotExist. However,
// other errors can occur. In any case we just want to attempt doing a write
// and return that error.
return ioutil.WriteFile(path, data, 0666)
}