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

     1  package set
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"net/http"
     8  	"strings"
     9  
    10  	"github.com/Redstoneguy129/cli/internal/utils"
    11  	"github.com/Redstoneguy129/cli/pkg/api"
    12  	"github.com/joho/godotenv"
    13  	"github.com/spf13/afero"
    14  )
    15  
    16  func Run(ctx context.Context, envFilePath string, args []string, fsys afero.Fs) error {
    17  	// 1. Sanity checks.
    18  	{
    19  		if err := utils.AssertSupabaseCliIsSetUpFS(fsys); err != nil {
    20  			return err
    21  		}
    22  	}
    23  
    24  	// 2. Set secret(s).
    25  	{
    26  		projectRef, err := utils.LoadProjectRef(fsys)
    27  		if err != nil {
    28  			return err
    29  		}
    30  
    31  		var secrets api.CreateSecretsJSONBody
    32  		if envFilePath != "" {
    33  			envMap, err := godotenv.Read(envFilePath)
    34  			if err != nil {
    35  				return err
    36  			}
    37  			for name, value := range envMap {
    38  				secret := api.CreateSecretBody{
    39  					Name:  name,
    40  					Value: value,
    41  				}
    42  				secrets = append(secrets, secret)
    43  			}
    44  		} else if len(args) == 0 {
    45  			return errors.New("No arguments found. Use --env-file to read from a .env file.")
    46  		} else {
    47  			for _, pair := range args {
    48  				name, value, found := strings.Cut(pair, "=")
    49  				if !found {
    50  					return errors.New("Invalid secret pair: " + utils.Aqua(pair) + ". Must be NAME=VALUE.")
    51  				}
    52  
    53  				secret := api.CreateSecretBody{
    54  					Name:  name,
    55  					Value: value,
    56  				}
    57  				secrets = append(secrets, secret)
    58  			}
    59  		}
    60  
    61  		resp, err := utils.GetSupabase().CreateSecretsWithResponse(ctx, projectRef, secrets)
    62  		if err != nil {
    63  			return err
    64  		}
    65  
    66  		// TODO: remove the StatusOK case after 2022-08-20
    67  		if resp.StatusCode() != http.StatusCreated && resp.StatusCode() != http.StatusOK {
    68  			return errors.New("Unexpected error setting project secrets: " + string(resp.Body))
    69  		}
    70  	}
    71  
    72  	fmt.Println("Finished " + utils.Aqua("supabase secrets set") + ".")
    73  	return nil
    74  }