Skip to content

Commit 51f6a9c

Browse files
yuichi10catto
authored andcommitted
fix: reduce habitat API call (#14)
1 parent afccabc commit 51f6a9c

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

sd-step.go

+21-6
Original file line numberDiff line numberDiff line change
@@ -71,18 +71,30 @@ func runCommand(command string, output io.Writer) error {
7171
return cmd.Run()
7272
}
7373

74+
// Check if package is installed
75+
func isPackageInstalled(pkgName string, pkgVersion string) bool {
76+
var output io.Writer
77+
78+
pkg, err := translatePkgName(pkgName, pkgVersion)
79+
if err != nil {
80+
return false
81+
}
82+
83+
// hab pkg path command exits with zero if pkg exists
84+
checkCmd := habPath + " pkg path " + pkg + " >/dev/null 2>&1"
85+
checkCmdResult := runCommand(checkCmd, output)
86+
87+
return checkCmdResult == nil
88+
}
89+
7490
// execHab installs habitat package and executes habitat command
7591
func execHab(pkgName string, pkgVersion string, habChannel string, command []string, output io.Writer) error {
7692
pkg, verErr := translatePkgName(pkgName, pkgVersion)
7793
if verErr != nil {
7894
return verErr
7995
}
8096

81-
// Check if the desired version of the package exists
82-
checkCmd := habPath + " pkg path " + pkg + " >/dev/null 2>&1"
83-
checkCmdResult := runCommand(checkCmd, output)
84-
85-
if checkCmdResult != nil {
97+
if !isPackageInstalled(pkgName, pkgVersion) {
8698
installCmd := []string{habPath, "pkg", "install", pkg, "-c", habChannel, ">/dev/null"}
8799
if u, userErr := user.Current(); userErr != nil || u.Uid != "0" {
88100
// execute sudo command if not root user
@@ -200,7 +212,10 @@ func main() {
200212

201213
depot := hab.New(habDepotURL)
202214

203-
if pkgVerExp != "" {
215+
// Use verExp as an exact package version if it is already installed
216+
if isPackageInstalled(pkgName, pkgVerExp) {
217+
pkgVersion = pkgVerExp
218+
} else if pkgVerExp != "" {
204219
pkgVersion, err = getPackageVersion(depot, pkgName, pkgVerExp, habChannel)
205220

206221
if err != nil {

0 commit comments

Comments
 (0)