github.com/Redstoneguy129/cli@v0.0.0-20230211220159-15dca4e91917/internal/functions/new/new.go (about)

     1  package new
     2  
     3  import (
     4  	"context"
     5  	_ "embed"
     6  	"errors"
     7  	"fmt"
     8  	"os"
     9  	"path/filepath"
    10  
    11  	"github.com/spf13/afero"
    12  	"github.com/Redstoneguy129/cli/internal/utils"
    13  )
    14  
    15  var (
    16  	//go:embed templates/index.ts
    17  	index string
    18  )
    19  
    20  func Run(ctx context.Context, slug string, fsys afero.Fs) error {
    21  	// 1. Sanity checks.
    22  	funcDir := filepath.Join(utils.FunctionsDir, slug)
    23  	{
    24  		if err := utils.ValidateFunctionSlug(slug); err != nil {
    25  			return err
    26  		}
    27  		if _, err := fsys.Stat(funcDir); !errors.Is(err, os.ErrNotExist) {
    28  			return errors.New("Function " + utils.Aqua(slug) + " already exists locally.")
    29  		}
    30  	}
    31  
    32  	// 2. Create new function.
    33  	{
    34  		if err := utils.MkdirIfNotExistFS(fsys, funcDir); err != nil {
    35  			return err
    36  		}
    37  		if err := afero.WriteFile(fsys, filepath.Join(funcDir, "index.ts"), []byte(index), 0644); err != nil {
    38  			return err
    39  		}
    40  	}
    41  
    42  	fmt.Println("Created new Function at " + utils.Bold(funcDir))
    43  	return nil
    44  }