1
0
mirror of https://github.com/prometheus-community/postgres_exporter.git synced 2025-08-08 04:42:07 +03:00

Add self-contained gometalinter build tooling.

This commit is contained in:
Will Rouesnel
2017-06-06 21:39:41 +10:00
parent 0de0311c22
commit e2b6c973a1
710 changed files with 277204 additions and 35 deletions

147
tools/vendor/github.com/mattn/goveralls/README.md generated vendored Normal file
View File

@@ -0,0 +1,147 @@
goveralls
=========
[Go](http://golang.org) integration for [Coveralls.io](http://coveralls.io)
continuous code coverage tracking system.
# Installation
`goveralls` requires a working Go installation (Go-1.2 or higher).
```bash
$ go get github.com/mattn/goveralls
```
# Usage
First you will need an API token. It is found at the bottom of your
repository's page when you are logged in to Coveralls.io. Each repo has its
own token.
```bash
$ cd $GOPATH/src/github.com/yourusername/yourpackage
$ goveralls -repotoken your_repos_coveralls_token
```
You can set the environment variable `$COVERALLS_TOKEN` to your token so you do
not have to specify it at each invocation.
# Continuous Integration
There is no need to run `go test` separately, as `goveralls` runs the entire
test suite.
## Travis CI
### GitHub Integration
Enable Travis-CI on your github repository settings.
For a **public** github repository put below's `.travis.yml`.
```
language: go
sudo: false
go:
- tip
before_install:
- go get github.com/mattn/goveralls
script:
- $HOME/gopath/bin/goveralls -service=travis-ci
```
For a **public** github repository, it is not necessary to define your repository key (`COVERALLS_TOKEN`).
For a **private** github repository put below's `.travis.yml`. If you use **travis pro**, you need to specify `-service=travis-pro` instead of `-service=travis-ci`.
```
language: go
sudo: false
go:
- tip
before_install:
- go get github.com/mattn/goveralls
script:
- $HOME/gopath/bin/goveralls -service=travis-pro
```
Store your Coveralls API token in `Environment variables`.
```
COVERALLS_TOKEN = your_token_goes_here
```
or you can store token using [travis encryption keys](https://docs.travis-ci.com/user/encryption-keys/). Note that this is the token provided in the page for that specific repository on Coveralls. This is *not* one that was created from the "Personal API Tokens" area under your Coveralls account settings.
```
$ gem install travis
$ travis encrypt COVERALLS_TOKEN=your_token_goes_here --add env.global
```
travis will add `env` block as following example:
```
env:
global:
secure: xxxxxxxxxxxxx
```
### For others:
```
$ go get github.com/mattn/goveralls
$ go test -covermode=count -coverprofile=profile.cov
$ goveralls -coverprofile=profile.cov -service=travis-ci
```
## Drone.io
Store your Coveralls API token in `Environment Variables`:
```
COVERALLS_TOKEN=your_token_goes_here
```
Replace the `go test` line in your `Commands` with these lines:
```
$ go get github.com/mattn/goveralls
$ goveralls -service drone.io
```
`goveralls` automatically use the environment variable `COVERALLS_TOKEN` as the
default value for `-repotoken`.
You can use the `-v` flag to see verbose output from the test suite:
```
$ goveralls -v -service drone.io
```
## CircleCI
Store your Coveralls API token as an [Environment Variable](https://circleci.com/docs/environment-variables).
In your `circle.yml` add the following commands under the `test` section.
```yml
test:
pre:
- go get github.com/mattn/goveralls
override:
- go test -v -cover -race -coverprofile=/home/ubuntu/coverage.out
post:
- /home/ubuntu/.go_workspace/bin/goveralls -coverprofile=/home/ubuntu/coverage.out -service=circle-ci -repotoken=$COVERALLS_TOKEN
```
For more information, See https://coveralls.zendesk.com/hc/en-us/articles/201342809-Go
# Authors
* Yasuhiro Matsumoto (a.k.a. mattn)
* haya14busa
# License
under the MIT License: http://mattn.mit-license.org/2016

116
tools/vendor/github.com/mattn/goveralls/gitinfo.go generated vendored Normal file
View File

@@ -0,0 +1,116 @@
package main
import (
"log"
"os"
"os/exec"
"regexp"
"strings"
)
var remotesRE = regexp.MustCompile(`^(\S+)\s+(\S+)`)
// A Head object encapsulates information about the HEAD revision of a git repo.
type Head struct {
Id string `json:"id"`
AuthorName string `json:"author_name,omitempty"`
AuthorEmail string `json:"author_email,omitempty"`
CommitterName string `json:"committer_name,omitempty"`
CommitterEmail string `json:"committer_email,omitempty"`
Message string `json:"message"`
}
// A Remote object encapsulates information about a remote of a git repo.
type Remote struct {
Name string `json:"name"`
Url string `json:"url"`
}
// A Git object encapsulates information about a git repo.
type Git struct {
Head Head `json:"head"`
Branch string `json:"branch"`
Remotes []*Remote `json:"remotes,omitempty"`
}
// collectGitInfo runs several git commands to compose a Git object.
func collectGitInfo() *Git {
gitCmds := map[string][]string{
"id": {"rev-parse", "HEAD"},
"branch": {"rev-parse", "--abbrev-ref", "HEAD"},
"aname": {"log", "-1", "--pretty=%aN"},
"aemail": {"log", "-1", "--pretty=%aE"},
"cname": {"log", "-1", "--pretty=%cN"},
"cemail": {"log", "-1", "--pretty=%cE"},
"message": {"log", "-1", "--pretty=%s"},
"remotes": {"remote", "-v"},
}
results := map[string]string{}
remotes := map[string]Remote{}
gitPath, err := exec.LookPath("git")
if err != nil {
log.Fatal(err)
}
for key, args := range gitCmds {
if key == "branch" {
if envBranch := loadBranchFromEnv(); envBranch != "" {
results[key] = envBranch
continue
}
}
cmd := exec.Command(gitPath, args...)
ret, err := cmd.CombinedOutput()
if err != nil {
if strings.Contains(string(ret), `Not a git repository`) {
return nil
}
log.Fatalf("%v: %v", err, string(ret))
}
s := string(ret)
s = strings.TrimRight(s, "\n")
results[key] = s
}
for _, line := range strings.Split(results["remotes"], "\n") {
matches := remotesRE.FindAllStringSubmatch(line, -1)
if len(matches) != 1 {
continue
}
if len(matches[0]) != 3 {
continue
}
name := matches[0][1]
url := matches[0][2]
r := Remote{
Name: name,
Url: url,
}
remotes[name] = r
}
h := Head{
Id: results["id"],
AuthorName: results["aname"],
AuthorEmail: results["aemail"],
CommitterName: results["cname"],
CommitterEmail: results["cemail"],
Message: results["message"],
}
g := &Git{
Head: h,
Branch: results["branch"],
}
for _, r := range remotes {
g.Remotes = append(g.Remotes, &r)
}
return g
}
func loadBranchFromEnv() string {
varNames := []string{"GIT_BRANCH", "CIRCLE_BRANCH", "TRAVIS_BRANCH", "CI_BRANCH", "APPVEYOR_REPO_BRANCH"}
for _, varName := range varNames {
if branch := os.Getenv(varName); branch != "" {
return branch
}
}
return ""
}

132
tools/vendor/github.com/mattn/goveralls/gocover.go generated vendored Normal file
View File

@@ -0,0 +1,132 @@
package main
// Much of the core of this is copied from go's cover tool itself.
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The rest is written by Dustin Sallings
import (
"bytes"
"fmt"
"go/build"
"io/ioutil"
"log"
"path/filepath"
"strings"
"golang.org/x/tools/cover"
)
func findFile(file string) (string, error) {
dir, file := filepath.Split(file)
pkg, err := build.Import(dir, ".", build.FindOnly)
if err != nil {
return "", fmt.Errorf("can't find %q: %v", file, err)
}
return filepath.Join(pkg.Dir, file), nil
}
// mergeProfs merges profiles for same target packages.
// It assumes each profiles have same sorted FileName and Blocks.
func mergeProfs(pfss [][]*cover.Profile) []*cover.Profile {
// skip empty profiles ([no test files])
for i := 0; i < len(pfss); i++ {
if len(pfss[i]) > 0 {
pfss = pfss[i:]
break
}
}
if len(pfss) == 0 {
return nil
} else if len(pfss) == 1 {
return pfss[0]
}
head, rest := pfss[0], pfss[1:]
ret := make([]*cover.Profile, 0, len(head))
for i, profile := range head {
for _, ps := range rest {
if len(ps) == 0 {
// no test files
continue
} else if len(ps) < i+1 {
log.Fatal("Profile length is different")
}
if ps[i].FileName != profile.FileName {
log.Fatal("Profile FileName is different")
}
profile.Blocks = mergeProfBlocks(profile.Blocks, ps[i].Blocks)
}
ret = append(ret, profile)
}
return ret
}
func mergeProfBlocks(as, bs []cover.ProfileBlock) []cover.ProfileBlock {
if len(as) != len(bs) {
log.Fatal("Two block length should be same")
}
// cover.ProfileBlock genereated by cover.ParseProfiles() is sorted by
// StartLine and StartCol, so we can use index.
ret := make([]cover.ProfileBlock, 0, len(as))
for i, a := range as {
b := bs[i]
if a.StartLine != b.StartLine || a.StartCol != b.StartCol {
log.Fatal("Blocks are not sorted")
}
a.Count += b.Count
ret = append(ret, a)
}
return ret
}
// toSF converts profiles to sourcefiles for coveralls.
func toSF(profs []*cover.Profile) ([]*SourceFile, error) {
var rv []*SourceFile
for _, prof := range profs {
path, err := findFile(prof.FileName)
if err != nil {
log.Fatalf("Can't find %v", err)
}
fb, err := ioutil.ReadFile(path)
if err != nil {
log.Fatalf("Error reading %v: %v", path, err)
}
sf := &SourceFile{
Name: getCoverallsSourceFileName(path),
Source: string(fb),
Coverage: make([]interface{}, 1+bytes.Count(fb, []byte{'\n'})),
}
for _, block := range prof.Blocks {
for i := block.StartLine; i <= block.EndLine; i++ {
count, _ := sf.Coverage[i-1].(int)
sf.Coverage[i-1] = count + block.Count
}
}
rv = append(rv, sf)
}
return rv, nil
}
func parseCover(fn string) ([]*SourceFile, error) {
var pfss [][]*cover.Profile
for _, p := range strings.Split(fn, ",") {
profs, err := cover.ParseProfiles(p)
if err != nil {
return nil, fmt.Errorf("Error parsing coverage: %v", err)
}
pfss = append(pfss, profs)
}
sourceFiles, err := toSF(mergeProfs(pfss))
if err != nil {
return nil, err
}
return sourceFiles, nil
}

335
tools/vendor/github.com/mattn/goveralls/goveralls.go generated vendored Normal file
View File

@@ -0,0 +1,335 @@
// Copyright (c) 2013 Yasuhiro Matsumoto, Jason McVetta.
// This is Free Software, released under the MIT license.
// See http://mattn.mit-license.org/2013 for details.
// goveralls is a Go client for Coveralls.io.
package main
import (
_ "crypto/sha512"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"golang.org/x/tools/cover"
)
/*
https://coveralls.io/docs/api_reference
*/
type Flags []string
func (a *Flags) String() string {
return strings.Join(*a, ",")
}
func (a *Flags) Set(value string) error {
*a = append(*a, value)
return nil
}
var (
extraFlags Flags
pkg = flag.String("package", "", "Go package")
verbose = flag.Bool("v", false, "Pass '-v' argument to 'go test'")
debug = flag.Bool("debug", false, "Enable debug output")
coverprof = flag.String("coverprofile", "", "If supplied, use a go cover profile (comma separated)")
covermode = flag.String("covermode", "count", "sent as covermode argument to go test")
repotoken = flag.String("repotoken", os.Getenv("COVERALLS_TOKEN"), "Repository Token on coveralls")
endpoint = flag.String("endpoint", "https://coveralls.io", "Hostname to submit Coveralls data to")
service = flag.String("service", "travis-ci", "The CI service or other environment in which the test suite was run. ")
shallow = flag.Bool("shallow", false, "Shallow coveralls internal server errors")
ignore = flag.String("ignore", "", "Comma separated files to ignore")
)
// usage supplants package flag's Usage variable
var usage = func() {
cmd := os.Args[0]
// fmt.Fprintf(os.Stderr, "Usage of %s:\n", cmd)
s := "Usage: %s [options]\n"
fmt.Fprintf(os.Stderr, s, cmd)
flag.PrintDefaults()
}
// A SourceFile represents a source code file and its coverage data for a
// single job.
type SourceFile struct {
Name string `json:"name"` // File path of this source file
Source string `json:"source"` // Full source code of this file
Coverage []interface{} `json:"coverage"` // Requires both nulls and integers
}
// A Job represents the coverage data from a single run of a test suite.
type Job struct {
RepoToken *string `json:"repo_token,omitempty"`
ServiceJobId string `json:"service_job_id"`
ServicePullRequest string `json:"service_pull_request,omitempty"`
ServiceName string `json:"service_name"`
SourceFiles []*SourceFile `json:"source_files"`
Git *Git `json:"git,omitempty"`
RunAt time.Time `json:"run_at"`
}
// A Response is returned by the Coveralls.io API.
type Response struct {
Message string `json:"message"`
URL string `json:"url"`
Error bool `json:"error"`
}
// getPkgs returns packages for mesuring coverage. Returned packages doesn't
// contain vendor packages.
func getPkgs(pkg string) ([]string, error) {
if pkg == "" {
pkg = "./..."
}
out, err := exec.Command("go", "list", pkg).CombinedOutput()
if err != nil {
return nil, err
}
allPkgs := strings.Split(strings.Trim(string(out), "\n"), "\n")
pkgs := make([]string, 0, len(allPkgs))
for _, p := range allPkgs {
if !strings.Contains(p, "/vendor/") {
pkgs = append(pkgs, p)
}
}
return pkgs, nil
}
func getCoverage() ([]*SourceFile, error) {
if *coverprof != "" {
return parseCover(*coverprof)
}
// pkgs is packages to run tests and get coverage.
pkgs, err := getPkgs(*pkg)
if err != nil {
return nil, err
}
coverpkg := fmt.Sprintf("-coverpkg=%s", strings.Join(pkgs, ","))
var pfss [][]*cover.Profile
for _, line := range pkgs {
f, err := ioutil.TempFile("", "goveralls")
if err != nil {
return nil, err
}
f.Close()
cmd := exec.Command("go")
args := []string{"go", "test", "-covermode", *covermode, "-coverprofile", f.Name(), coverpkg}
if *verbose {
args = append(args, "-v")
}
args = append(args, extraFlags...)
args = append(args, line)
cmd.Args = args
b, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("%v: %v", err, string(b))
}
pfs, err := cover.ParseProfiles(f.Name())
if err != nil {
return nil, err
}
err = os.Remove(f.Name())
if err != nil {
return nil, err
}
pfss = append(pfss, pfs)
}
sourceFiles, err := toSF(mergeProfs(pfss))
if err != nil {
return nil, err
}
return sourceFiles, nil
}
var vscDirs = []string{".git", ".hg", ".bzr", ".svn"}
func findRepositoryRoot(dir string) (string, bool) {
for _, vcsdir := range vscDirs {
if d, err := os.Stat(filepath.Join(dir, vcsdir)); err == nil && d.IsDir() {
return dir, true
}
}
nextdir := filepath.Dir(dir)
if nextdir == dir {
return "", false
}
return findRepositoryRoot(nextdir)
}
func getCoverallsSourceFileName(name string) string {
if dir, ok := findRepositoryRoot(name); !ok {
return name
} else {
filename := strings.TrimPrefix(name, dir+string(os.PathSeparator))
return filename
}
}
func process() error {
log.SetFlags(log.Ltime | log.Lshortfile)
//
// Parse Flags
//
flag.Usage = usage
flag.Var(&extraFlags, "flags", "extra flags to the tests")
flag.Parse()
if len(flag.Args()) > 0 {
flag.Usage()
os.Exit(1)
}
//
// Setup PATH environment variable
//
paths := filepath.SplitList(os.Getenv("PATH"))
if goroot := os.Getenv("GOROOT"); goroot != "" {
paths = append(paths, filepath.Join(goroot, "bin"))
}
if gopath := os.Getenv("GOPATH"); gopath != "" {
for _, path := range filepath.SplitList(gopath) {
paths = append(paths, filepath.Join(path, "bin"))
}
}
os.Setenv("PATH", strings.Join(paths, string(filepath.ListSeparator)))
//
// Initialize Job
//
var jobId string
if travisJobId := os.Getenv("TRAVIS_JOB_ID"); travisJobId != "" {
jobId = travisJobId
} else if circleCiJobId := os.Getenv("CIRCLE_BUILD_NUM"); circleCiJobId != "" {
jobId = circleCiJobId
} else if appveyorJobId := os.Getenv("APPVEYOR_JOB_ID"); appveyorJobId != "" {
jobId = appveyorJobId
}
if *repotoken == "" {
repotoken = nil // remove the entry from json
}
var pullRequest string
if prNumber := os.Getenv("CIRCLE_PR_NUMBER"); prNumber != "" {
// for Circle CI (pull request from forked repo)
pullRequest = prNumber
} else if prNumber := os.Getenv("TRAVIS_PULL_REQUEST"); prNumber != "" && prNumber != "false" {
pullRequest = prNumber
} else if prURL := os.Getenv("CI_PULL_REQUEST"); prURL != "" {
// for Circle CI
pullRequest = regexp.MustCompile(`[0-9]+$`).FindString(prURL)
} else if prNumber := os.Getenv("APPVEYOR_PULL_REQUEST_NUMBER"); prNumber != "" {
pullRequest = prNumber
}
sourceFiles, err := getCoverage()
if err != nil {
return err
}
j := Job{
RunAt: time.Now(),
RepoToken: repotoken,
ServicePullRequest: pullRequest,
Git: collectGitInfo(),
SourceFiles: sourceFiles,
}
// Only include a job ID if it's known, otherwise, Coveralls looks
// for the job and can't find it.
if jobId != "" {
j.ServiceJobId = jobId
j.ServiceName = *service
}
// Ignore files
if len(*ignore) > 0 {
patterns := strings.Split(*ignore, ",")
for i, pattern := range patterns {
patterns[i] = strings.TrimSpace(pattern)
}
var files []*SourceFile
Files:
for _, file := range j.SourceFiles {
for _, pattern := range patterns {
match, err := filepath.Match(pattern, file.Name)
if err != nil {
return err
}
if match {
fmt.Printf("ignoring %s\n", file.Name)
continue Files
}
}
files = append(files, file)
}
j.SourceFiles = files
}
if *debug {
b, err := json.MarshalIndent(j, "", " ")
if err != nil {
return err
}
log.Printf("Posting data: %s", b)
}
b, err := json.Marshal(j)
if err != nil {
return err
}
params := make(url.Values)
params.Set("json", string(b))
res, err := http.PostForm(*endpoint+"/api/v1/jobs", params)
if err != nil {
return err
}
defer res.Body.Close()
bodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("Unable to read response body from coveralls: %s", err)
}
if res.StatusCode >= http.StatusInternalServerError && *shallow {
fmt.Println("coveralls server failed internally")
return nil
}
if res.StatusCode != 200 {
return fmt.Errorf("Bad response status from coveralls: %d\n%s", res.StatusCode, bodyBytes)
}
var response Response
if err = json.Unmarshal(bodyBytes, &response); err != nil {
return fmt.Errorf("Unable to unmarshal response JSON from coveralls: %s\n%s", err, bodyBytes)
}
if response.Error {
return errors.New(response.Message)
}
fmt.Println(response.Message)
fmt.Println(response.URL)
return nil
}
func main() {
if err := process(); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
}