git-combine: create synthetic origin repo in tmpdir (#49536)

As part of bazel migration we stopped using the checked out sourcegraph
repo and introduced this synthetic origin repo. This commit makes it so
we only use the synthetic repo if we don't have access to a local
repository.

Test Plan: Ran inside of the sg repo and outside of a git repo. In the
sg repo you can see in the output it doesn't create a repo and it takes
longer for it to run git fetch (since it fetches 100 real commits
instead of 2 synthetic ones).

``` shell
cd internal/cmd/git-combine
go test -c .
./git-combine.test -test.v

mv git-combine.test /tmp
cd /tmp
./git-combine.test -test.v
```
This commit is contained in:
Keegan Carruthers-Smith 2023-03-16 18:59:04 +02:00 committed by GitHub
parent 2672c3ff72
commit ad96f2ea76
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -7,6 +7,7 @@ import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/go-git/go-git/v5/plumbing"
@ -17,38 +18,47 @@ import (
func TestCombine(t *testing.T) {
tmp := t.TempDir()
origin := filepath.Join(tmp, "origin")
dir := filepath.Join(tmp, "combined-repo.git")
// If we are running inside of the sourcegraph repo, use that as the
// origin rather than using a small synthetic repo. In practice this means
// when using go test we use the sg repo, in bazel we use a tiny synthetic
// repo.
if out, err := exec.Command("git", "rev-parse", "--show-toplevel").Output(); err == nil {
origin = strings.TrimSpace(string(out))
t.Log("using local repository instead of synthetic repo", origin)
}
setupPath := filepath.Join(tmp, "setup.sh")
if err := os.WriteFile(setupPath, []byte(`#!/usr/bin/env bash
set -ex
mkdir origin
cd origin
git init
## Setup origin repo if it doesn't exist.
# needed in CI, sandbox is really strict
git config user.email test@sourcegraph.com
if [ ! -d "$ORIGIN" ]; then
mkdir -p "$ORIGIN"
cd "$ORIGIN"
git init
echo "foobar" > README.md
git add README.md
git commit -m "initial commit"
echo "foobar" >> README.md
git add README.md
git commit -m "second commit"
git config user.email test@sourcegraph.com
echo "foobar" > README.md
git add README.md
git commit -m "initial commit"
echo "foobar" >> README.md
git add README.md
git commit -m "second commit"
fi
repo=$(git rev-parse --show-toplevel)
cd ..
## Setup git-combine repo
mkdir -p "$DIR"
cd "$DIR"
git init --bare .
# needed in CI, sandbox is really strict
git config user.email test@sourcegraph.com
git remote add --no-tags sourcegraph "$repo"
git remote add --no-tags sourcegraph "$ORIGIN"
git config --replace-all remote.origin.fetch '+HEAD:refs/remotes/sourcegraph/master'
git fetch --depth 100 sourcegraph
@ -57,7 +67,12 @@ git fetch --depth 100 sourcegraph
}
cmd := exec.Command("sh", setupPath)
cmd.Env = append(os.Environ(), "DIR="+dir)
cmd.Dir = tmp
cmd.Env = append(
os.Environ(),
"DIR="+dir,
"ORIGIN="+origin,
)
if testing.Verbose() {
cmd.Stderr = os.Stderr
}