[codegen/go] Add utility function to get current package version (#6117)

This function uses reflection to determine the current package
path and then extracts the version from that path string.
This commit is contained in:
Levi Blackstone 2021-01-15 10:03:57 -07:00 committed by GitHub
parent 61ae57da0c
commit aec642e8c9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1637,12 +1637,15 @@ func GeneratePackage(tool string, pkg *schema.Package) (map[string][]byte, error
} }
// Utilities // Utilities
if pkg.needsUtils { if pkg.needsUtils || len(mod) == 0 {
buffer := &bytes.Buffer{} buffer := &bytes.Buffer{}
imports := codegen.NewStringSet("github.com/pulumi/pulumi/sdk/v2/go/pulumi") imports := codegen.NewStringSet(
pkg.genHeader(buffer, []string{"os", "strconv", "strings"}, imports) "github.com/blang/semver",
"github.com/pulumi/pulumi/sdk/v2/go/pulumi",
)
pkg.genHeader(buffer, []string{"os", "reflect", "strconv", "strings"}, imports)
fmt.Fprintf(buffer, "%s", utilitiesFile) fmt.Fprintf(buffer, utilitiesFile, pkg.pkg.Name)
setFile(path.Join(mod, "pulumiUtilities.go"), buffer.String()) setFile(path.Join(mod, "pulumiUtilities.go"), buffer.String())
} }
@ -1702,4 +1705,19 @@ func getEnvOrDefault(def interface{}, parser envParser, vars ...string) interfac
} }
return def return def
} }
// PkgVersion uses reflection to determine the version of the current package.
func PkgVersion() (semver.Version, error) {
type sentinal struct{}
pkgPath := reflect.TypeOf(sentinal{}).PkgPath()
re := regexp.MustCompile("^.*/pulumi-%s/sdk/v(\\d+)*")
if match := re.FindStringSubmatch(pkgPath); match != nil {
vStr := match[1]
if len(vStr) == 0 {
return semver.Version{Major: 1}, nil
}
return semver.MustParse(fmt.Sprintf("%%s.0.0", vStr)), nil
}
return semver.Version{}, fmt.Errorf("not found")
}
` `