You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

embedded.go 7.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. //go:build bindata
  5. // +build bindata
  6. package cmd
  7. import (
  8. "errors"
  9. "fmt"
  10. "os"
  11. "path/filepath"
  12. "sort"
  13. "strings"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/options"
  16. "code.gitea.io/gitea/modules/public"
  17. "code.gitea.io/gitea/modules/setting"
  18. "code.gitea.io/gitea/modules/templates"
  19. "code.gitea.io/gitea/modules/util"
  20. "github.com/gobwas/glob"
  21. "github.com/urfave/cli"
  22. )
  23. // Cmdembedded represents the available extract sub-command.
  24. var (
  25. Cmdembedded = cli.Command{
  26. Name: "embedded",
  27. Usage: "Extract embedded resources",
  28. Description: "A command for extracting embedded resources, like templates and images",
  29. Subcommands: []cli.Command{
  30. subcmdList,
  31. subcmdView,
  32. subcmdExtract,
  33. },
  34. }
  35. subcmdList = cli.Command{
  36. Name: "list",
  37. Usage: "List files matching the given pattern",
  38. Action: runList,
  39. Flags: []cli.Flag{
  40. cli.BoolFlag{
  41. Name: "include-vendored,vendor",
  42. Usage: "Include files under public/vendor as well",
  43. },
  44. },
  45. }
  46. subcmdView = cli.Command{
  47. Name: "view",
  48. Usage: "View a file matching the given pattern",
  49. Action: runView,
  50. Flags: []cli.Flag{
  51. cli.BoolFlag{
  52. Name: "include-vendored,vendor",
  53. Usage: "Include files under public/vendor as well",
  54. },
  55. },
  56. }
  57. subcmdExtract = cli.Command{
  58. Name: "extract",
  59. Usage: "Extract resources",
  60. Action: runExtract,
  61. Flags: []cli.Flag{
  62. cli.BoolFlag{
  63. Name: "include-vendored,vendor",
  64. Usage: "Include files under public/vendor as well",
  65. },
  66. cli.BoolFlag{
  67. Name: "overwrite",
  68. Usage: "Overwrite files if they already exist",
  69. },
  70. cli.BoolFlag{
  71. Name: "rename",
  72. Usage: "Rename files as {name}.bak if they already exist (overwrites previous .bak)",
  73. },
  74. cli.BoolFlag{
  75. Name: "custom",
  76. Usage: "Extract to the 'custom' directory as per app.ini",
  77. },
  78. cli.StringFlag{
  79. Name: "destination,dest-dir",
  80. Usage: "Extract to the specified directory",
  81. },
  82. },
  83. }
  84. sections map[string]*section
  85. assets []asset
  86. )
  87. type section struct {
  88. Path string
  89. Names func() []string
  90. IsDir func(string) (bool, error)
  91. Asset func(string) ([]byte, error)
  92. }
  93. type asset struct {
  94. Section *section
  95. Name string
  96. Path string
  97. }
  98. func initEmbeddedExtractor(c *cli.Context) error {
  99. // Silence the console logger
  100. log.DelNamedLogger("console")
  101. log.DelNamedLogger(log.DEFAULT)
  102. // Read configuration file
  103. setting.LoadAllowEmpty()
  104. pats, err := getPatterns(c.Args())
  105. if err != nil {
  106. return err
  107. }
  108. sections := make(map[string]*section, 3)
  109. sections["public"] = &section{Path: "public", Names: public.AssetNames, IsDir: public.AssetIsDir, Asset: public.Asset}
  110. sections["options"] = &section{Path: "options", Names: options.AssetNames, IsDir: options.AssetIsDir, Asset: options.Asset}
  111. sections["templates"] = &section{Path: "templates", Names: templates.AssetNames, IsDir: templates.AssetIsDir, Asset: templates.Asset}
  112. for _, sec := range sections {
  113. assets = append(assets, buildAssetList(sec, pats, c)...)
  114. }
  115. // Sort assets
  116. sort.SliceStable(assets, func(i, j int) bool {
  117. return assets[i].Path < assets[j].Path
  118. })
  119. return nil
  120. }
  121. func runList(c *cli.Context) error {
  122. if err := runListDo(c); err != nil {
  123. fmt.Fprintf(os.Stderr, "%v\n", err)
  124. return err
  125. }
  126. return nil
  127. }
  128. func runView(c *cli.Context) error {
  129. if err := runViewDo(c); err != nil {
  130. fmt.Fprintf(os.Stderr, "%v\n", err)
  131. return err
  132. }
  133. return nil
  134. }
  135. func runExtract(c *cli.Context) error {
  136. if err := runExtractDo(c); err != nil {
  137. fmt.Fprintf(os.Stderr, "%v\n", err)
  138. return err
  139. }
  140. return nil
  141. }
  142. func runListDo(c *cli.Context) error {
  143. if err := initEmbeddedExtractor(c); err != nil {
  144. return err
  145. }
  146. for _, a := range assets {
  147. fmt.Println(a.Path)
  148. }
  149. return nil
  150. }
  151. func runViewDo(c *cli.Context) error {
  152. if err := initEmbeddedExtractor(c); err != nil {
  153. return err
  154. }
  155. if len(assets) == 0 {
  156. return fmt.Errorf("No files matched the given pattern")
  157. } else if len(assets) > 1 {
  158. return fmt.Errorf("Too many files matched the given pattern; try to be more specific")
  159. }
  160. data, err := assets[0].Section.Asset(assets[0].Name)
  161. if err != nil {
  162. return fmt.Errorf("%s: %v", assets[0].Path, err)
  163. }
  164. if _, err = os.Stdout.Write(data); err != nil {
  165. return fmt.Errorf("%s: %v", assets[0].Path, err)
  166. }
  167. return nil
  168. }
  169. func runExtractDo(c *cli.Context) error {
  170. if err := initEmbeddedExtractor(c); err != nil {
  171. return err
  172. }
  173. if len(c.Args()) == 0 {
  174. return fmt.Errorf("A list of pattern of files to extract is mandatory (e.g. '**' for all)")
  175. }
  176. destdir := "."
  177. if c.IsSet("destination") {
  178. destdir = c.String("destination")
  179. } else if c.Bool("custom") {
  180. destdir = setting.CustomPath
  181. fmt.Println("Using app.ini at", setting.CustomConf)
  182. }
  183. fi, err := os.Stat(destdir)
  184. if errors.Is(err, os.ErrNotExist) {
  185. // In case Windows users attempt to provide a forward-slash path
  186. wdestdir := filepath.FromSlash(destdir)
  187. if wfi, werr := os.Stat(wdestdir); werr == nil {
  188. destdir = wdestdir
  189. fi = wfi
  190. err = nil
  191. }
  192. }
  193. if err != nil {
  194. return fmt.Errorf("%s: %s", destdir, err)
  195. } else if !fi.IsDir() {
  196. return fmt.Errorf("%s is not a directory.", destdir)
  197. }
  198. fmt.Printf("Extracting to %s:\n", destdir)
  199. overwrite := c.Bool("overwrite")
  200. rename := c.Bool("rename")
  201. for _, a := range assets {
  202. if err := extractAsset(destdir, a, overwrite, rename); err != nil {
  203. // Non-fatal error
  204. fmt.Fprintf(os.Stderr, "%s: %v", a.Path, err)
  205. }
  206. }
  207. return nil
  208. }
  209. func extractAsset(d string, a asset, overwrite, rename bool) error {
  210. dest := filepath.Join(d, filepath.FromSlash(a.Path))
  211. dir := filepath.Dir(dest)
  212. data, err := a.Section.Asset(a.Name)
  213. if err != nil {
  214. return fmt.Errorf("%s: %v", a.Path, err)
  215. }
  216. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  217. return fmt.Errorf("%s: %v", dir, err)
  218. }
  219. perms := os.ModePerm & 0666
  220. fi, err := os.Lstat(dest)
  221. if err != nil {
  222. if !errors.Is(err, os.ErrNotExist) {
  223. return fmt.Errorf("%s: %v", dest, err)
  224. }
  225. } else if !overwrite && !rename {
  226. fmt.Printf("%s already exists; skipped.\n", dest)
  227. return nil
  228. } else if !fi.Mode().IsRegular() {
  229. return fmt.Errorf("%s already exists, but it's not a regular file", dest)
  230. } else if rename {
  231. if err := util.Rename(dest, dest+".bak"); err != nil {
  232. return fmt.Errorf("Error creating backup for %s: %v", dest, err)
  233. }
  234. // Attempt to respect file permissions mask (even if user:group will be set anew)
  235. perms = fi.Mode()
  236. }
  237. file, err := os.OpenFile(dest, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, perms)
  238. if err != nil {
  239. return fmt.Errorf("%s: %v", dest, err)
  240. }
  241. defer file.Close()
  242. if _, err = file.Write(data); err != nil {
  243. return fmt.Errorf("%s: %v", dest, err)
  244. }
  245. fmt.Println(dest)
  246. return nil
  247. }
  248. func buildAssetList(sec *section, globs []glob.Glob, c *cli.Context) []asset {
  249. var results = make([]asset, 0, 64)
  250. for _, name := range sec.Names() {
  251. if isdir, err := sec.IsDir(name); !isdir && err == nil {
  252. if sec.Path == "public" &&
  253. strings.HasPrefix(name, "vendor/") &&
  254. !c.Bool("include-vendored") {
  255. continue
  256. }
  257. matchName := sec.Path + "/" + name
  258. for _, g := range globs {
  259. if g.Match(matchName) {
  260. results = append(results, asset{Section: sec,
  261. Name: name,
  262. Path: sec.Path + "/" + name})
  263. break
  264. }
  265. }
  266. }
  267. }
  268. return results
  269. }
  270. func getPatterns(args []string) ([]glob.Glob, error) {
  271. if len(args) == 0 {
  272. args = []string{"**"}
  273. }
  274. pat := make([]glob.Glob, len(args))
  275. for i := range args {
  276. if g, err := glob.Compile(args[i], '/'); err != nil {
  277. return nil, fmt.Errorf("'%s': Invalid glob pattern: %v", args[i], err)
  278. } else {
  279. pat[i] = g
  280. }
  281. }
  282. return pat, nil
  283. }