github.com/jcarley/cli@v0.0.0-20180201210820-966d90434c30/commands/git/add.go (about)

     1  package git
     2  
     3  import (
     4  	"fmt"
     5  	"os/exec"
     6  
     7  	"github.com/Sirupsen/logrus"
     8  	"github.com/daticahealth/cli/commands/services"
     9  )
    10  
    11  func CmdAdd(svcName, remote string, force bool, ig IGit, is services.IServices) error {
    12  	service, err := is.RetrieveByLabel(svcName)
    13  	if err != nil {
    14  		return err
    15  	}
    16  	if service == nil {
    17  		return fmt.Errorf("Could not find a service with the label \"%s\". You can list services with the \"datica services list\" command.", svcName)
    18  	}
    19  	if service.Source == "" {
    20  		return fmt.Errorf("No git remote found for the \"%s\" service.", svcName)
    21  	}
    22  	remotes, err := ig.List()
    23  	if err != nil {
    24  		return err
    25  	}
    26  	exists := false
    27  	for _, r := range remotes {
    28  		if r == remote {
    29  			exists = true
    30  			break
    31  		}
    32  	}
    33  	if exists && !force {
    34  		return fmt.Errorf("A git remote named \"%s\" already exists, please specify --force to overwrite it or use the -r (remote) option to name a different git remote", remote)
    35  	} else if exists {
    36  		err = ig.SetURL(remote, service.Source)
    37  		if err != nil {
    38  			return fmt.Errorf("Failed to update existing git remote: %s", err)
    39  		}
    40  	} else {
    41  		err = ig.Add(remote, service.Source)
    42  		if err != nil {
    43  			return fmt.Errorf("Failed to add a git remote: %s", err)
    44  		}
    45  	}
    46  	logrus.Printf("\"%s\" remote added.", remote)
    47  	return nil
    48  }
    49  
    50  // Add a git remote to a git repo in the current working directory. If the
    51  // current working directory is not yet a git repo, this command will fail.
    52  func (g *SGit) Add(remote, gitURL string) error {
    53  	_, err := exec.Command("git", "remote", "add", remote, gitURL).Output()
    54  	return err
    55  }
    56  
    57  // SetURL updates the remove URL for a given git repo.
    58  func (g *SGit) SetURL(remote, gitURL string) error {
    59  	_, err := exec.Command("git", "remote", "set-url", remote, gitURL).Output()
    60  	return err
    61  }