github.com/driusan/dgit@v0.0.0-20221118233547-f39f0c15edbb/git/push.go (about)

     1  package git
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  )
     7  
     8  type PushOptions struct {
     9  	SendPackOptions
    10  
    11  	SetUpstream bool
    12  }
    13  
    14  func Push(c *Client, opts PushOptions, r Remote, refs []Refname) error {
    15  	if len(refs) < 1 {
    16  		// The cmd package should have validated this or
    17  		// provided the defaults otherwise
    18  		return fmt.Errorf("Must specify refnames to push")
    19  	}
    20  	if r == "" {
    21  		return fmt.Errorf("Must specify remote to push to")
    22  	}
    23  	remoteurl, err := r.PushURL(c)
    24  	if err != nil {
    25  		return err
    26  	}
    27  	if remoteurl == "" {
    28  		return fmt.Errorf("Could not determine URL for %v", r)
    29  	}
    30  
    31  	var sendrefs []Refname
    32  	var config GitConfig
    33  	if opts.SetUpstream {
    34  		// Only bother parsing the config file if we're going
    35  		// to modify it
    36  		config, err = LoadLocalConfig(c)
    37  		if err != nil {
    38  			return err
    39  		}
    40  	}
    41  	for _, ref := range refs {
    42  		// Convert from the name given on the command line
    43  		// to the remote ref in the config
    44  		// Use the part after the ':' if specified
    45  		name := string(ref.RemoteName())
    46  
    47  		var merge string
    48  		if opts.SetUpstream {
    49  			config.SetConfig(
    50  				fmt.Sprintf("branch.%v.remote", name),
    51  				r.String(),
    52  			)
    53  			merge = "refs/heads/" + name
    54  			config.SetConfig(
    55  				fmt.Sprintf("branch.%v.merge", name),
    56  				merge,
    57  			)
    58  		} else {
    59  			merge = c.GetConfig("branch." + name + ".merge")
    60  			if merge == "" {
    61  				return fmt.Errorf("The branch %v has no upstream set.\n"+
    62  					"To push and set the upstream to the remote named \"origin\" use:\n\n"+
    63  					"\t%v push --set-upstream origin %v\n",
    64  					name, os.Args[0], name)
    65  			}
    66  		}
    67  		sendrefs = append(sendrefs, ref.LocalName()+":"+Refname(merge))
    68  	}
    69  
    70  	if opts.SetUpstream {
    71  		if err := config.WriteConfig(); err != nil {
    72  			return err
    73  		}
    74  	}
    75  
    76  	return SendPack(c, opts.SendPackOptions, r, sendrefs)
    77  }