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