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.1KB

Rewrite logger system (#24726) ## ⚠️ Breaking The `log.<mode>.<logger>` style config has been dropped. If you used it, please check the new config manual & app.example.ini to make your instance output logs as expected. Although many legacy options still work, it's encouraged to upgrade to the new options. The SMTP logger is deleted because SMTP is not suitable to collect logs. If you have manually configured Gitea log options, please confirm the logger system works as expected after upgrading. ## Description Close #12082 and maybe more log-related issues, resolve some related FIXMEs in old code (which seems unfixable before) Just like rewriting queue #24505 : make code maintainable, clear legacy bugs, and add the ability to support more writers (eg: JSON, structured log) There is a new document (with examples): `logging-config.en-us.md` This PR is safer than the queue rewriting, because it's just for logging, it won't break other logic. ## The old problems The logging system is quite old and difficult to maintain: * Unclear concepts: Logger, NamedLogger, MultiChannelledLogger, SubLogger, EventLogger, WriterLogger etc * Some code is diffuclt to konw whether it is right: `log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs `log.DelLogger("console")` * The old system heavily depends on ini config system, it's difficult to create new logger for different purpose, and it's very fragile. * The "color" trick is difficult to use and read, many colors are unnecessary, and in the future structured log could help * It's difficult to add other log formats, eg: JSON format * The log outputer doesn't have full control of its goroutine, it's difficult to make outputer have advanced behaviors * The logs could be lost in some cases: eg: no Fatal error when using CLI. * Config options are passed by JSON, which is quite fragile. * INI package makes the KEY in `[log]` section visible in `[log.sub1]` and `[log.sub1.subA]`, this behavior is quite fragile and would cause more unclear problems, and there is no strong requirement to support `log.<mode>.<logger>` syntax. ## The new design See `logger.go` for documents. ## Screenshot <details> ![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff) ![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9) ![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee) </details> ## TODO * [x] add some new tests * [x] fix some tests * [x] test some sub-commands (manually ....) --------- Co-authored-by: Jason Song <i@wolfogre.com> Co-authored-by: delvh <dev.lh@web.de> Co-authored-by: Giteabot <teabot@gitea.io>
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cmd
  4. import (
  5. "errors"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "code.gitea.io/gitea/modules/assetfs"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/options"
  13. "code.gitea.io/gitea/modules/public"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/templates"
  16. "code.gitea.io/gitea/modules/util"
  17. "github.com/gobwas/glob"
  18. "github.com/urfave/cli"
  19. )
  20. // CmdEmbedded represents the available extract sub-command.
  21. var (
  22. CmdEmbedded = cli.Command{
  23. Name: "embedded",
  24. Usage: "Extract embedded resources",
  25. Description: "A command for extracting embedded resources, like templates and images",
  26. Subcommands: []cli.Command{
  27. subcmdList,
  28. subcmdView,
  29. subcmdExtract,
  30. },
  31. }
  32. subcmdList = cli.Command{
  33. Name: "list",
  34. Usage: "List files matching the given pattern",
  35. Action: runList,
  36. Flags: []cli.Flag{
  37. cli.BoolFlag{
  38. Name: "include-vendored,vendor",
  39. Usage: "Include files under public/vendor as well",
  40. },
  41. },
  42. }
  43. subcmdView = cli.Command{
  44. Name: "view",
  45. Usage: "View a file matching the given pattern",
  46. Action: runView,
  47. Flags: []cli.Flag{
  48. cli.BoolFlag{
  49. Name: "include-vendored,vendor",
  50. Usage: "Include files under public/vendor as well",
  51. },
  52. },
  53. }
  54. subcmdExtract = cli.Command{
  55. Name: "extract",
  56. Usage: "Extract resources",
  57. Action: runExtract,
  58. Flags: []cli.Flag{
  59. cli.BoolFlag{
  60. Name: "include-vendored,vendor",
  61. Usage: "Include files under public/vendor as well",
  62. },
  63. cli.BoolFlag{
  64. Name: "overwrite",
  65. Usage: "Overwrite files if they already exist",
  66. },
  67. cli.BoolFlag{
  68. Name: "rename",
  69. Usage: "Rename files as {name}.bak if they already exist (overwrites previous .bak)",
  70. },
  71. cli.BoolFlag{
  72. Name: "custom",
  73. Usage: "Extract to the 'custom' directory as per app.ini",
  74. },
  75. cli.StringFlag{
  76. Name: "destination,dest-dir",
  77. Usage: "Extract to the specified directory",
  78. },
  79. },
  80. }
  81. matchedAssetFiles []assetFile
  82. )
  83. type assetFile struct {
  84. fs *assetfs.LayeredFS
  85. name string
  86. path string
  87. }
  88. func initEmbeddedExtractor(c *cli.Context) error {
  89. setupConsoleLogger(log.ERROR, log.CanColorStderr, os.Stderr)
  90. patterns, err := compileCollectPatterns(c.Args())
  91. if err != nil {
  92. return err
  93. }
  94. collectAssetFilesByPattern(c, patterns, "options", options.BuiltinAssets())
  95. collectAssetFilesByPattern(c, patterns, "public", public.BuiltinAssets())
  96. collectAssetFilesByPattern(c, patterns, "templates", templates.BuiltinAssets())
  97. return nil
  98. }
  99. func runList(c *cli.Context) error {
  100. if err := runListDo(c); err != nil {
  101. fmt.Fprintf(os.Stderr, "%v\n", err)
  102. return err
  103. }
  104. return nil
  105. }
  106. func runView(c *cli.Context) error {
  107. if err := runViewDo(c); err != nil {
  108. fmt.Fprintf(os.Stderr, "%v\n", err)
  109. return err
  110. }
  111. return nil
  112. }
  113. func runExtract(c *cli.Context) error {
  114. if err := runExtractDo(c); err != nil {
  115. fmt.Fprintf(os.Stderr, "%v\n", err)
  116. return err
  117. }
  118. return nil
  119. }
  120. func runListDo(c *cli.Context) error {
  121. if err := initEmbeddedExtractor(c); err != nil {
  122. return err
  123. }
  124. for _, a := range matchedAssetFiles {
  125. fmt.Println(a.path)
  126. }
  127. return nil
  128. }
  129. func runViewDo(c *cli.Context) error {
  130. if err := initEmbeddedExtractor(c); err != nil {
  131. return err
  132. }
  133. if len(matchedAssetFiles) == 0 {
  134. return fmt.Errorf("no files matched the given pattern")
  135. } else if len(matchedAssetFiles) > 1 {
  136. return fmt.Errorf("too many files matched the given pattern, try to be more specific")
  137. }
  138. data, err := matchedAssetFiles[0].fs.ReadFile(matchedAssetFiles[0].name)
  139. if err != nil {
  140. return fmt.Errorf("%s: %w", matchedAssetFiles[0].path, err)
  141. }
  142. if _, err = os.Stdout.Write(data); err != nil {
  143. return fmt.Errorf("%s: %w", matchedAssetFiles[0].path, err)
  144. }
  145. return nil
  146. }
  147. func runExtractDo(c *cli.Context) error {
  148. if err := initEmbeddedExtractor(c); err != nil {
  149. return err
  150. }
  151. if len(c.Args()) == 0 {
  152. return fmt.Errorf("a list of pattern of files to extract is mandatory (e.g. '**' for all)")
  153. }
  154. destdir := "."
  155. if c.IsSet("destination") {
  156. destdir = c.String("destination")
  157. } else if c.Bool("custom") {
  158. destdir = setting.CustomPath
  159. fmt.Println("Using app.ini at", setting.CustomConf)
  160. }
  161. fi, err := os.Stat(destdir)
  162. if errors.Is(err, os.ErrNotExist) {
  163. // In case Windows users attempt to provide a forward-slash path
  164. wdestdir := filepath.FromSlash(destdir)
  165. if wfi, werr := os.Stat(wdestdir); werr == nil {
  166. destdir = wdestdir
  167. fi = wfi
  168. err = nil
  169. }
  170. }
  171. if err != nil {
  172. return fmt.Errorf("%s: %s", destdir, err)
  173. } else if !fi.IsDir() {
  174. return fmt.Errorf("destination %q is not a directory", destdir)
  175. }
  176. fmt.Printf("Extracting to %s:\n", destdir)
  177. overwrite := c.Bool("overwrite")
  178. rename := c.Bool("rename")
  179. for _, a := range matchedAssetFiles {
  180. if err := extractAsset(destdir, a, overwrite, rename); err != nil {
  181. // Non-fatal error
  182. fmt.Fprintf(os.Stderr, "%s: %v", a.path, err)
  183. }
  184. }
  185. return nil
  186. }
  187. func extractAsset(d string, a assetFile, overwrite, rename bool) error {
  188. dest := filepath.Join(d, filepath.FromSlash(a.path))
  189. dir := filepath.Dir(dest)
  190. data, err := a.fs.ReadFile(a.name)
  191. if err != nil {
  192. return fmt.Errorf("%s: %w", a.path, err)
  193. }
  194. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  195. return fmt.Errorf("%s: %w", dir, err)
  196. }
  197. perms := os.ModePerm & 0o666
  198. fi, err := os.Lstat(dest)
  199. if err != nil {
  200. if !errors.Is(err, os.ErrNotExist) {
  201. return fmt.Errorf("%s: %w", dest, err)
  202. }
  203. } else if !overwrite && !rename {
  204. fmt.Printf("%s already exists; skipped.\n", dest)
  205. return nil
  206. } else if !fi.Mode().IsRegular() {
  207. return fmt.Errorf("%s already exists, but it's not a regular file", dest)
  208. } else if rename {
  209. if err := util.Rename(dest, dest+".bak"); err != nil {
  210. return fmt.Errorf("error creating backup for %s: %w", dest, err)
  211. }
  212. // Attempt to respect file permissions mask (even if user:group will be set anew)
  213. perms = fi.Mode()
  214. }
  215. file, err := os.OpenFile(dest, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, perms)
  216. if err != nil {
  217. return fmt.Errorf("%s: %w", dest, err)
  218. }
  219. defer file.Close()
  220. if _, err = file.Write(data); err != nil {
  221. return fmt.Errorf("%s: %w", dest, err)
  222. }
  223. fmt.Println(dest)
  224. return nil
  225. }
  226. func collectAssetFilesByPattern(c *cli.Context, globs []glob.Glob, path string, layer *assetfs.Layer) {
  227. fs := assetfs.Layered(layer)
  228. files, err := fs.ListAllFiles(".", true)
  229. if err != nil {
  230. log.Error("Error listing files in %q: %v", path, err)
  231. return
  232. }
  233. for _, name := range files {
  234. if path == "public" &&
  235. strings.HasPrefix(name, "vendor/") &&
  236. !c.Bool("include-vendored") {
  237. continue
  238. }
  239. matchName := path + "/" + name
  240. for _, g := range globs {
  241. if g.Match(matchName) {
  242. matchedAssetFiles = append(matchedAssetFiles, assetFile{fs: fs, name: name, path: path + "/" + name})
  243. break
  244. }
  245. }
  246. }
  247. }
  248. func compileCollectPatterns(args []string) ([]glob.Glob, error) {
  249. if len(args) == 0 {
  250. args = []string{"**"}
  251. }
  252. pat := make([]glob.Glob, len(args))
  253. for i := range args {
  254. if g, err := glob.Compile(args[i], '/'); err != nil {
  255. return nil, fmt.Errorf("'%s': Invalid glob pattern: %w", args[i], err)
  256. } else { //nolint:revive
  257. pat[i] = g
  258. }
  259. }
  260. return pat, nil
  261. }