github.com/supabase/cli@v1.168.1/internal/functions/new/new.go (about) 1 package new 2 3 import ( 4 "context" 5 _ "embed" 6 "fmt" 7 "html/template" 8 "os" 9 "path/filepath" 10 11 "github.com/go-errors/errors" 12 "github.com/spf13/afero" 13 "github.com/supabase/cli/internal/utils" 14 ) 15 16 var ( 17 //go:embed templates/index.ts 18 indexEmbed string 19 indexTemplate = template.Must(template.New("indexl").Parse(indexEmbed)) 20 ) 21 22 type indexConfig struct { 23 Port uint16 24 Slug string 25 Token string 26 } 27 28 func Run(ctx context.Context, slug string, fsys afero.Fs) error { 29 // 1. Sanity checks. 30 funcDir := filepath.Join(utils.FunctionsDir, slug) 31 { 32 if err := utils.ValidateFunctionSlug(slug); err != nil { 33 return err 34 } 35 } 36 37 // 2. Create new function. 38 { 39 if err := utils.MkdirIfNotExistFS(fsys, funcDir); err != nil { 40 return err 41 } 42 path := filepath.Join(funcDir, "index.ts") 43 f, err := fsys.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644) 44 if err != nil { 45 return errors.Errorf("failed to create function entrypoint: %w", err) 46 } 47 defer f.Close() 48 // Templatize index.ts by config.toml if available 49 utils.Config.Api.Port = 54321 50 if err := utils.LoadConfigFS(fsys); err != nil { 51 utils.CmdSuggestion = "" 52 } 53 config := indexConfig{ 54 Port: utils.Config.Api.Port, 55 Slug: slug, 56 Token: utils.Config.Auth.AnonKey, 57 } 58 if err := indexTemplate.Execute(f, config); err != nil { 59 return errors.Errorf("failed to initialise function entrypoint: %w", err) 60 } 61 } 62 63 fmt.Println("Created new Function at " + utils.Bold(funcDir)) 64 return nil 65 }