1
0

statik.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package contains a program that generates code to register
  15. // a directory and its contents as zip data for statik file system.
  16. package main
  17. import (
  18. "archive/zip"
  19. "bytes"
  20. "flag"
  21. "fmt"
  22. "io"
  23. "io/ioutil"
  24. "os"
  25. "path"
  26. "path/filepath"
  27. "strings"
  28. )
  29. const (
  30. namePackage = "statik"
  31. nameSourceFile = "statik.go"
  32. )
  33. var (
  34. flagSrc = flag.String("src", path.Join(".", "public"), "The path of the source directory.")
  35. flagDest = flag.String("dest", ".", "The destination path of the generated package.")
  36. )
  37. func main() {
  38. flag.Parse()
  39. file, err := generateSource(*flagSrc)
  40. if err != nil {
  41. exitWithError(err)
  42. }
  43. destDir := path.Join(*flagDest, namePackage)
  44. err = os.MkdirAll(destDir, 0755)
  45. if err != nil {
  46. exitWithError(err)
  47. }
  48. err = rename(file.Name(), path.Join(destDir, nameSourceFile))
  49. if err != nil {
  50. exitWithError(err)
  51. }
  52. }
  53. // rename tries to os.Rename, but fall backs to copying from src
  54. // to dest and unlink the source if os.Rename fails.
  55. func rename(src, dest string) error {
  56. // Try to rename generated source.
  57. if err := os.Rename(src, dest); err == nil {
  58. return nil
  59. }
  60. // If the rename failed (might do so due to temporary file residing on a
  61. // different device), try to copy byte by byte.
  62. rc, err := os.Open(src)
  63. if err != nil {
  64. return err
  65. }
  66. defer func() {
  67. rc.Close()
  68. os.Remove(src) // ignore the error, source is in tmp.
  69. }()
  70. if _, err = os.Stat(dest); !os.IsNotExist(err) {
  71. return fmt.Errorf("file %q already exists", dest)
  72. }
  73. wc, err := os.Create(dest)
  74. if err != nil {
  75. return err
  76. }
  77. defer wc.Close()
  78. if _, err = io.Copy(wc, rc); err != nil {
  79. // Delete remains of failed copy attempt.
  80. os.Remove(dest)
  81. }
  82. return err
  83. }
  84. // Walks on the source path and generates source code
  85. // that contains source directory's contents as zip contents.
  86. // Generates source registers generated zip contents data to
  87. // be read by the statik/fs HTTP file system.
  88. func generateSource(srcPath string) (file *os.File, err error) {
  89. var (
  90. buffer bytes.Buffer
  91. zipWriter io.Writer
  92. )
  93. zipWriter = &buffer
  94. f, err := ioutil.TempFile("", namePackage)
  95. if err != nil {
  96. return
  97. }
  98. zipWriter = io.MultiWriter(zipWriter, f)
  99. defer f.Close()
  100. w := zip.NewWriter(zipWriter)
  101. if err = filepath.Walk(srcPath, func(path string, fi os.FileInfo, err error) error {
  102. if err != nil {
  103. return err
  104. }
  105. // Ignore directories and hidden files.
  106. // No entry is needed for directories in a zip file.
  107. // Each file is represented with a path, no directory
  108. // entities are required to build the hierarchy.
  109. if fi.IsDir() || strings.HasPrefix(fi.Name(), ".") {
  110. return nil
  111. }
  112. relPath, err := filepath.Rel(srcPath, path)
  113. if err != nil {
  114. return err
  115. }
  116. b, err := ioutil.ReadFile(path)
  117. if err != nil {
  118. return err
  119. }
  120. fHeader, err := zip.FileInfoHeader(fi)
  121. if err != nil {
  122. return err
  123. }
  124. fHeader.Name = filepath.ToSlash(relPath)
  125. f, err := w.CreateHeader(fHeader)
  126. if err != nil {
  127. return err
  128. }
  129. _, err = f.Write(b)
  130. return err
  131. }); err != nil {
  132. return
  133. }
  134. if err = w.Close(); err != nil {
  135. return
  136. }
  137. // then embed it as a quoted string
  138. var qb bytes.Buffer
  139. fmt.Fprintf(&qb, `package %s
  140. import (
  141. "github.com/rakyll/statik/fs"
  142. )
  143. func init() {
  144. data := "`, namePackage)
  145. FprintZipData(&qb, buffer.Bytes())
  146. fmt.Fprint(&qb, `"
  147. fs.Register(data)
  148. }
  149. `)
  150. if err = ioutil.WriteFile(f.Name(), qb.Bytes(), 0644); err != nil {
  151. return
  152. }
  153. return f, nil
  154. }
  155. // Converts zip binary contents to a string literal.
  156. func FprintZipData(dest *bytes.Buffer, zipData []byte) {
  157. for _, b := range zipData {
  158. if b == '\n' {
  159. dest.WriteString(`\n`)
  160. continue
  161. }
  162. if b == '\\' {
  163. dest.WriteString(`\\`)
  164. continue
  165. }
  166. if b == '"' {
  167. dest.WriteString(`\"`)
  168. continue
  169. }
  170. if (b >= 32 && b <= 126) || b == '\t' {
  171. dest.WriteByte(b)
  172. continue
  173. }
  174. fmt.Fprintf(dest, "\\x%02x", b)
  175. }
  176. }
  177. // Prints out the error message and exists with a non-success signal.
  178. func exitWithError(err error) {
  179. fmt.Println(err)
  180. os.Exit(1)
  181. }