github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/secret/shared/shared.go (about)

     1  package shared
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/ungtb10d/cli/v2/internal/text"
     9  )
    10  
    11  type Visibility string
    12  
    13  const (
    14  	All      = "all"
    15  	Private  = "private"
    16  	Selected = "selected"
    17  )
    18  
    19  type App string
    20  
    21  const (
    22  	Actions    = "actions"
    23  	Codespaces = "codespaces"
    24  	Dependabot = "dependabot"
    25  	Unknown    = "unknown"
    26  )
    27  
    28  func (app App) String() string {
    29  	return string(app)
    30  }
    31  
    32  func (app App) Title() string {
    33  	return text.Title(app.String())
    34  }
    35  
    36  type SecretEntity string
    37  
    38  const (
    39  	Repository   = "repository"
    40  	Organization = "organization"
    41  	User         = "user"
    42  	Environment  = "environment"
    43  )
    44  
    45  func GetSecretEntity(orgName, envName string, userSecrets bool) (SecretEntity, error) {
    46  	orgSet := orgName != ""
    47  	envSet := envName != ""
    48  
    49  	if orgSet && envSet || orgSet && userSecrets || envSet && userSecrets {
    50  		return "", errors.New("cannot specify multiple secret entities")
    51  	}
    52  
    53  	if orgSet {
    54  		return Organization, nil
    55  	}
    56  	if envSet {
    57  		return Environment, nil
    58  	}
    59  	if userSecrets {
    60  		return User, nil
    61  	}
    62  	return Repository, nil
    63  }
    64  
    65  func GetSecretApp(app string, entity SecretEntity) (App, error) {
    66  	switch strings.ToLower(app) {
    67  	case Actions:
    68  		return Actions, nil
    69  	case Codespaces:
    70  		return Codespaces, nil
    71  	case Dependabot:
    72  		return Dependabot, nil
    73  	case "":
    74  		if entity == User {
    75  			return Codespaces, nil
    76  		}
    77  		return Actions, nil
    78  	default:
    79  		return Unknown, fmt.Errorf("invalid application: %s", app)
    80  	}
    81  }
    82  
    83  func IsSupportedSecretEntity(app App, entity SecretEntity) bool {
    84  	switch app {
    85  	case Actions:
    86  		return entity == Repository || entity == Organization || entity == Environment
    87  	case Codespaces:
    88  		return entity == User || entity == Organization || entity == Repository
    89  	case Dependabot:
    90  		return entity == Repository || entity == Organization
    91  	default:
    92  		return false
    93  	}
    94  }