1// Copyright 2020 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13
14// +build go1.12
15
16package wire
17
18import (
19	"runtime/debug"
20	"strconv"
21	"strings"
22)
23
24const pubsubLiteModulePath = "cloud.google.com/go/pubsublite"
25
26type version struct {
27	Major string
28	Minor string
29}
30
31// libraryVersion attempts to determine the pubsublite module version.
32func libraryVersion() (version, bool) {
33	if buildInfo, ok := debug.ReadBuildInfo(); ok {
34		return pubsubliteModuleVersion(buildInfo)
35	}
36	return version{}, false
37}
38
39// pubsubliteModuleVersion extracts the module version from BuildInfo embedded
40// in the binary. Only applies to binaries built with module support.
41func pubsubliteModuleVersion(buildInfo *debug.BuildInfo) (version, bool) {
42	for _, dep := range buildInfo.Deps {
43		if dep.Path == pubsubLiteModulePath {
44			return parseModuleVersion(dep.Version)
45		}
46	}
47	return version{}, false
48}
49
50func parseModuleVersion(value string) (v version, ok bool) {
51	if strings.HasPrefix(value, "v") {
52		value = value[1:]
53	}
54	components := strings.Split(value, ".")
55	if len(components) >= 2 {
56		if _, err := strconv.ParseInt(components[0], 10, 32); err != nil {
57			return
58		}
59		if _, err := strconv.ParseInt(components[1], 10, 32); err != nil {
60			return
61		}
62		v = version{Major: components[0], Minor: components[1]}
63		ok = true
64	}
65	return
66}
67