本文整理匯總了Golang中github.com/blang/semver.Parse函數的典型用法代碼示例。如果您正苦於以下問題:Golang Parse函數的具體用法?Golang Parse怎麽用?Golang Parse使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Parse函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: ParseImageTag
// ParseImageTag parses the docker image tag string and returns a validated Version or error
func ParseImageTag(s string) (CombinedVersion, error) {
// try parse as a SEMVER
prefix := ""
version, err := semver.Parse(s)
if err == nil {
return CombinedVersion{Prefix: prefix, Version: version}, nil
}
// accept format such as `vSEMVER`
if vIndex := strings.IndexRune(s, 'v'); vIndex == 0 {
prefix = s[:vIndex+1]
version, err = semver.Parse(s[vIndex+1:])
if err == nil {
return CombinedVersion{Prefix: prefix, Version: version}, nil
}
}
// accept format such as `ANY-SEMVER`
if firstHyphenIndex := strings.IndexRune(s, '-'); firstHyphenIndex != -1 {
prefix = s[:firstHyphenIndex+1]
version, err = semver.Parse(s[firstHyphenIndex+1:])
if err == nil {
return CombinedVersion{Prefix: prefix, Version: version}, nil
}
}
return CombinedVersion{}, err
}
示例2: UnmarshalJSON
// UnmarshalJSON implements json.Unmarshaler and postprocesses of ProducerTopics and VersionObj
func (p *Producer) UnmarshalJSON(b []byte) error {
var r struct {
RemoteAddress string `json:"remote_address"`
Hostname string `json:"hostname"`
BroadcastAddress string `json:"broadcast_address"`
TCPPort int `json:"tcp_port"`
HTTPPort int `json:"http_port"`
Version string `json:"version"`
Topics []string `json:"topics"`
Tombstoned []bool `json:"tombstones"`
}
if err := json.Unmarshal(b, &r); err != nil {
return err
}
*p = Producer{
RemoteAddress: r.RemoteAddress,
Hostname: r.Hostname,
BroadcastAddress: r.BroadcastAddress,
TCPPort: r.TCPPort,
HTTPPort: r.HTTPPort,
Version: r.Version,
}
for i, t := range r.Topics {
p.Topics = append(p.Topics, ProducerTopic{Topic: t, Tombstoned: r.Tombstoned[i]})
}
version, err := semver.Parse(p.Version)
if err != nil {
version, _ = semver.Parse("0.0.0")
}
p.VersionObj = version
return nil
}
示例3: ToValidSemver
// ToValidSemver attempts to return the input as valid semver.
// If the input fails to parse as semver, it appends .0 or .0.0 to the input and retries
// If this is still not valid semver, it returns an error
func (s SemverConverter) ToValidSemver(input string) (semver.Version, error) {
v, err := semver.Parse(input)
if err == nil {
return v, nil
}
s.logger.Info(fmt.Sprintf(
"failed to parse semver: '%s', appending zeros and trying again",
input,
))
maybeSemver := input
segs := strings.SplitN(maybeSemver, ".", 3)
switch len(segs) {
case 2:
maybeSemver += ".0"
case 1:
maybeSemver += ".0.0"
}
v, err = semver.Parse(maybeSemver)
if err == nil {
return v, nil
}
s.logger.Info(fmt.Sprintf(
"still failed to parse semver: '%s', giving up",
maybeSemver,
))
return semver.Version{}, err
}
示例4: PrioritizeTags
// PrioritizeTags orders a set of image tags with a few conventions:
//
// 1. the "latest" tag, if present, should be first
// 2. any tags that represent a semantic major version ("5", "v5") should be next, in descending order
// 3. any tags that represent a semantic minor version ("5.1", "v5.1") should be next, in descending order
// 4. any tags that represent a full semantic version ("5.1.3-other", "v5.1.3-other") should be next, in descending order
// 5. any remaining tags should be sorted in lexicographic order
//
// The method updates the tags in place.
func PrioritizeTags(tags []string) {
remaining := tags
finalTags := make([]string, 0, len(tags))
for i, tag := range tags {
if tag == DefaultImageTag {
tags[0], tags[i] = tags[i], tags[0]
finalTags = append(finalTags, tags[0])
remaining = tags[1:]
break
}
}
exact := make(map[string]string)
var major, minor, micro semver.Versions
other := make([]string, 0, len(remaining))
for _, tag := range remaining {
short := strings.TrimLeft(tag, "v")
v, err := semver.Parse(short)
switch {
case err == nil:
exact[v.String()] = tag
micro = append(micro, v)
continue
case reMajorSemantic.MatchString(short):
if v, err = semver.Parse(short + ".0.0"); err == nil {
exact[v.String()] = tag
major = append(major, v)
continue
}
case reMinorSemantic.MatchString(short):
if v, err = semver.Parse(short + ".0"); err == nil {
exact[v.String()] = tag
minor = append(minor, v)
continue
}
}
other = append(other, tag)
}
sort.Sort(sort.Reverse(major))
sort.Sort(sort.Reverse(minor))
sort.Sort(sort.Reverse(micro))
sort.Sort(sort.StringSlice(other))
for _, v := range major {
finalTags = append(finalTags, exact[v.String()])
}
for _, v := range minor {
finalTags = append(finalTags, exact[v.String()])
}
for _, v := range micro {
finalTags = append(finalTags, exact[v.String()])
}
for _, v := range other {
finalTags = append(finalTags, v)
}
copy(tags, finalTags)
}
示例5: Less
func (r releases) Less(i, j int) bool {
v1, err := semver.Parse(r[i].Version)
if err != nil {
panic(err)
}
v2, err := semver.Parse(r[j].Version)
if err != nil {
writeLn(r[j].Version)
panic(err)
}
return v1.LT(v2)
}
示例6: Version
// Version returns the Docker version and whether it is a Red Hat distro version
func (h *Helper) Version() (*semver.Version, bool, error) {
glog.V(5).Infof("Retrieving Docker version")
env, err := h.client.Version()
if err != nil {
glog.V(2).Infof("Error retrieving version: %v", err)
return nil, false, err
}
glog.V(5).Infof("Docker version results: %#v", env)
versionStr := env.Get("Version")
if len(versionStr) == 0 {
return nil, false, errors.New("did not get a version")
}
glog.V(5).Infof("Version: %s", versionStr)
dockerVersion, err := semver.Parse(versionStr)
if err != nil {
glog.V(2).Infof("Error parsing Docker version %q", versionStr)
return nil, false, err
}
isRedHat := false
packageVersion := env.Get("PkgVersion")
if len(packageVersion) > 0 {
isRedHat = fedoraPackage.MatchString(packageVersion) || rhelPackage.MatchString(packageVersion)
}
return &dockerVersion, isRedHat, nil
}
示例7: FromSource
func FromSource(source models.Source) (Driver, error) {
var initialVersion semver.Version
if source.InitialVersion != "" {
version, err := semver.Parse(source.InitialVersion)
if err != nil {
return nil, fmt.Errorf("invalid initial version (%s): %s", source.InitialVersion, err)
}
initialVersion = version
} else {
initialVersion = semver.Version{Major: 0, Minor: 0, Patch: 0}
}
switch source.Driver {
case models.DriverUnspecified, models.DriverS3:
auth := aws.Auth{
AccessKey: source.AccessKeyID,
SecretKey: source.SecretAccessKey,
}
regionName := source.RegionName
if len(regionName) == 0 {
regionName = aws.USEast.Name
}
region, ok := aws.Regions[regionName]
if !ok {
return nil, errors.New(fmt.Sprintf("no such region '%s'", regionName))
}
if len(source.Endpoint) != 0 {
region = aws.Region{
S3Endpoint: fmt.Sprintf("https://%s", source.Endpoint),
}
}
client := s3.New(auth, region)
bucket := client.Bucket(source.Bucket)
return &S3Driver{
InitialVersion: initialVersion,
Bucket: bucket,
Key: source.Key,
}, nil
case models.DriverGit:
return &GitDriver{
InitialVersion: initialVersion,
URI: source.URI,
Branch: source.Branch,
PrivateKey: source.PrivateKey,
File: source.File,
}, nil
default:
return nil, fmt.Errorf("unknown driver: %s", source.Driver)
}
}
示例8: checkSchema
func checkSchema() {
var count int
defer writeConstants()
db.DB.Table("constants").Where("schema_version = ?", schemaVersion.String()).Count(&count)
if count == 1 {
return
}
currStr := getCurrConstants().SchemaVersion
if currStr == "" {
db.DB.Save(&Constant{
schemaVersion.String(),
})
//Initial database migration
whitelist_id_string()
//Write current schema version
return
}
if v, _ := semver.Parse(currStr); v.Major < schemaVersion.Major {
logrus.Warningf("Incompatible schema change detected (%s), attempting to migrate to (%s).", currStr, schemaVersion.String())
for i := v.Major + 1; i <= schemaVersion.Major; i++ {
logrus.Debugf("Calling migration routine for %d.0.0", i)
f := migrationRoutines[i]
f()
}
}
}
示例9: getLatestVersion
func getLatestVersion(zipFile []byte, prefix, suffix string) (string, error) {
r, err := zip.NewReader(bytes.NewReader(zipFile), int64(len(zipFile)))
if err != nil {
return "", err
}
latest := ""
for _, f := range r.File {
artifact := path.Base(f.Name)
if strings.HasPrefix(artifact, prefix) && strings.HasSuffix(artifact, suffix) {
v := extractVersion(artifact)
if latest == "" {
latest = v
}
v1, err := semver.Parse(v)
if err != nil {
return "", err
}
l := semver.MustParse(latest)
if v1.GT(l) {
latest = v
}
}
}
return latest, nil
}
示例10: mustParse
func mustParse(s string) semver.Version {
v, err := semver.Parse(s)
if err != nil {
panic(`semver: Parse(` + s + `): ` + err.Error())
}
return v
}
示例11: bumpedVersion
// bumpedVersion returns new bumped-up version according to given spec.
func (conf Config) bumpedVersion(version string) (string, error) {
if conf.Exact != "" {
exact, err := semver.New(conf.Exact)
if err != nil {
return "", err
}
return exact.String(), nil
}
v, err := semver.Parse(version)
if err != nil {
return "", err
}
if conf.MajorDelta > 0 {
v.Major = v.Major + conf.MajorDelta
v.Minor = 0
v.Patch = 0
} else if conf.MinorDelta > 0 {
v.Minor = v.Minor + conf.MinorDelta
v.Patch = 0
} else if conf.PatchDelta > 0 {
v.Patch = v.Patch + conf.PatchDelta
}
return v.String(), nil
}
示例12: Parse
func Parse(versionString string) (*Version, error) {
v, err := semver.Parse(versionString)
if err != nil {
return nil, err
}
return &Version{v}, nil
}
示例13: Parse
// Parse will try to parse the data and determine which specific version of schema to further parse.
func (parser YAMLParser) Parse(data []byte) (common.OpenControl, error) {
if data == nil || len(data) == 0 {
return nil, common.ErrNoDataToParse
}
b := Base{}
err := yaml.Unmarshal(data, &b)
if err != nil {
return nil, errors.New(ErrMalformedBaseYamlPrefix + " - " + err.Error())
}
var opencontrol common.OpenControl
var parseError error
v, err := semver.Parse(b.SchemaVersion)
if err != nil {
return nil, common.ErrCantParseSemver
}
switch {
case SchemaV1_0_0.Equals(v):
opencontrol = new(v1_0_0.OpenControl)
parseError = yaml.Unmarshal(data, opencontrol)
default:
return nil, common.ErrUnknownSchemaVersion
}
if parseError != nil {
return nil, parseError
}
return opencontrol, nil
}
示例14: GetLookupdProducers
// GetLookupdProducers returns a ProducerList metadata for each node connected to the given lookupds
func (c *ClusterInfo) GetLookupdProducers(lookupdHTTPAddrs []string) (ProducerList, error) {
var success bool
var output []*Producer
var lock sync.Mutex
var wg sync.WaitGroup
allProducers := make(map[string]*Producer)
maxVersion, _ := semver.Parse("0.0.0")
type respType struct {
Producers []*Producer `json:"producers"`
}
for _, addr := range lookupdHTTPAddrs {
wg.Add(1)
endpoint := fmt.Sprintf("http://%s/nodes", addr)
c.logf("LOOKUPD: querying %s", endpoint)
go func(addr string, endpoint string) {
defer wg.Done()
var resp respType
err := http_api.NegotiateV1(endpoint, &resp)
if err != nil {
c.logf("ERROR: lookupd %s - %s", endpoint, err)
return
}
lock.Lock()
defer lock.Unlock()
success = true
for _, producer := range resp.Producers {
key := producer.TCPAddress()
p, ok := allProducers[key]
if !ok {
if maxVersion.LT(producer.VersionObj) {
maxVersion = producer.VersionObj
}
sort.Sort(producer.Topics)
p = producer
allProducers[key] = p
output = append(output, p)
}
p.RemoteAddresses = append(p.RemoteAddresses, fmt.Sprintf("%s/%s", addr, producer.Address()))
}
}(addr, endpoint)
}
wg.Wait()
if success == false {
return nil, errors.New("unable to query any lookupd")
}
for _, producer := range allProducers {
if producer.VersionObj.LT(maxVersion) {
producer.OutOfDate = true
}
}
sort.Sort(ProducersByHost{output})
return output, nil
}
示例15: Parse
// Parse will try to parse the data and determine which specific version of schema to further parse.
func Parse(parser common.SchemaParser, data []byte) (common.BaseSchema, error) {
if data == nil || len(data) == 0 {
return nil, ErrNoDataToParse
}
base := common.Base{}
err := yaml.Unmarshal(data, &base)
if err != nil {
return nil, errors.New(ErrMalformedBaseYamlPrefix + " - " + err.Error())
}
var schema common.BaseSchema
var parseError error
v, err := semver.Parse(base.SchemaVersion)
if err != nil {
return nil, ErrCantParseSemver
}
switch {
case SchemaV1_0_0.Equals(v):
schema, parseError = parser.ParseV1_0_0(data)
default:
return nil, ErrUnknownSchemaVersion
}
if parseError != nil {
return nil, parseError
}
return schema, nil
}