本文整理汇总了Golang中github.com/juju/version.Parse函数的典型用法代码示例。如果您正苦于以下问题:Golang Parse函数的具体用法?Golang Parse怎么用?Golang Parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Parse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: loginForVersion
func (st *state) loginForVersion(tag names.Tag, password, nonce string, macaroons []macaroon.Slice, vers int) error {
var result params.LoginResultV1
request := ¶ms.LoginRequest{
AuthTag: tagToString(tag),
Credentials: password,
Nonce: nonce,
Macaroons: macaroons,
}
if tag == nil {
// Add any macaroons from the cookie jar that might work for
// authenticating the login request.
request.Macaroons = append(request.Macaroons,
httpbakery.MacaroonsForURL(st.bakeryClient.Client.Jar, st.cookieURL)...,
)
}
err := st.APICall("Admin", vers, "", "Login", request, &result)
if err != nil {
return errors.Trace(err)
}
if result.DischargeRequired != nil {
// The result contains a discharge-required
// macaroon. We discharge it and retry
// the login request with the original macaroon
// and its discharges.
if result.DischargeRequiredReason == "" {
result.DischargeRequiredReason = "no reason given for discharge requirement"
}
if err := st.bakeryClient.HandleError(st.cookieURL, &httpbakery.Error{
Message: result.DischargeRequiredReason,
Code: httpbakery.ErrDischargeRequired,
Info: &httpbakery.ErrorInfo{
Macaroon: result.DischargeRequired,
MacaroonPath: "/",
},
}); err != nil {
return errors.Trace(err)
}
// Add the macaroons that have been saved by HandleError to our login request.
request.Macaroons = httpbakery.MacaroonsForURL(st.bakeryClient.Client.Jar, st.cookieURL)
result = params.LoginResultV1{} // zero result
err = st.APICall("Admin", vers, "", "Login", request, &result)
if err != nil {
return errors.Trace(err)
}
if result.DischargeRequired != nil {
return errors.Errorf("login with discharged macaroons failed: %s", result.DischargeRequiredReason)
}
}
servers := params.NetworkHostsPorts(result.Servers)
err = st.setLoginResult(tag, result.ModelTag, result.ControllerTag, servers, result.Facades)
if err != nil {
return errors.Trace(err)
}
st.serverVersion, err = version.Parse(result.ServerVersion)
if err != nil {
return errors.Trace(err)
}
return nil
}
示例2: logDocToRecord
func logDocToRecord(doc *logDoc) (*LogRecord, error) {
var ver version.Number
if doc.Version != "" {
parsed, err := version.Parse(doc.Version)
if err != nil {
return nil, errors.Annotatef(err, "invalid version %q", doc.Version)
}
ver = parsed
}
level := loggo.Level(doc.Level)
if level > loggo.CRITICAL {
return nil, errors.Errorf("unrecognized log level %q", doc.Level)
}
entity, err := names.ParseTag(doc.Entity)
if err != nil {
return nil, errors.Annotate(err, "while parsing entity tag")
}
rec := &LogRecord{
ID: doc.Time,
Time: time.Unix(0, doc.Time).UTC(), // not worth preserving TZ
ModelUUID: doc.ModelUUID,
Entity: entity,
Version: ver,
Level: level,
Module: doc.Module,
Location: doc.Location,
Message: doc.Message,
}
return rec, nil
}
示例3: appendArchives
// appendArchives collects all matching Juju GUI archive metadata information.
func appendArchives(
source simplestreams.DataSource,
matchingItems []interface{},
items map[string]interface{},
cons simplestreams.LookupConstraint,
) ([]interface{}, error) {
var majorVersion int
if guiConstraint, ok := cons.(*constraint); ok {
majorVersion = guiConstraint.majorVersion
}
for _, item := range items {
meta := item.(*Metadata)
if majorVersion != 0 && majorVersion != meta.JujuMajorVersion {
continue
}
fullPath, err := source.URL(meta.Path)
if err != nil {
return nil, errors.Annotate(err, "cannot retrieve metadata full path")
}
meta.FullPath = fullPath
vers, err := version.Parse(meta.StringVersion)
if err != nil {
return nil, errors.Annotate(err, "cannot parse metadata version")
}
meta.Version = vers
meta.Source = source
matchingItems = append(matchingItems, meta)
}
return matchingItems, nil
}
示例4: detectMongoVersion
func detectMongoVersion() (version.Number, error) {
mongoPath, err := getMongod()
if err != nil {
return version.Zero, errors.Trace(err)
}
output, err := exec.Command(mongoPath, "--version").Output()
if err != nil {
return version.Zero, errors.Trace(err)
}
// Read the first line of the output with a scanner (to handle
// newlines in a cross-platform way).
scanner := bufio.NewScanner(bytes.NewReader(output))
versionLine := ""
if scanner.Scan() {
versionLine = scanner.Text()
}
if scanner.Err() != nil {
return version.Zero, errors.Trace(scanner.Err())
}
if !strings.HasPrefix(versionLine, versionLinePrefix) {
return version.Zero, errors.New("couldn't get mongod version - no version line")
}
ver, err := version.Parse(versionLine[len(versionLinePrefix):])
if err != nil {
return version.Zero, errors.Trace(err)
}
logger.Debugf("detected mongod version %v", ver)
return ver, nil
}
示例5: Init
func (c *bootstrapCommand) Init(args []string) (err error) {
if c.showClouds && c.showRegionsForCloud != "" {
return errors.New("--clouds and --regions can't be used together")
}
if c.showClouds {
return cmd.CheckEmpty(args)
}
if c.showRegionsForCloud != "" {
return cmd.CheckEmpty(args)
}
if c.AgentVersionParam != "" && c.BuildAgent {
return errors.New("--agent-version and --build-agent can't be used together")
}
if c.BootstrapSeries != "" && !charm.IsValidSeries(c.BootstrapSeries) {
return errors.NotValidf("series %q", c.BootstrapSeries)
}
// Parse the placement directive. Bootstrap currently only
// supports provider-specific placement directives.
if c.Placement != "" {
_, err = instance.ParsePlacement(c.Placement)
if err != instance.ErrPlacementScopeMissing {
// We only support unscoped placement directives for bootstrap.
return errors.Errorf("unsupported bootstrap placement directive %q", c.Placement)
}
}
if !c.AutoUpgrade {
// With no auto upgrade chosen, we default to the version matching the bootstrap client.
vers := jujuversion.Current
c.AgentVersion = &vers
}
if c.AgentVersionParam != "" {
if vers, err := version.ParseBinary(c.AgentVersionParam); err == nil {
c.AgentVersion = &vers.Number
} else if vers, err := version.Parse(c.AgentVersionParam); err == nil {
c.AgentVersion = &vers
} else {
return err
}
}
if c.AgentVersion != nil && (c.AgentVersion.Major != jujuversion.Current.Major || c.AgentVersion.Minor != jujuversion.Current.Minor) {
return errors.New("requested agent version major.minor mismatch")
}
switch len(args) {
case 0:
// no args or flags, go interactive.
c.interactive = true
return nil
}
c.Cloud = args[0]
if i := strings.IndexRune(c.Cloud, '/'); i > 0 {
c.Cloud, c.Region = c.Cloud[:i], c.Cloud[i+1:]
}
if len(args) > 1 {
c.controllerName = args[1]
return cmd.CheckEmpty(args[2:])
}
return nil
}
示例6: archiveVersion
// archiveVersion retrieves the GUI version from the juju-gui-* directory
// included in the given tar.bz2 archive reader.
func archiveVersion(r io.Reader) (version.Number, error) {
var vers version.Number
prefix := "jujugui-"
tr := tar.NewReader(bzip2.NewReader(r))
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return vers, errors.New("cannot read Juju GUI archive")
}
info := hdr.FileInfo()
if !info.IsDir() || !strings.HasPrefix(hdr.Name, prefix) {
continue
}
n := filepath.Dir(hdr.Name)[len(prefix):]
vers, err = version.Parse(n)
if err != nil {
return vers, errors.Errorf("invalid version %q in archive", n)
}
return vers, nil
}
return vers, errors.New("cannot find Juju GUI version in archive")
}
示例7: originFromAPI
func originFromAPI(apiRec params.LogStreamRecord, controllerUUID string) (logfwd.Origin, error) {
var origin logfwd.Origin
tag, err := names.ParseTag(apiRec.Entity)
if err != nil {
return origin, errors.Annotate(err, "invalid entity")
}
ver, err := version.Parse(apiRec.Version)
if err != nil {
return origin, errors.Annotatef(err, "invalid version %q", apiRec.Version)
}
switch tag := tag.(type) {
case names.MachineTag:
origin = logfwd.OriginForMachineAgent(tag, controllerUUID, apiRec.ModelUUID, ver)
case names.UnitTag:
origin = logfwd.OriginForUnitAgent(tag, controllerUUID, apiRec.ModelUUID, ver)
default:
origin, err = logfwd.OriginForJuju(tag, controllerUUID, apiRec.ModelUUID, ver)
if err != nil {
return origin, errors.Annotate(err, "could not extract origin")
}
}
return origin, nil
}
示例8: Init
func (c *bootstrapCommand) Init(args []string) (err error) {
if c.AgentVersionParam != "" && c.UploadTools {
return fmt.Errorf("--agent-version and --upload-tools can't be used together")
}
if c.BootstrapSeries != "" && !charm.IsValidSeries(c.BootstrapSeries) {
return errors.NotValidf("series %q", c.BootstrapSeries)
}
if c.BootstrapImage != "" {
if c.BootstrapSeries == "" {
return errors.Errorf("--bootstrap-image must be used with --bootstrap-series")
}
cons, err := constraints.Merge(c.Constraints, c.BootstrapConstraints)
if err != nil {
return errors.Trace(err)
}
if !cons.HasArch() {
return errors.Errorf("--bootstrap-image must be used with --bootstrap-constraints, specifying architecture")
}
}
// Parse the placement directive. Bootstrap currently only
// supports provider-specific placement directives.
if c.Placement != "" {
_, err = instance.ParsePlacement(c.Placement)
if err != instance.ErrPlacementScopeMissing {
// We only support unscoped placement directives for bootstrap.
return fmt.Errorf("unsupported bootstrap placement directive %q", c.Placement)
}
}
if !c.AutoUpgrade {
// With no auto upgrade chosen, we default to the version matching the bootstrap client.
vers := jujuversion.Current
c.AgentVersion = &vers
}
if c.AgentVersionParam != "" {
if vers, err := version.ParseBinary(c.AgentVersionParam); err == nil {
c.AgentVersion = &vers.Number
} else if vers, err := version.Parse(c.AgentVersionParam); err == nil {
c.AgentVersion = &vers
} else {
return err
}
}
if c.AgentVersion != nil && (c.AgentVersion.Major != jujuversion.Current.Major || c.AgentVersion.Minor != jujuversion.Current.Minor) {
return fmt.Errorf("requested agent version major.minor mismatch")
}
// The user must specify two positional arguments: the controller name,
// and the cloud name (optionally with region specified).
if len(args) < 2 {
return errors.New("controller name and cloud name are required")
}
c.controllerName = bootstrappedControllerName(args[0])
c.Cloud = args[1]
if i := strings.IndexRune(c.Cloud, '/'); i > 0 {
c.Cloud, c.Region = c.Cloud[:i], c.Cloud[i+1:]
}
return cmd.CheckEmpty(args[2:])
}
示例9: AgentVersion
// AgentVersion returns the proposed version number for the agent tools,
// and whether it has been set. Once an environment is bootstrapped, this
// must always be valid.
func (c *Config) AgentVersion() (version.Number, bool) {
if v, ok := c.defined[AgentVersionKey].(string); ok {
n, err := version.Parse(v)
if err != nil {
panic(err) // We should have checked it earlier.
}
return n, true
}
return version.Zero, false
}
示例10: TestCompare
func (*suite) TestCompare(c *gc.C) {
cmpTests := []struct {
v1, v2 string
compare int
}{
{"1.0.0", "1.0.0", 0},
{"01.0.0", "1.0.0", 0},
{"10.0.0", "9.0.0", 1},
{"1.0.0", "1.0.1", -1},
{"1.0.1", "1.0.0", 1},
{"1.0.0", "1.1.0", -1},
{"1.1.0", "1.0.0", 1},
{"1.0.0", "2.0.0", -1},
{"1.2-alpha1", "1.2.0", -1},
{"1.2-alpha2", "1.2-alpha1", 1},
{"1.2-alpha2.1", "1.2-alpha2", 1},
{"1.2-alpha2.2", "1.2-alpha2.1", 1},
{"1.2-beta1", "1.2-alpha1", 1},
{"1.2-beta1", "1.2-alpha2.1", 1},
{"1.2-beta1", "1.2.0", -1},
{"1.2.1", "1.2.0", 1},
{"2.0.0", "1.0.0", 1},
{"2.0.0.0", "2.0.0", 0},
{"2.0.0.0", "2.0.0.0", 0},
{"2.0.0.1", "2.0.0.0", 1},
{"2.0.1.10", "2.0.0.0", 1},
}
for i, test := range cmpTests {
c.Logf("test %d: %q == %q", i, test.v1, test.v2)
v1, err := version.Parse(test.v1)
c.Assert(err, jc.ErrorIsNil)
v2, err := version.Parse(test.v2)
c.Assert(err, jc.ErrorIsNil)
compare := v1.Compare(v2)
c.Check(compare, gc.Equals, test.compare)
// Check that reversing the operands has
// the expected result.
compare = v2.Compare(v1)
c.Check(compare, gc.Equals, -test.compare)
}
}
示例11: binary
// binary returns the tools metadata's binary version, which may be used for
// map lookup.
func (t *ToolsMetadata) binary() (version.Binary, error) {
num, err := version.Parse(t.Version)
if err != nil {
return version.Binary{}, errors.Trace(err)
}
return version.Binary{
Number: num,
Series: t.Release,
Arch: t.Arch,
}, nil
}
示例12: jujuClientVersionFromReq
func jujuClientVersionFromReq(req *http.Request) (version.Number, error) {
verStr := req.URL.Query().Get("jujuclientversion")
if verStr == "" {
return version.Zero, errors.New(`missing "jujuclientversion" in URL query`)
}
ver, err := version.Parse(verStr)
if err != nil {
return version.Zero, errors.Annotatef(err, "invalid jujuclientversion %q", verStr)
}
return ver, nil
}
示例13: ValidateToolsMetadata
// ValidateToolsMetadata attempts to load tools metadata for the specified cloud attributes and returns
// any tools versions found, or an error if the metadata could not be loaded.
func ValidateToolsMetadata(params *ToolsMetadataLookupParams) ([]string, *simplestreams.ResolveInfo, error) {
if len(params.Architectures) == 0 {
return nil, nil, fmt.Errorf("required parameter arches not specified")
}
if len(params.Sources) == 0 {
return nil, nil, fmt.Errorf("required parameter sources not specified")
}
if params.Version == "" && params.Major == 0 {
params.Version = jujuversion.Current.String()
}
var toolsConstraint *ToolsConstraint
if params.Version == "" {
toolsConstraint = NewGeneralToolsConstraint(params.Major, params.Minor, simplestreams.LookupParams{
CloudSpec: simplestreams.CloudSpec{
Region: params.Region,
Endpoint: params.Endpoint,
},
Stream: params.Stream,
Series: []string{params.Series},
Arches: params.Architectures,
})
} else {
versNum, err := version.Parse(params.Version)
if err != nil {
return nil, nil, err
}
toolsConstraint = NewVersionedToolsConstraint(versNum, simplestreams.LookupParams{
CloudSpec: simplestreams.CloudSpec{
Region: params.Region,
Endpoint: params.Endpoint,
},
Stream: params.Stream,
Series: []string{params.Series},
Arches: params.Architectures,
})
}
matchingTools, resolveInfo, err := Fetch(params.Sources, toolsConstraint)
if err != nil {
return nil, resolveInfo, err
}
if len(matchingTools) == 0 {
return nil, resolveInfo, fmt.Errorf("no matching tools found for constraint %+v", toolsConstraint)
}
versions := make([]string, len(matchingTools))
for i, tm := range matchingTools {
vers := version.Binary{
Number: version.MustParse(tm.Version),
Series: tm.Release,
Arch: tm.Arch,
}
versions[i] = vers.String()
}
return versions, resolveInfo, nil
}
示例14: checkVersion
func (c *ModelConfigCreator) checkVersion(base *config.Config, attrs map[string]interface{}) error {
baseVersion, ok := base.AgentVersion()
if !ok {
return errors.Errorf("agent-version not found in base config")
}
// If there is no agent-version specified, use the current version.
// otherwise we need to check for tools
value, ok := attrs["agent-version"]
if !ok {
attrs["agent-version"] = baseVersion.String()
return nil
}
versionStr, ok := value.(string)
if !ok {
return errors.Errorf("agent-version must be a string but has type '%T'", value)
}
versionNumber, err := version.Parse(versionStr)
if err != nil {
return errors.Trace(err)
}
n := versionNumber.Compare(baseVersion)
switch {
case n > 0:
return errors.Errorf(
"agent-version (%s) cannot be greater than the controller (%s)",
versionNumber, baseVersion,
)
case n == 0:
// If the version is the same as the base config,
// then assume tools are available.
return nil
case n < 0:
if c.FindTools == nil {
return errors.New(
"agent-version does not match base config, " +
"and no tools-finder is supplied",
)
}
}
// Look to see if we have tools available for that version.
list, err := c.FindTools(versionNumber)
if err != nil {
return errors.Trace(err)
}
if len(list) == 0 {
return errors.Errorf("no tools found for version %s", versionNumber)
}
logger.Tracef("found tools: %#v", list)
return nil
}
示例15: TestParse
func (*suite) TestParse(c *gc.C) {
for i, test := range parseTests {
c.Logf("test %d: %q", i, test.v)
got, err := version.Parse(test.v)
if test.err != "" {
c.Assert(err, gc.ErrorMatches, test.err)
} else {
c.Assert(err, jc.ErrorIsNil)
c.Assert(got, gc.Equals, test.expect)
c.Check(got.String(), gc.Equals, test.v)
}
}
}