From f47adc9ea8f16544a023ea9b67d1ed320750c5e7 Mon Sep 17 00:00:00 2001
From: Arba Sasmoyo <arba.sasmoyo@gmail.com>
Date: Mon, 13 Nov 2017 03:00:18 +0700
Subject: [PATCH] .dockerignore, internal/build: Read git information directly
 from file (#15458)

* .dockerignore, internal/build: Read git information directly from file

This commit changes the way of retrieving git commit and branch for build
environment from running git command to reading git files directly.

This commit also adds required git files into Docker build context.

fixes: #15346

* .dockerignore: workaround for including some files in .git
---
 .dockerignore          |  3 +++
 internal/build/env.go  | 13 ++++++++-----
 internal/build/util.go | 10 ++++++++++
 3 files changed, 21 insertions(+), 5 deletions(-)

diff --git a/.dockerignore b/.dockerignore
index 07eab0766..751ff2a0c 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -1,4 +1,7 @@
 **/.git
+/.git
+!/.git/HEAD
+!/.git/refs/heads
 **/*_test.go
 
 build/_workspace
diff --git a/internal/build/env.go b/internal/build/env.go
index c47681ebe..793242fcf 100644
--- a/internal/build/env.go
+++ b/internal/build/env.go
@@ -82,18 +82,21 @@ func Env() Environment {
 // LocalEnv returns build environment metadata gathered from git.
 func LocalEnv() Environment {
 	env := applyEnvFlags(Environment{Name: "local", Repo: "ethereum/go-ethereum"})
-	if _, err := os.Stat(".git"); err != nil {
+	head := ReadGitFile("HEAD")
+	if splits := strings.Split(head, " "); len(splits) == 2 {
+		head = splits[1]
+	} else {
 		return env
 	}
 	if env.Commit == "" {
-		env.Commit = RunGit("rev-parse", "HEAD")
+		env.Commit = ReadGitFile(head)
 	}
 	if env.Branch == "" {
-		if b := RunGit("rev-parse", "--abbrev-ref", "HEAD"); b != "HEAD" {
-			env.Branch = b
+		if head != "HEAD" {
+			env.Branch = strings.TrimLeft(head, "refs/heads/")
 		}
 	}
-	if env.Tag == "" {
+	if info, err := os.Stat(".git/objects"); err == nil && info.IsDir() && env.Tag == "" {
 		env.Tag = firstLine(RunGit("tag", "-l", "--points-at", "HEAD"))
 	}
 	return env
diff --git a/internal/build/util.go b/internal/build/util.go
index ade9cbe93..91465c419 100644
--- a/internal/build/util.go
+++ b/internal/build/util.go
@@ -25,6 +25,7 @@ import (
 	"log"
 	"os"
 	"os/exec"
+	"path"
 	"path/filepath"
 	"runtime"
 	"strings"
@@ -88,6 +89,15 @@ func RunGit(args ...string) string {
 	return strings.TrimSpace(stdout.String())
 }
 
+// ReadGitFile returns content of file in .git directory.
+func ReadGitFile(file string) string {
+	content, err := ioutil.ReadFile(path.Join(".git", file))
+	if err != nil {
+		return ""
+	}
+	return strings.TrimSpace(string(content))
+}
+
 // Render renders the given template file into outputFile.
 func Render(templateFile, outputFile string, outputPerm os.FileMode, x interface{}) {
 	tpl := template.Must(template.ParseFiles(templateFile))
-- 
GitLab