github.com/ethereum/go-ethereum@v1.14.3/internal/build/env.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package build
    18  
    19  import (
    20  	"flag"
    21  	"fmt"
    22  	"os"
    23  	"regexp"
    24  	"strconv"
    25  	"strings"
    26  	"time"
    27  )
    28  
    29  var (
    30  	// These flags override values in build env.
    31  	GitCommitFlag     = flag.String("git-commit", "", `Overrides git commit hash embedded into executables`)
    32  	GitBranchFlag     = flag.String("git-branch", "", `Overrides git branch being built`)
    33  	GitTagFlag        = flag.String("git-tag", "", `Overrides git tag being built`)
    34  	BuildnumFlag      = flag.String("buildnum", "", `Overrides CI build number`)
    35  	PullRequestFlag   = flag.Bool("pull-request", false, `Overrides pull request status of the build`)
    36  	CronJobFlag       = flag.Bool("cron-job", false, `Overrides cron job status of the build`)
    37  	UbuntuVersionFlag = flag.String("ubuntu", "", `Sets the ubuntu version being built for`)
    38  )
    39  
    40  // Environment contains metadata provided by the build environment.
    41  type Environment struct {
    42  	CI                        bool
    43  	Name                      string // name of the environment
    44  	Repo                      string // name of GitHub repo
    45  	Commit, Date, Branch, Tag string // Git info
    46  	Buildnum                  string
    47  	UbuntuVersion             string // Ubuntu version being built for
    48  	IsPullRequest             bool
    49  	IsCronJob                 bool
    50  }
    51  
    52  func (env Environment) String() string {
    53  	return fmt.Sprintf("%s env (commit:%s date:%s branch:%s tag:%s buildnum:%s pr:%t)",
    54  		env.Name, env.Commit, env.Date, env.Branch, env.Tag, env.Buildnum, env.IsPullRequest)
    55  }
    56  
    57  // Env returns metadata about the current CI environment, falling back to LocalEnv
    58  // if not running on CI.
    59  func Env() Environment {
    60  	switch {
    61  	case os.Getenv("CI") == "true" && os.Getenv("TRAVIS") == "true":
    62  		commit := os.Getenv("TRAVIS_PULL_REQUEST_SHA")
    63  		if commit == "" {
    64  			commit = os.Getenv("TRAVIS_COMMIT")
    65  		}
    66  		return Environment{
    67  			CI:            true,
    68  			Name:          "travis",
    69  			Repo:          os.Getenv("TRAVIS_REPO_SLUG"),
    70  			Commit:        commit,
    71  			Date:          getDate(commit),
    72  			Branch:        os.Getenv("TRAVIS_BRANCH"),
    73  			Tag:           os.Getenv("TRAVIS_TAG"),
    74  			Buildnum:      os.Getenv("TRAVIS_BUILD_NUMBER"),
    75  			IsPullRequest: os.Getenv("TRAVIS_PULL_REQUEST") != "false",
    76  			IsCronJob:     os.Getenv("TRAVIS_EVENT_TYPE") == "cron",
    77  		}
    78  	case os.Getenv("CI") == "True" && os.Getenv("APPVEYOR") == "True":
    79  		commit := os.Getenv("APPVEYOR_PULL_REQUEST_HEAD_COMMIT")
    80  		if commit == "" {
    81  			commit = os.Getenv("APPVEYOR_REPO_COMMIT")
    82  		}
    83  		return Environment{
    84  			CI:            true,
    85  			Name:          "appveyor",
    86  			Repo:          os.Getenv("APPVEYOR_REPO_NAME"),
    87  			Commit:        commit,
    88  			Date:          getDate(commit),
    89  			Branch:        os.Getenv("APPVEYOR_REPO_BRANCH"),
    90  			Tag:           os.Getenv("APPVEYOR_REPO_TAG_NAME"),
    91  			Buildnum:      os.Getenv("APPVEYOR_BUILD_NUMBER"),
    92  			IsPullRequest: os.Getenv("APPVEYOR_PULL_REQUEST_NUMBER") != "",
    93  			IsCronJob:     os.Getenv("APPVEYOR_SCHEDULED_BUILD") == "True",
    94  		}
    95  	default:
    96  		return LocalEnv()
    97  	}
    98  }
    99  
   100  // LocalEnv returns build environment metadata gathered from git.
   101  func LocalEnv() Environment {
   102  	env := applyEnvFlags(Environment{Name: "local", Repo: "ethereum/go-ethereum"})
   103  
   104  	head := readGitFile("HEAD")
   105  	if fields := strings.Fields(head); len(fields) == 2 {
   106  		head = fields[1]
   107  	} else {
   108  		// In this case we are in "detached head" state
   109  		// see: https://git-scm.com/docs/git-checkout#_detached_head
   110  		// Additional check required to verify, that file contains commit hash
   111  		commitRe, _ := regexp.Compile("^([0-9a-f]{40})$")
   112  		if commit := commitRe.FindString(head); commit != "" && env.Commit == "" {
   113  			env.Commit = commit
   114  		}
   115  		return env
   116  	}
   117  	if env.Commit == "" {
   118  		env.Commit = readGitFile(head)
   119  	}
   120  	env.Date = getDate(env.Commit)
   121  	if env.Branch == "" {
   122  		if head != "HEAD" {
   123  			env.Branch = strings.TrimPrefix(head, "refs/heads/")
   124  		}
   125  	}
   126  	if info, err := os.Stat(".git/objects"); err == nil && info.IsDir() && env.Tag == "" {
   127  		env.Tag = firstLine(RunGit("tag", "-l", "--points-at", "HEAD"))
   128  	}
   129  	return env
   130  }
   131  
   132  func firstLine(s string) string {
   133  	return strings.Split(s, "\n")[0]
   134  }
   135  
   136  func getDate(commit string) string {
   137  	if commit == "" {
   138  		return ""
   139  	}
   140  	out := RunGit("show", "-s", "--format=%ct", commit)
   141  	if out == "" {
   142  		return ""
   143  	}
   144  	date, err := strconv.ParseInt(strings.TrimSpace(out), 10, 64)
   145  	if err != nil {
   146  		panic(fmt.Sprintf("failed to parse git commit date: %v", err))
   147  	}
   148  	return time.Unix(date, 0).Format("20060102")
   149  }
   150  
   151  func applyEnvFlags(env Environment) Environment {
   152  	if !flag.Parsed() {
   153  		panic("you need to call flag.Parse before Env or LocalEnv")
   154  	}
   155  	if *GitCommitFlag != "" {
   156  		env.Commit = *GitCommitFlag
   157  	}
   158  	if *GitBranchFlag != "" {
   159  		env.Branch = *GitBranchFlag
   160  	}
   161  	if *GitTagFlag != "" {
   162  		env.Tag = *GitTagFlag
   163  	}
   164  	if *BuildnumFlag != "" {
   165  		env.Buildnum = *BuildnumFlag
   166  	}
   167  	if *PullRequestFlag {
   168  		env.IsPullRequest = true
   169  	}
   170  	if *CronJobFlag {
   171  		env.IsCronJob = true
   172  	}
   173  	if *UbuntuVersionFlag != "" {
   174  		env.UbuntuVersion = *UbuntuVersionFlag
   175  	}
   176  	return env
   177  }