github.com/abdfnx/gh-api@v0.0.0-20210414084727-f5432eec23b8/pkg/cmd/factory/default.go (about)

     1  package factory
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"net/http"
     7  	"os"
     8  
     9  	"github.com/abdfnx/gh-api/git"
    10  	"github.com/abdfnx/gh-api/internal/config"
    11  	"github.com/abdfnx/gh-api/internal/ghrepo"
    12  	"github.com/abdfnx/gh-api/pkg/cmdutil"
    13  	"github.com/abdfnx/gh-api/pkg/iostreams"
    14  )
    15  
    16  func New(appVersion string) *cmdutil.Factory {
    17  	io := iostreams.System()
    18  
    19  	var cachedConfig config.Config
    20  	var configError error
    21  	configFunc := func() (config.Config, error) {
    22  		if cachedConfig != nil || configError != nil {
    23  			return cachedConfig, configError
    24  		}
    25  		cachedConfig, configError = config.ParseDefaultConfig()
    26  		if errors.Is(configError, os.ErrNotExist) {
    27  			cachedConfig = config.NewBlankConfig()
    28  			configError = nil
    29  		}
    30  		cachedConfig = config.InheritEnv(cachedConfig)
    31  		return cachedConfig, configError
    32  	}
    33  
    34  	rr := &remoteResolver{
    35  		readRemotes: git.Remotes,
    36  		getConfig:   configFunc,
    37  	}
    38  	remotesFunc := rr.Resolver()
    39  
    40  	ghExecutable := "gh"
    41  	if exe, err := os.Executable(); err == nil {
    42  		ghExecutable = exe
    43  	}
    44  
    45  	return &cmdutil.Factory{
    46  		IOStreams: io,
    47  		Config:    configFunc,
    48  		Remotes:   remotesFunc,
    49  		HttpClient: func() (*http.Client, error) {
    50  			cfg, err := configFunc()
    51  			if err != nil {
    52  				return nil, err
    53  			}
    54  
    55  			return NewHTTPClient(io, cfg, appVersion, true), nil
    56  		},
    57  		BaseRepo: func() (ghrepo.Interface, error) {
    58  			remotes, err := remotesFunc()
    59  			if err != nil {
    60  				return nil, err
    61  			}
    62  			return remotes[0], nil
    63  		},
    64  		Branch: func() (string, error) {
    65  			currentBranch, err := git.CurrentBranch()
    66  			if err != nil {
    67  				return "", fmt.Errorf("could not determine current branch: %w", err)
    68  			}
    69  			return currentBranch, nil
    70  		},
    71  		Executable: ghExecutable,
    72  		Browser:    cmdutil.NewBrowser(os.Getenv("BROWSER"), io.Out, io.ErrOut),
    73  	}
    74  }