github.com/henvic/wedeploycli@v1.7.6-0.20200319005353-3630f582f284/command/deploy/internal/getproject/getproject.go (about)

     1  package getproject
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"net/http"
     8  
     9  	"github.com/henvic/wedeploycli/apihelper"
    10  	"github.com/henvic/wedeploycli/color"
    11  	"github.com/henvic/wedeploycli/command/canceled"
    12  	"github.com/henvic/wedeploycli/command/internal/we"
    13  	"github.com/henvic/wedeploycli/fancy"
    14  	"github.com/henvic/wedeploycli/isterm"
    15  	"github.com/henvic/wedeploycli/projects"
    16  )
    17  
    18  // MaybeID tries to get a project ID for using on deployment
    19  func MaybeID(maybe, region string) (projectID string, err error) {
    20  	projectsClient := projects.New(we.Context())
    21  	projectID = maybe
    22  
    23  	if projectID == "" {
    24  		if !isterm.Check() {
    25  			return projectID, errors.New("project ID is missing")
    26  		}
    27  
    28  		fmt.Println(fancy.Question("Choose a project ID") + " " + fancy.Tip("default: random"))
    29  		projectID, err = fancy.Prompt()
    30  
    31  		if err != nil {
    32  			return projectID, err
    33  		}
    34  	}
    35  
    36  	if projectID != "" {
    37  		userProject, err := projectsClient.Get(context.Background(), projectID)
    38  
    39  		if err == nil {
    40  			if region == "" || region == userProject.Region {
    41  				return projectID, nil
    42  			}
    43  
    44  			return "", errors.New("cannot change region of existing project")
    45  		}
    46  
    47  		if epf, ok := err.(apihelper.APIFault); !ok || epf.Status != http.StatusNotFound {
    48  			return "", err
    49  		}
    50  
    51  		if err := confirmation(projectID, userProject); err != nil {
    52  			return "", err
    53  		}
    54  	}
    55  
    56  	p, ep := projectsClient.Create(context.Background(), projects.Project{
    57  		ProjectID: projectID,
    58  		Region:    region,
    59  	})
    60  
    61  	return p.ProjectID, ep
    62  }
    63  
    64  func confirmation(projectID string, userProject projects.Project) error {
    65  	if userProject.ProjectID != "" {
    66  		return nil
    67  	}
    68  
    69  	var question = fmt.Sprintf("No project found. %s project \"%s\" and %s the deployment?",
    70  		color.Format(color.FgMagenta, color.Bold, "Create"),
    71  		color.Format(color.FgHiBlack, projectID),
    72  		color.Format(color.FgMagenta, color.Bold, "continue"))
    73  
    74  	switch ok, askErr := fancy.Boolean(question); {
    75  	case askErr != nil:
    76  		return askErr
    77  	case ok:
    78  		fmt.Println("")
    79  		return nil
    80  	}
    81  
    82  	return canceled.CancelCommand("deployment canceled")
    83  }