summaryrefslogtreecommitdiffstats
path: root/cmd/embedded.go
blob: 9f03f7be7c416478d8d3befc5b94915d5630bed9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package cmd

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"code.gitea.io/gitea/modules/assetfs"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/options"
	"code.gitea.io/gitea/modules/public"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/templates"
	"code.gitea.io/gitea/modules/util"

	"github.com/gobwas/glob"
	"github.com/urfave/cli/v2"
)

// CmdEmbedded represents the available extract sub-command.
var (
	CmdEmbedded = &cli.Command{
		Name:        "embedded",
		Usage:       "Extract embedded resources",
		Description: "A command for extracting embedded resources, like templates and images",
		Subcommands: []*cli.Command{
			subcmdList,
			subcmdView,
			subcmdExtract,
		},
	}

	subcmdList = &cli.Command{
		Name:   "list",
		Usage:  "List files matching the given pattern",
		Action: runList,
		Flags: []cli.Flag{
			&cli.BoolFlag{
				Name:    "include-vendored",
				Aliases: []string{"vendor"},
				Usage:   "Include files under public/vendor as well",
			},
		},
	}

	subcmdView = &cli.Command{
		Name:   "view",
		Usage:  "View a file matching the given pattern",
		Action: runView,
		Flags: []cli.Flag{
			&cli.BoolFlag{
				Name:    "include-vendored",
				Aliases: []string{"vendor"},
				Usage:   "Include files under public/vendor as well",
			},
		},
	}

	subcmdExtract = &cli.Command{
		Name:   "extract",
		Usage:  "Extract resources",
		Action: runExtract,
		Flags: []cli.Flag{
			&cli.BoolFlag{
				Name:    "include-vendored",
				Aliases: []string{"vendor"},
				Usage:   "Include files under public/vendor as well",
			},
			&cli.BoolFlag{
				Name:  "overwrite",
				Usage: "Overwrite files if they already exist",
			},
			&cli.BoolFlag{
				Name:  "rename",
				Usage: "Rename files as {name}.bak if they already exist (overwrites previous .bak)",
			},
			&cli.BoolFlag{
				Name:  "custom",
				Usage: "Extract to the 'custom' directory as per app.ini",
			},
			&cli.StringFlag{
				Name:    "destination",
				Aliases: []string{"dest-dir"},
				Usage:   "Extract to the specified directory",
			},
		},
	}

	matchedAssetFiles []assetFile
)

type assetFile struct {
	fs   *assetfs.LayeredFS
	name string
	path string
}

func initEmbeddedExtractor(c *cli.Context) error {
	setupConsoleLogger(log.ERROR, log.CanColorStderr, os.Stderr)

	patterns, err := compileCollectPatterns(c.Args().Slice())
	if err != nil {
		return err
	}

	collectAssetFilesByPattern(c, patterns, "options", options.BuiltinAssets())
	collectAssetFilesByPattern(c, patterns, "public", public.BuiltinAssets())
	collectAssetFilesByPattern(c, patterns, "templates", templates.BuiltinAssets())

	return nil
}

func runList(c *cli.Context) error {
	if err := runListDo(c); err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return err
	}
	return nil
}

func runView(c *cli.Context) error {
	if err := runViewDo(c); err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return err
	}
	return nil
}

func runExtract(c *cli.Context) error {
	if err := runExtractDo(c); err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return err
	}
	return nil
}

func runListDo(c *cli.Context) error {
	if err := initEmbeddedExtractor(c); err != nil {
		return err
	}

	for _, a := range matchedAssetFiles {
		fmt.Println(a.path)
	}

	return nil
}

func runViewDo(c *cli.Context) error {
	if err := initEmbeddedExtractor(c); err != nil {
		return err
	}

	if len(matchedAssetFiles) == 0 {
		return errors.New("no files matched the given pattern")
	} else if len(matchedAssetFiles) > 1 {
		return errors.New("too many files matched the given pattern, try to be more specific")
	}

	data, err := matchedAssetFiles[0].fs.ReadFile(matchedAssetFiles[0].name)
	if err != nil {
		return fmt.Errorf("%s: %w", matchedAssetFiles[0].path, err)
	}

	if _, err = os.Stdout.Write(data); err != nil {
		return fmt.Errorf("%s: %w", matchedAssetFiles[0].path, err)
	}

	return nil
}

func runExtractDo(c *cli.Context) error {
	if err := initEmbeddedExtractor(c); err != nil {
		return err
	}

	if c.NArg() == 0 {
		return errors.New("a list of pattern of files to extract is mandatory (e.g. '**' for all)")
	}

	destdir := "."

	if c.IsSet("destination") {
		destdir = c.String("destination")
	} else if c.Bool("custom") {
		destdir = setting.CustomPath
		fmt.Println("Using app.ini at", setting.CustomConf)
	}

	fi, err := os.Stat(destdir)
	if errors.Is(err, os.ErrNotExist) {
		// In case Windows users attempt to provide a forward-slash path
		wdestdir := filepath.FromSlash(destdir)
		if wfi, werr := os.Stat(wdestdir); werr == nil {
			destdir = wdestdir
			fi = wfi
			err = nil
		}
	}
	if err != nil {
		return fmt.Errorf("%s: %s", destdir, err)
	} else if !fi.IsDir() {
		return fmt.Errorf("destination %q is not a directory", destdir)
	}

	fmt.Printf("Extracting to %s:\n", destdir)

	overwrite := c.Bool("overwrite")
	rename := c.Bool("rename")

	for _, a := range matchedAssetFiles {
		if err := extractAsset(destdir, a, overwrite, rename); err != nil {
			// Non-fatal error
			fmt.Fprintf(os.Stderr, "%s: %v", a.path, err)
		}
	}

	return nil
}

func extractAsset(d string, a assetFile, overwrite, rename bool) error {
	dest := filepath.Join(d, filepath.FromSlash(a.path))
	dir := filepath.Dir(dest)

	data, err := a.fs.ReadFile(a.name)
	if err != nil {
		return fmt.Errorf("%s: %w", a.path, err)
	}

	if err := os.MkdirAll(dir, os.ModePerm); err != nil {
		return fmt.Errorf("%s: %w", dir, err)
	}

	perms := os.ModePerm & 0o666

	fi, err := os.Lstat(dest)
	if err != nil {
		if !errors.Is(err, os.ErrNotExist) {
			return fmt.Errorf("%s: %w", dest, err)
		}
	} else if !overwrite && !rename {
		fmt.Printf("%s already exists; skipped.\n", dest)
		return nil
	} else if !fi.Mode().IsRegular() {
		return fmt.Errorf("%s already exists, but it's not a regular file", dest)
	} else if rename {
		if err := util.Rename(dest, dest+".bak"); err != nil {
			return fmt.Errorf("error creating backup for %s: %w", dest, err)
		}
		// Attempt to respect file permissions mask (even if user:group will be set anew)
		perms = fi.Mode()
	}

	file, err := os.OpenFile(dest, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, perms)
	if err != nil {
		return fmt.Errorf("%s: %w", dest, err)
	}
	defer file.Close()

	if _, err = file.Write(data); err != nil {
		return fmt.Errorf("%s: %w", dest, err)
	}

	fmt.Println(dest)

	return nil
}

func collectAssetFilesByPattern(c *cli.Context, globs []glob.Glob, path string, layer *assetfs.Layer) {
	fs := assetfs.Layered(layer)
	files, err := fs.ListAllFiles(".", true)
	if err != nil {
		log.Error("Error listing files in %q: %v", path, err)
		return
	}
	for _, name := range files {
		if path == "public" &&
			strings.HasPrefix(name, "vendor/") &&
			!c.Bool("include-vendored") {
			continue
		}
		matchName := path + "/" + name
		for _, g := range globs {
			if g.Match(matchName) {
				matchedAssetFiles = append(matchedAssetFiles, assetFile{fs: fs, name: name, path: path + "/" + name})
				break
			}
		}
	}
}

func compileCollectPatterns(args []string) ([]glob.Glob, error) {
	if len(args) == 0 {
		args = []string{"**"}
	}
	pat := make([]glob.Glob, len(args))
	for i := range args {
		if g, err := glob.Compile(args[i], '/'); err != nil {
			return nil, fmt.Errorf("'%s': Invalid glob pattern: %w", args[i], err)
		} else { //nolint:revive
			pat[i] = g
		}
	}
	return pat, nil
}