//go:build dev /* Package cmd Copyright © 2024 Shane C. */ package cmd import ( "errors" "github.com/evanw/esbuild/pkg/api" "github.com/kr/pretty" "io" "io/fs" "log" "os" "path/filepath" "strings" "github.com/spf13/cobra" ) var ignoredAssetExtensions = []string{ ".css", ".js", ".ts", } // assetsCmd represents the assets command var assetsCmd = &cobra.Command{ Use: "assets", Short: "Generates assets needed for webserver", Run: func(cmd *cobra.Command, args []string) { err := filepath.Walk("./web/assets", func(path string, info os.FileInfo, err error) error { if info.IsDir() { return nil } relPath, _ := strings.CutPrefix(path, "web/assets/") if strings.HasPrefix(relPath, "dist") { return nil } for _, ext := range ignoredAssetExtensions { if strings.HasSuffix(info.Name(), ext) { return nil } } distFolder, _ := strings.CutSuffix(relPath, info.Name()) if err := os.MkdirAll("web/assets/dist/"+distFolder, 0600); err != nil && !errors.Is(err, fs.ErrExist) { log.Fatalln(err) } copyFile(path, filepath.Join("web/assets/dist/"+distFolder, info.Name())) return nil }) if err != nil { log.Fatalln(err) } result := api.Build(api.BuildOptions{ Format: api.FormatESModule, EntryPoints: []string{"./web/assets/js/*.ts", "./web/assets/js/**/*.ts"}, Outdir: "./web/assets/dist/js", Sourcemap: api.SourceMapLinked, MinifyWhitespace: true, MinifyIdentifiers: true, MinifySyntax: true, Splitting: true, Write: true, TreeShaking: api.TreeShakingTrue, Bundle: true, }) if len(result.Errors) != 0 { pretty.Println(result.Errors) os.Exit(1) } }, } func init() { generateCmd.AddCommand(assetsCmd) } func copyFile(sourcePath, destinationPath string) { sourcePath = filepath.Clean(sourcePath) sourceFile, err := os.Open(sourcePath) if err != nil { log.Fatalln(err) } defer sourceFile.Close() destinationPath = filepath.Clean(destinationPath) destinationFile, err := os.Create(destinationPath) if err != nil { log.Fatalln(err) } defer destinationFile.Close() _, err = io.Copy(destinationFile, sourceFile) if err != nil { log.Fatalln(err) } if err := sourceFile.Close(); err != nil { log.Fatalln(err) } if err := destinationFile.Close(); err != nil { log.Fatalln(err) } }