1// This work is subject to the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
2// license. Its contents can be found at:
3// http://creativecommons.org/publicdomain/zero/1.0/
4
5package bindata
6
7import (
8	"fmt"
9	"io"
10)
11
12// writeOneFileDebug writes the debug code file for each file (when splited file).
13func writeOneFileDebug(w io.Writer, c *Config, a *Asset) error {
14	if err := writeDebugFileHeader(w, c.Dev); err != nil {
15		return err
16	}
17
18	if err := writeDebugAsset(w, c, a); err != nil {
19		return err
20	}
21
22	return nil
23}
24
25// writeDebug writes the debug code file for single file.
26func writeDebug(w io.Writer, c *Config, toc []Asset) error {
27	err := writeDebugHeader(w)
28	if err != nil {
29		return err
30	}
31
32	for i := range toc {
33		err = writeDebugAsset(w, c, &toc[i])
34		if err != nil {
35			return err
36		}
37	}
38
39	return nil
40}
41
42// writeDebugHeader writes output file headers for each file.
43// This targets debug builds.
44func writeDebugFileHeader(w io.Writer, dev bool) error {
45	add := ""
46	if dev {
47		add = `
48	"path/filepath"`
49	}
50
51	_, err := fmt.Fprintf(w, `import (
52	"fmt"
53	"os"%s
54)
55
56`, add)
57
58	return err
59}
60
61// writeDebugHeader writes output file headers for sigle file.
62// This targets debug builds.
63func writeDebugHeader(w io.Writer) error {
64	_, err := fmt.Fprintf(w, `import (
65	"fmt"
66	"io/ioutil"
67	"os"
68	"path/filepath"
69	"strings"
70)
71
72// bindataRead reads the given file from disk. It returns an error on failure.
73func bindataRead(path, name string) ([]byte, error) {
74	buf, err := ioutil.ReadFile(path)
75	if err != nil {
76		err = fmt.Errorf("Error reading asset %%s at %%s: %%v", name, path, err)
77	}
78	return buf, err
79}
80
81type asset struct {
82	bytes []byte
83	info  os.FileInfo
84}
85
86`)
87	return err
88}
89
90// writeDebugAsset write a debug entry for the given asset.
91// A debug entry is simply a function which reads the asset from
92// the original file (e.g.: from disk).
93func writeDebugAsset(w io.Writer, c *Config, asset *Asset) error {
94	pathExpr := fmt.Sprintf("\"%s/%s\"", c.cwd, asset.Path)
95	if c.Dev {
96		pathExpr = fmt.Sprintf("filepath.Join(rootDir, %q)", asset.Name)
97	}
98
99	_, err := fmt.Fprintf(w, `// %s reads file data from disk. It returns an error on failure.
100func %s() (*asset, error) {
101	path := %s
102	name := %q
103	bytes, err := bindataRead(path, name)
104	if err != nil {
105		return nil, err
106	}
107
108	fi, err := os.Stat(path)
109	if err != nil {
110		err = fmt.Errorf("Error reading asset info %%s at %%s: %%v", name, path, err)
111	}
112
113	a := &asset{bytes: bytes, info: fi}
114	return a, err
115}
116
117`, asset.Func, asset.Func, pathExpr, asset.Name)
118	return err
119}
120