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. package cmd
  6. import (
  7. "errors"
  8. "fmt"
  9. "os"
  10. "path/filepath"
  11. "sort"
  12. "strings"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/options"
  15. "code.gitea.io/gitea/modules/public"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/templates"
  18. "code.gitea.io/gitea/modules/util"
  19. "github.com/gobwas/glob"
  20. "github.com/urfave/cli"
  21. )
  22. // Cmdembedded represents the available extract sub-command.
  23. var (
  24. Cmdembedded = cli.Command{
  25. Name: "embedded",
  26. Usage: "Extract embedded resources",
  27. Description: "A command for extracting embedded resources, like templates and images",
  28. Subcommands: []cli.Command{
  29. subcmdList,
  30. subcmdView,
  31. subcmdExtract,
  32. },
  33. }
  34. subcmdList = cli.Command{
  35. Name: "list",
  36. Usage: "List files matching the given pattern",
  37. Action: runList,
  38. Flags: []cli.Flag{
  39. cli.BoolFlag{
  40. Name: "include-vendored,vendor",
  41. Usage: "Include files under public/vendor as well",
  42. },
  43. },
  44. }
  45. subcmdView = cli.Command{
  46. Name: "view",
  47. Usage: "View a file matching the given pattern",
  48. Action: runView,
  49. Flags: []cli.Flag{
  50. cli.BoolFlag{
  51. Name: "include-vendored,vendor",
  52. Usage: "Include files under public/vendor as well",
  53. },
  54. },
  55. }
  56. subcmdExtract = cli.Command{
  57. Name: "extract",
  58. Usage: "Extract resources",
  59. Action: runExtract,
  60. Flags: []cli.Flag{
  61. cli.BoolFlag{
  62. Name: "include-vendored,vendor",
  63. Usage: "Include files under public/vendor as well",
  64. },
  65. cli.BoolFlag{
  66. Name: "overwrite",
  67. Usage: "Overwrite files if they already exist",
  68. },
  69. cli.BoolFlag{
  70. Name: "rename",
  71. Usage: "Rename files as {name}.bak if they already exist (overwrites previous .bak)",
  72. },
  73. cli.BoolFlag{
  74. Name: "custom",
  75. Usage: "Extract to the 'custom' directory as per app.ini",
  76. },
  77. cli.StringFlag{
  78. Name: "destination,dest-dir",
  79. Usage: "Extract to the specified directory",
  80. },
  81. },
  82. }
  83. sections map[string]*section
  84. assets []asset
  85. )
  86. type section struct {
  87. Path string
  88. Names func() []string
  89. IsDir func(string) (bool, error)
  90. Asset func(string) ([]byte, error)
  91. }
  92. type asset struct {
  93. Section *section
  94. Name string
  95. Path string
  96. }
  97. func initEmbeddedExtractor(c *cli.Context) error {
  98. // Silence the console logger
  99. log.DelNamedLogger("console")
  100. log.DelNamedLogger(log.DEFAULT)
  101. // Read configuration file
  102. setting.LoadAllowEmpty()
  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.AssetNames, IsDir: templates.AssetIsDir, Asset: templates.Asset}
  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: %v", assets[0].Path, err)
  162. }
  163. if _, err = os.Stdout.Write(data); err != nil {
  164. return fmt.Errorf("%s: %v", 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: %v", a.Path, err)
  214. }
  215. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  216. return fmt.Errorf("%s: %v", 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: %v", 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: %v", 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: %v", dest, err)
  239. }
  240. defer file.Close()
  241. if _, err = file.Write(data); err != nil {
  242. return fmt.Errorf("%s: %v", 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: %v", args[i], err)
  279. } else {
  280. pat[i] = g
  281. }
  282. }
  283. return pat, nil
  284. }