aboutsummaryrefslogtreecommitdiffstats
path: root/Godeps/_workspace/src/github.com/obscuren/qml/cmd/genqrc/main.go
blob: a601d812669526027c1247699f43b8094911af37 (plain) (blame)
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

// XXX: The documentation is duplicated here and in the the doc variable
// below. Update both at the same time.

// Command genqrc packs resource files into the Go binary.
//
// Usage: genqrc [options] <subdir1> [<subdir2> ...]
// 
// The genqrc tool packs all resource files under the provided subdirectories into
// a single qrc.go file that may be built into the generated binary. Bundled files
// may then be loaded by Go or QML code under the URL "qrc:///some/path", where
// "some/path" matches the original path for the resource file locally.
// 
// For example, the following will load a .qml file from the resource pack, and
// that file may in turn reference other content (code, images, etc) in the pack:
// 
//     component, err := engine.LoadFile("qrc://path/to/file.qml")
// 
// Starting with Go 1.4, this tool may be conveniently run by the "go generate"
// subcommand by adding a line similar to the following one to any existent .go
// file in the project (assuming the subdirectories ./code/ and ./images/ exist):
// 
//     //go:generate genqrc code images
// 
// Then, just run "go generate" to update the qrc.go file.
// 
// During development, the generated qrc.go can repack the filesystem content at
// runtime to avoid the process of regenerating the qrc.go file and rebuilding the
// application to test every minor change made. Runtime repacking is enabled by
// setting the QRC_REPACK environment variable to 1:
// 
//     export QRC_REPACK=1
// 
// This does not update the static content in the qrc.go file, though, so after
// the changes are performed, genqrc must be run again to update the content that
// will ship with built binaries.
package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
    "text/template"

    "gopkg.in/qml.v1"
)

const doc = `
Usage: genqrc [options] <subdir1> [<subdir2> ...]

The genqrc tool packs all resource files under the provided subdirectories into
a single qrc.go file that may be built into the generated binary. Bundled files
may then be loaded by Go or QML code under the URL "qrc:///some/path", where
"some/path" matches the original path for the resource file locally.

For example, the following will load a .qml file from the resource pack, and
that file may in turn reference other content (code, images, etc) in the pack:

    component, err := engine.LoadFile("qrc://path/to/file.qml")

Starting with Go 1.4, this tool may be conveniently run by the "go generate"
subcommand by adding a line similar to the following one to any existent .go
file in the project (assuming the subdirectories ./code/ and ./images/ exist):

    //go:generate genqrc code images

Then, just run "go generate" to update the qrc.go file.

During development, the generated qrc.go can repack the filesystem content at
runtime to avoid the process of regenerating the qrc.go file and rebuilding the
application to test every minor change made. Runtime repacking is enabled by
setting the QRC_REPACK environment variable to 1:

    export QRC_REPACK=1

This does not update the static content in the qrc.go file, though, so after
the changes are performed, genqrc must be run again to update the content that
will ship with built binaries.
`

// XXX: The documentation is duplicated here and in the the package comment
// above. Update both at the same time.

var packageName = flag.String("package", "main", "package name that qrc.go will be under (not needed for go generate)")

func main() {
    flag.Usage = func() {
        fmt.Fprintf(os.Stderr, "%s", doc)
        flag.PrintDefaults()
    }
    flag.Parse()
    if err := run(); err != nil {
        fmt.Fprintf(os.Stderr, "error: %v\n", err)
        os.Exit(1)
    }
}

func run() error {
    subdirs := flag.Args()
    if len(subdirs) == 0 {
        return fmt.Errorf("must provide at least one subdirectory path")
    }

    var rp qml.ResourcesPacker

    for _, subdir := range flag.Args() {
        err := filepath.Walk(subdir, func(path string, info os.FileInfo, err error) error {
            if err != nil {
                return err
            }
            if info.IsDir() {
                return nil
            }
            data, err := ioutil.ReadFile(path)
            if err != nil {
                return err
            }
            rp.Add(filepath.ToSlash(path), data)
            return nil
        })
        if err != nil {
            return err
        }
    }

    resdata := rp.Pack().Bytes()

    f, err := os.Create("qrc.go")
    if err != nil {
        return err
    }
    defer f.Close()

    data := templateData{
        PackageName:   *packageName,
        SubDirs:       subdirs,
        ResourcesData: resdata,
    }

    // $GOPACKAGE is set automatically by go generate.
    if pkgname := os.Getenv("GOPACKAGE"); pkgname != "" {
        data.PackageName = pkgname
    }

    return tmpl.Execute(f, data)
}

type templateData struct {
    PackageName   string
    SubDirs       []string
    ResourcesData []byte
}

func buildTemplate(name, content string) *template.Template {
    return template.Must(template.New(name).Parse(content))
}

var tmpl = buildTemplate("qrc.go", `package {{.PackageName}}

// This file is automatically generated by gopkg.in/qml.v1/cmd/genqrc

import (
    "io/ioutil"
    "os"
    "path/filepath"

    "gopkg.in/qml.v1"
)

func init() {
    var r *qml.Resources
    var err error
    if os.Getenv("QRC_REPACK") == "1" {
        err = qrcRepackResources()
        if err != nil {
            panic("cannot repack qrc resources: " + err.Error())
        }
        r, err = qml.ParseResources(qrcResourcesRepacked)
    } else {
        r, err = qml.ParseResourcesString(qrcResourcesData)
    }
    if err != nil {
        panic("cannot parse bundled resources data: " + err.Error())
    }
    qml.LoadResources(r)
}

func qrcRepackResources() error {
    subdirs := {{printf "%#v" .SubDirs}}
    var rp qml.ResourcesPacker
    for _, subdir := range subdirs {
        err := filepath.Walk(subdir, func(path string, info os.FileInfo, err error) error {
            if err != nil {
                return err
            }
            if info.IsDir() {
                return nil
            }
            data, err := ioutil.ReadFile(path)
            if err != nil {
                return err
            }
            rp.Add(filepath.ToSlash(path), data)
            return nil
        })
        if err != nil {
            return err
        }
    }
    qrcResourcesRepacked = rp.Pack().Bytes()
    return nil
}

var qrcResourcesRepacked []byte
var qrcResourcesData = {{printf "%q" .ResourcesData}}
`)