github.com/jfrog/jfrog-cli-core/v2@v2.52.0/general/utils.go (about)

     1  package general
     2  
     3  import (
     4  	"github.com/jfrog/jfrog-cli-core/v2/common/commands"
     5  	"github.com/jfrog/jfrog-cli-core/v2/utils/config"
     6  	"github.com/jfrog/jfrog-client-go/utils/errorutils"
     7  	"net"
     8  	"net/url"
     9  	"strings"
    10  )
    11  
    12  const defaultServerId = "default-server"
    13  
    14  // Deduce the server ID from the URL and add server details to config.
    15  func ConfigServerWithDeducedId(server *config.ServerDetails, interactive, webLogin bool) error {
    16  	serverId, err := deduceServerId(server.Url)
    17  	if err != nil {
    18  		return err
    19  	}
    20  	return ConfigServerAsDefault(server, serverId, interactive, webLogin)
    21  }
    22  
    23  func deduceServerId(platformUrl string) (string, error) {
    24  	u, err := url.Parse(platformUrl)
    25  	if errorutils.CheckError(err) != nil {
    26  		return "", err
    27  	}
    28  
    29  	// If the host is an IP address, use a default server ID.
    30  	serverId := defaultServerId
    31  	if net.ParseIP(u.Hostname()) == nil {
    32  		// Otherwise, take the server name from host name: https://myjfrog.jfrog.com/ -> myjfrog
    33  		serverId = strings.Split(u.Hostname(), ".")[0]
    34  	}
    35  	return serverId, nil
    36  }
    37  
    38  // Add the given server details to the CLI's config by running a 'jf config' command, and make it the default server.
    39  func ConfigServerAsDefault(server *config.ServerDetails, serverId string, interactive, webLogin bool) error {
    40  	return commands.NewConfigCommand(commands.AddOrEdit, serverId).
    41  		SetInteractive(interactive).SetUseWebLogin(webLogin).
    42  		SetDetails(server).SetMakeDefault(true).Run()
    43  }