github.com/tooploox/oya@v0.0.21-0.20230524103240-1cda1861aad6/cmd/internal/get.go (about)

     1  package internal
     2  
     3  import (
     4  	"io"
     5  	"strings"
     6  
     7  	"github.com/pkg/errors"
     8  	"github.com/tooploox/oya/pkg/pack"
     9  	"github.com/tooploox/oya/pkg/project"
    10  	"github.com/tooploox/oya/pkg/repo"
    11  	"github.com/tooploox/oya/pkg/semver"
    12  	"github.com/tooploox/oya/pkg/types"
    13  )
    14  
    15  func Get(workDir, uri string, update bool, stdout, stderr io.Writer) error {
    16  	importPathStr, versionStr, err := parseUri(uri)
    17  	if err != nil {
    18  		return wrapErr(err, uri)
    19  	}
    20  	importPath := types.ImportPath(importPathStr)
    21  	library, err := repo.Open(importPath)
    22  	if err != nil {
    23  		return wrapErr(err, uri)
    24  	}
    25  
    26  	installDir, err := installDir()
    27  	if err != nil {
    28  		return wrapErr(err, uri)
    29  	}
    30  	prj, err := project.Detect(workDir, installDir)
    31  	if err != nil {
    32  		return wrapErr(err, uri)
    33  	}
    34  
    35  	var pack pack.Pack
    36  	if len(versionStr) == 0 {
    37  		if !update {
    38  			currentPack, found, err := prj.FindRequiredPack(importPath)
    39  			if err != nil {
    40  				return wrapErr(err, uri)
    41  			}
    42  			if found {
    43  				installed, err := prj.IsInstalled(currentPack)
    44  				if err != nil {
    45  					return wrapErr(err, uri)
    46  				}
    47  				if installed {
    48  					return nil
    49  				}
    50  			}
    51  		}
    52  		pack, err = library.LatestVersion()
    53  		if err != nil {
    54  			return wrapErr(err, uri)
    55  		}
    56  	} else {
    57  		if update {
    58  			return errors.Errorf("Cannot request a specific pack version and use the -u (--update) flag at the same time")
    59  		}
    60  		version, err := semver.Parse(versionStr)
    61  		if err != nil {
    62  			return wrapErr(err, uri)
    63  		}
    64  
    65  		pack, err = library.Version(version)
    66  		if err != nil {
    67  			return wrapErr(err, uri)
    68  		}
    69  	}
    70  	err = prj.Install(pack)
    71  	if err != nil {
    72  		return wrapErr(err, uri)
    73  	}
    74  	err = prj.Require(pack)
    75  	if err != nil {
    76  		return wrapErr(err, uri)
    77  	}
    78  	return nil
    79  }
    80  
    81  func parseUri(uri string) (string, string, error) {
    82  	parts := strings.Split(uri, "@")
    83  	switch len(parts) {
    84  	case 1:
    85  		return parts[0], "", nil
    86  	case 2:
    87  		return parts[0], parts[1], nil
    88  	default:
    89  		return "", "", errors.Errorf("unsupported pack uri: %v", uri)
    90  	}
    91  }
    92  
    93  func wrapErr(err error, uri string) error {
    94  	return errors.Wrapf(err, "error getting pack %v", uri)
    95  }