github.com/golang/dep@v0.5.4/gps/vcs_version.go (about)

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package gps
     6  
     7  import (
     8  	"strings"
     9  
    10  	"github.com/Masterminds/vcs"
    11  	"github.com/pkg/errors"
    12  )
    13  
    14  // VCSVersion returns the current project version for an absolute path.
    15  func VCSVersion(path string) (Version, error) {
    16  	repo, err := vcs.NewRepo("", path)
    17  	if err != nil {
    18  		return nil, errors.Wrapf(err, "creating new repo for root: %s", path)
    19  	}
    20  
    21  	ver, err := repo.Current()
    22  	if err != nil {
    23  		return nil, errors.Wrapf(err, "finding current branch/version for root: %s", path)
    24  	}
    25  
    26  	rev, err := repo.Version()
    27  	if err != nil {
    28  		return nil, errors.Wrapf(err, "getting repo version for root: %s", path)
    29  	}
    30  
    31  	// First look through tags.
    32  	tags, err := repo.Tags()
    33  	if err != nil {
    34  		return nil, errors.Wrapf(err, "getting repo tags for root: %s", path)
    35  	}
    36  	// Try to match the current version to a tag.
    37  	if contains(tags, ver) {
    38  		// Assume semver if it starts with a v.
    39  		if strings.HasPrefix(ver, "v") {
    40  			return NewVersion(ver).Pair(Revision(rev)), nil
    41  		}
    42  
    43  		return nil, errors.Errorf("version for root %s does not start with a v: %q", path, ver)
    44  	}
    45  
    46  	// Look for the current branch.
    47  	branches, err := repo.Branches()
    48  	if err != nil {
    49  		return nil, errors.Wrapf(err, "getting repo branch for root: %s", path)
    50  	}
    51  	// Try to match the current version to a branch.
    52  	if contains(branches, ver) {
    53  		return NewBranch(ver).Pair(Revision(rev)), nil
    54  	}
    55  
    56  	return Revision(rev), nil
    57  }
    58  
    59  // contains checks if a array of strings contains a value
    60  func contains(a []string, b string) bool {
    61  	for _, v := range a {
    62  		if b == v {
    63  			return true
    64  		}
    65  	}
    66  	return false
    67  }