github.com/henvic/wedeploycli@v1.7.6-0.20200319005353-3630f582f284/deployment/internal/groupuid/groupuid.go (about)

     1  package groupuid
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"errors"
     7  	"fmt"
     8  	"strings"
     9  
    10  	"github.com/hashicorp/errwrap"
    11  	"github.com/henvic/wedeploycli/apihelper"
    12  )
    13  
    14  var (
    15  	gitRemoteMessagePrefix     = "remote: " // git client prepends this when printing messages
    16  	gitRemoteDeployPrefix      = "wedeploy="
    17  	gitRemoteDeployErrorPrefix = "wedeployError="
    18  )
    19  
    20  // Extract group uid from remote message.
    21  func Extract(s string) (string, error) {
    22  	lines := strings.Split(s, "\n")
    23  
    24  	for _, line := range lines {
    25  		line = strings.TrimPrefix(line, gitRemoteMessagePrefix)
    26  
    27  		if strings.HasPrefix(line, gitRemoteDeployPrefix) {
    28  			// \x1b[K is showing up at the end of "remote: wedeploy=" on at least git 1.9
    29  			line = strings.TrimSuffix(line, "\x1b[K\n")
    30  			return extractGroupUIDFromBuild([]byte(strings.TrimPrefix(line, gitRemoteDeployPrefix)))
    31  		}
    32  
    33  		if strings.HasPrefix(line, gitRemoteDeployErrorPrefix) {
    34  			return "", extractErrorFromBuild([]byte(strings.TrimPrefix(line, gitRemoteDeployErrorPrefix)))
    35  		}
    36  	}
    37  
    38  	return "", errors.New("can't find deployment group UID response")
    39  }
    40  
    41  func extractErrorFromBuild(e []byte) error {
    42  	var af apihelper.APIFault
    43  	if errJSON := json.Unmarshal(e, &af); errJSON != nil {
    44  		return fmt.Errorf(`can't process error message: "%s"`, bytes.TrimSpace(e))
    45  	}
    46  
    47  	return af
    48  }
    49  
    50  type buildDeploymentOnGitServer struct {
    51  	GroupUID string `json:"groupUid"`
    52  }
    53  
    54  func extractGroupUIDFromBuild(e []byte) (groupUID string, err error) {
    55  	var bds []buildDeploymentOnGitServer
    56  
    57  	if errJSON := json.Unmarshal(e, &bds); errJSON != nil {
    58  		return "", errwrap.Wrapf("deployment response is invalid: {{err}}", errJSON)
    59  	}
    60  
    61  	if len(bds) == 0 {
    62  		return "", errors.New("found no build during deployment")
    63  	}
    64  
    65  	return bds[0].GroupUID, nil
    66  }