diff --git a/.fdignore b/.fdignore new file mode 100644 index 0000000..d383c56 --- /dev/null +++ b/.fdignore @@ -0,0 +1 @@ +testdata diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 0325ab0..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Release -on: - push: - branches: - - main - workflow_dispatch: -jobs: - release: - name: release - runs-on: ubuntu-22.04 - permissions: - contents: write - issues: write - pull-requests: write - steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - persist-credentials: false - - uses: actions/setup-node@v3 - with: - node-version: lts/* - - run: | - npm install @semantic-release/git @semantic-release/changelog -D - npx semantic-release - env: - GH_TOKEN: ${{ secrets.BGPS_CI_TOKEN }} - GITHUB_TOKEN: ${{ secrets.BGPS_CI_TOKEN }} - - diff --git a/.github/workflows/test_release.yml b/.github/workflows/test_release.yml new file mode 100644 index 0000000..9bf3227 --- /dev/null +++ b/.github/workflows/test_release.yml @@ -0,0 +1,76 @@ +name: test_release +on: + push: + branches: + - main + pull_request: + workflow_dispatch: + +permissions: + contents: write + issues: write + pull-requests: write + +jobs: + test: + runs-on: ubuntu-22.04 + name: test + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + + - name: golangci-lint + uses: golangci/golangci-lint-action@v4 + with: + version: latest + + - name: test + run: | + make test + + + release: + if: (github.ref == 'refs/heads/main') && (github.repository_owner == 'mikesmithgh') + runs-on: ubuntu-22.04 + name: release + needs: + - test + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + + - name: Setup Node + uses: actions/setup-node@v3 + with: + node-version: lts/* + + - name: Setup GoReleaser + uses: goreleaser/goreleaser-action@v5 + with: + distribution: goreleaser + version: latest + install-only: true + + - name: Semantic Release + run: | + npm install @semantic-release/git @semantic-release/changelog @semantic-release/exec -D + npx semantic-release + env: + GH_TOKEN: ${{ secrets.BGPS_CI_TOKEN }} + GITHUB_TOKEN: ${{ secrets.BGPS_CI_TOKEN }} diff --git a/.gitignore b/.gitignore index 1377554..bf347d3 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,6 @@ *.swp +tmp/ +dist/ +node_modules/ +package-lock.json +package.json diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..11b8b99 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,31 @@ +linters: + enable: + - errcheck + - gosimple + - govet + - ineffassign + - staticcheck + - unused + - errorlint + - gofmt + - goimports + - gosec + - whitespace + - bodyclose + - dogsled + - durationcheck + - errorlint + - exhaustive + - exportloopref + - goconst + - gocritic + - gosec + - importas + - misspell + - nilerr + - gofumpt + +linters-settings: + gosec: + excludes: + - G204 diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..4caaf9a --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,27 @@ +version: 1 + +builds: + - env: + - CGO_ENABLED=0 + goos: + - linux + - windows + - darwin + +archives: + - format: tar.gz + # this name template makes the OS and Arch compatible with the results of `uname`. + name_template: >- + {{ .ProjectName }}_ + {{- title .Os }}_ + {{- if eq .Arch "amd64" }}x86_64 + {{- else if eq .Arch "386" }}i386 + {{- else }}{{ .Arch }}{{ end }} + {{- if .Arm }}v{{ .Arm }}{{ end }} + # use zip for windows archives + format_overrides: + - goos: windows + format: zip + +# yaml-language-server: $schema=https://goreleaser.com/static/schema.json +# vim: set ts=2 sw=2 tw=0 fo=cnqoj diff --git a/.releaserc b/.releaserc index 9342315..908434d 100644 --- a/.releaserc +++ b/.releaserc @@ -19,8 +19,10 @@ } ], [ - "@semantic-release/github" + "@semantic-release/exec", + { + "publishCmd": "./scripts/release_publish.sh \"${nextRelease.notes}\"" + } ] ] } - diff --git a/.rgignore b/.rgignore new file mode 100644 index 0000000..d383c56 --- /dev/null +++ b/.rgignore @@ -0,0 +1 @@ +testdata diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 02fe808..0000000 --- a/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM ubuntu - -RUN useradd -ms /bin/bash jdoe -RUN printf "root:root\njdoe:jdoe" | chpasswd - -RUN apt-get update -RUN apt-get install -y vim git - -USER jdoe -RUN git clone https://github.com/mjsmith1028/bgps.git /home/jdoe/bgps -RUN git config --global user.name "John Doe" -RUN git config --global user.email "jdoe@docker.com" -RUN ln -s /home/jdoe/bgps/examples/mine /home/jdoe/.bgps_config - -USER root -RUN echo "source /etc/bash_completion.d/git-prompt" | tee -a /root/.bashrc /home/jdoe/.bashrc -RUN ln -s /home/jdoe/bgps/examples/mine /root/.bgps_config -RUN ln -s /home/jdoe/bgps/bgps /usr/local/bin/bgps - -ENV PROMPT_COMMAND "source bgps" - -USER jdoe -WORKDIR /home/jdoe/bgps diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..4af7c6b --- /dev/null +++ b/Makefile @@ -0,0 +1,16 @@ +.PHONY: help +help: + @echo "==> describe make commands" + @echo "" + @echo "build ==> build bgps for current GOOS and GOARCH" + @echo "test ==> run tests" + +.PHONY: build +build: + @goreleaser build --single-target --clean --snapshot + +.PHONY: test +test: + # TODO: temporary hack return 0 for first release + @echo skipping tests + diff --git a/README.md b/README.md index c646126..e2a7156 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Better Git Prompt String > [!WARNING]\ -> 03/16/2024: bgps is actively undergoing a major v2 rewrite in ![go](https://img.shields.io/badge/Go-00ADD8?style=flat-square&logo=go&logoColor=white) +> 03/20/2024: bgps is actively undergoing a major v2 rewrite in ![go](https://img.shields.io/badge/Go-00ADD8?style=flat-square&logo=go&logoColor=white) > > This is a breaking change that will simplify and improve maintainability of bgps > @@ -160,3 +160,4 @@ bgps has been tested with the following: - Operating System: 20.6.0 Darwin Kernel Version 20.6.0 - Bash: 5.1.16(1)-release (x86_64-apple-darwin20.6.0) - Git: 2.37.0 + diff --git a/examples/blue_time b/examples/blue_time deleted file mode 100644 index f2b95f9..0000000 --- a/examples/blue_time +++ /dev/null @@ -1,4 +0,0 @@ -PS1_FORMAT="\[\033[0;34m\][\@]\[\033[0m\] \u@\h%( %s%)\[\033[0m\] \$ " -TEXT_COLOR="\[\033[0;36m\]" -GIT_COLOR_ENABLED="true" -GIT_COLOR_CLEAN="\[\033[5;94m\]" diff --git a/examples/colorful b/examples/colorful deleted file mode 100644 index a60f7d0..0000000 --- a/examples/colorful +++ /dev/null @@ -1,11 +0,0 @@ -PS1_FORMAT="\[\033[3;35m\]\t\[\033[0m\]-\[\033[3;97m\]\h:\[\033[33;1m\]\w%( %s%)\[\033[m\] -> " -TEXT_COLOR="\[\033[0;32m\]" -GIT_COLOR_ENABLED="true" -GIT_COLOR_CLEAN="\[\033[1;92m\]" -GIT_COLOR_CONFLICT="\[\033[1;43m\]" -GIT_COLOR_DIRTY="\[\033[1;91m\]" -GIT_COLOR_UNTRACKED="\[\033[1;90m\]" -GIT_PREFIX=":) " -GIT_AHEAD="+%s" -GIT_BEHIND="-%s" -GIT_DIVERGED="+%a -%b" diff --git a/examples/mine b/examples/mine deleted file mode 100644 index a6077c2..0000000 --- a/examples/mine +++ /dev/null @@ -1,12 +0,0 @@ -PS1_FORMAT="$(_bgps_ps1 -u \u -h \h -D \D{%Y-%m-%dT%T} -s \s -V \V -w \w)\[\033[0m\]%BGPS_GIT_STATUS $(_code_ps1)\n$([[ $(type -t iterm2_prompt_mark) == 'function' ]] && echo \[$(iterm2_prompt_mark)\])$(((${EUID})) && echo '\[\033[0;92m\]' || echo '\[\033[0;91m\]')$(printf "\x1b[%s;2;%sm" '38' '167;192;128')\u@\h $(printf "\x1b[%s;2;%sm" '38' '131;165;152')\$ " -# PS1_FORMAT="$ " -GIT_COLOR_ENABLED="true" -GIT_PREFIX="  " -GIT_AHEAD="↑[%s]" -GIT_BEHIND="↓[%s]" -GIT_DIVERGED="↕ ↑[%a] ↓[%b]" -GIT_COLOR_CLEAN=$(printf "\x1b[%s;2;%sm" '38' '167;192;128') -GIT_COLOR_NO_UPSTREAM=$(printf "\x1b[%s;2;%sm" '38' '146;131;116')" -GIT_COLOR_UNTRACKED=$(printf "\x1b[%s;2;%sm" '38' '211;134;155') -GIT_COLOR_DIRTY=$(printf "\x1b[%s;2;%sm" '38' '255;105;97') -GIT_COLOR_CONFLICT=$(printf "\x1b[%s;2;%sm" '38' '219;188;95') diff --git a/examples/simple b/examples/simple deleted file mode 100644 index 92fe2c3..0000000 --- a/examples/simple +++ /dev/null @@ -1 +0,0 @@ -PS1_FORMAT="%(%s %)\$ " diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..7415c18 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module github.com/mikesmithgh/bgps + +go 1.22.0 + +require github.com/pelletier/go-toml/v2 v2.1.1 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..532513b --- /dev/null +++ b/go.sum @@ -0,0 +1,18 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI= +github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/integration/bgps_test.go b/integration/bgps_test.go new file mode 100644 index 0000000..99e72ca --- /dev/null +++ b/integration/bgps_test.go @@ -0,0 +1,94 @@ +package integration + +import ( + "os" + "os/exec" + "path/filepath" + "testing" +) + +func TestBGPS(t *testing.T) { + tests := []struct { + dir string + input []string + expected string + environ []string + }{ + {"bare", []string{"--config=NONE"}, "\x1b[90m \ue0a0 BARE:main\x1b[0m", nil}, + {"no_upstream", []string{"--config=NONE"}, "\x1b[90m \ue0a0 main\x1b[0m", nil}, + {"no_upstream_remote", []string{"--config=NONE"}, "\x1b[90m \ue0a0 main → mikesmithgh/test/main\x1b[0m", nil}, + {"git_dir", []string{"--config=NONE"}, "\x1b[90m \ue0a0 GIT_DIR!\x1b[0m", nil}, + {"clean", []string{"--config=NONE"}, "\x1b[32m \ue0a0 main\x1b[0m", nil}, + {"tag", []string{"--config=NONE"}, "\x1b[90m \ue0a0 (v1.0.0)\x1b[0m", nil}, + {"commit", []string{"--config=NONE"}, "\x1b[90m \ue0a0 (24afc95)\x1b[0m", nil}, + {"dirty", []string{"--config=NONE"}, "\x1b[31m \ue0a0 main *\x1b[0m", nil}, + {"dirty_staged", []string{"--config=NONE"}, "\x1b[31m \ue0a0 main *\x1b[0m", nil}, + {"conflict_ahead", []string{"--config=NONE"}, "\x1b[33m \ue0a0 main ↑[1]\x1b[0m", nil}, + {"conflict_behind", []string{"--config=NONE"}, "\x1b[33m \ue0a0 main ↓[1]\x1b[0m", nil}, + {"conflict_diverged", []string{"--config=NONE"}, "\x1b[33m \ue0a0 main ↕ ↑[1] ↓[1]\x1b[0m", nil}, + {"untracked", []string{"--config=NONE"}, "\x1b[35m \ue0a0 main *\x1b[0m", nil}, + {"sparse", []string{"--config=NONE"}, "\x1b[32m \ue0a0 main|SPARSE\x1b[0m", nil}, + {"sparse_merge_conflict", []string{"--config=NONE"}, "\x1b[31m \ue0a0 main|SPARSE|MERGING|CONFLICT *↕ ↑[1] ↓[1]\x1b[0m", nil}, + + // rebase merge + {"rebase_i", []string{"--config=NONE"}, "\x1b[34m \ue0a0 main|REBASE-i 1/1\x1b[0m", nil}, + {"rebase_m", []string{"--config=NONE"}, "\x1b[34m \ue0a0 main|REBASE-m 1/1\x1b[0m", nil}, + // rebase apply + {"am_rebase", []string{"--config=NONE"}, "\x1b[34m \ue0a0 (b69e688)|AM/REBASE 1/1\x1b[0m", nil}, + {"am", []string{"--config=NONE"}, "\x1b[34m \ue0a0 (b69e688)|AM 1/1\x1b[0m", nil}, + {"rebase", []string{"--config=NONE"}, "\x1b[34m \ue0a0 main|REBASE 1/1\x1b[0m", nil}, + // merge + {"merge_conflict", []string{"--config=NONE"}, "\x1b[31m \ue0a0 main|MERGING|CONFLICT *↕ ↑[1] ↓[1]\x1b[0m", nil}, + {"merge", []string{"--config=NONE"}, "\x1b[35m \ue0a0 main|MERGING *↕ ↑[1] ↓[1]\x1b[0m", nil}, + // cherry pick + {"cherry_pick_conflict", []string{"--config=NONE"}, "\x1b[31m \ue0a0 main|CHERRY-PICKING|CONFLICT *↕ ↑[1] ↓[1]\x1b[0m", nil}, + {"cherry_pick", []string{"--config=NONE"}, "\x1b[35m \ue0a0 main|CHERRY-PICKING *↕ ↑[1] ↓[1]\x1b[0m", nil}, + // revert + {"revert_conflict", []string{"--config=NONE"}, "\x1b[31m \ue0a0 main|REVERTING|CONFLICT *↕ ↑[2] ↓[1]\x1b[0m", nil}, + {"revert", []string{"--config=NONE"}, "\x1b[31m \ue0a0 main|REVERTING *↕ ↑[2] ↓[1]\x1b[0m", nil}, + // bisect + {"bisect", []string{"--config=NONE"}, "\x1b[34m \ue0a0 main|BISECTING ↓[1]\x1b[0m", nil}, + + // formatting + {"clean", []string{"--config=NONE", "--color-enabled=false"}, " \ue0a0 main", nil}, + {"clean", []string{"--config=NONE", "--color-enabled=false", "--prompt-prefix= start "}, " start main", nil}, + {"clean", []string{"--config=NONE", "--color-enabled=false", "--prompt-suffix= stop"}, " \ue0a0 main stop", nil}, + {"conflict_ahead", []string{"--config=NONE", "--color-enabled=false", "--ahead-format=ahead by %d"}, " \ue0a0 main ahead by 1", nil}, + {"conflict_behind", []string{"--config=NONE", "--color-enabled=false", "--behind-format=behind by %d"}, " \ue0a0 main behind by 1", nil}, + {"conflict_diverged", []string{"--config=NONE", "--color-enabled=false", "--diverged-format=ahead by %d behind by %d"}, " \ue0a0 main ahead by 1 behind by 1", nil}, + {"no_upstream_remote", []string{"--config=NONE", "--color-enabled=false", "--no-upstream-remote-format= upstream=[repo: %s branch: %s]"}, " \ue0a0 main upstream=[repo: mikesmithgh/test branch: main]", nil}, + + // color overrides + {"clean", []string{"--config=../configs/color_overrides.toml"}, "\x1b[38;2;230;238;4m \ue0a0 main\x1b[0m", nil}, + {"no_upstream", []string{"--config=../configs/color_overrides.toml"}, "\x1b[30m\x1b[47m \ue0a0 main\x1b[0m", nil}, + {"dirty", []string{"--config=../configs/color_overrides.toml"}, "\x1b[48;2;179;5;89m \ue0a0 main *\x1b[0m", nil}, + {"conflict_ahead", []string{"--config=../configs/color_overrides.toml"}, "\x1b[38;2;252;183;40m \ue0a0 main ↑[1]\x1b[0m", nil}, + {"untracked", []string{"--config=../configs/color_overrides.toml"}, "\x1b[38;2;255;0;0m\x1b[48;2;22;242;170m \ue0a0 main *\x1b[0m", nil}, + {"bisect", []string{}, "\x1b[48;2;204;204;255m\x1b[35m \ue0a0 main|BISECTING ↓[1]\x1b[0m", []string{"BGPS_CONFIG=../configs/color_overrides.toml"}}, + + // config errors + {"clean", []string{"--config=/fromparam/does/not/exist"}, "\x1b[31m bgps error(read config): open /fromparam/does/not/exist: no such file or directory\x1b[0m", nil}, + {"configs", []string{}, "\x1b[31m bgps error(read config): open /fromenvvar/does/not/exist: no such file or directory\x1b[0m", []string{"BGPS_CONFIG=/fromenvvar/does/not/exist"}}, + {"configs", []string{"--config=invalid_syntax.toml"}, "\x1b[31m bgps error(unmarshal config): toml: expected character =\x1b[0m", nil}, + {"configs", []string{}, "\x1b[31m bgps error(unmarshal config): toml: expected character =\x1b[0m", []string{"BGPS_CONFIG=invalid_syntax.toml"}}, + + {"norepo", []string{"--config=NONE"}, "", nil}, + } + + for _, test := range tests { + cmd := exec.Command(builtBinaryPath, test.input...) + cmd.Dir = filepath.Join(tmpDir, "testdata", test.dir) + if test.environ != nil { + cmd.Env = os.Environ() + cmd.Env = append(cmd.Env, test.environ...) + } + result, err := cmd.CombinedOutput() + if err != nil { + t.Errorf("Unexpected error: %s", err) + } + actual := string(result) + if actual != test.expected { + t.Errorf("in directory %s, %s != %s\nexpected:\n%q, \ngot:\n%q", test.dir, test.expected, actual, test.expected, actual) + } + } +} diff --git a/integration/init_test.go b/integration/init_test.go new file mode 100644 index 0000000..073a2c4 --- /dev/null +++ b/integration/init_test.go @@ -0,0 +1,64 @@ +package integration + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" +) + +var ( + builtBinaryPath string + tmpDir string +) + +func TestMain(m *testing.M) { + var err error + tmpDir, err = os.MkdirTemp("", "integration") + if err != nil { + panic("failed to create temp dir") + } + defer os.RemoveAll(tmpDir) + + builtBinaryPath = filepath.Join(tmpDir, "bgps") + + cmd := exec.Command("go", "build", "-o", builtBinaryPath, "..") + output, err := cmd.CombinedOutput() + if err != nil { + panic(fmt.Sprintf("failed to build bgps: %s, %s", output, err)) + } + + cmd = exec.Command("cp", "-r", "../testdata", tmpDir) + err = cmd.Run() + if err != nil { + panic(fmt.Sprintf("failed to copy test data: %s", err)) + } + + test_dirs, err := os.ReadDir(filepath.Join(tmpDir, "testdata")) + if err != nil { + panic(fmt.Sprintf("failed to read test data dir: %s", err)) + } + + for _, test_dir := range test_dirs { + test_dir_path := filepath.Join(tmpDir, "testdata", test_dir.Name()) + test_dir_files, err := os.ReadDir(test_dir_path) + if err != nil { + panic(fmt.Sprintf("failed to read test data file: %s", err)) + } + for _, test_dir_file := range test_dir_files { + if test_dir_file.Name() == "dot_git" { + err = os.Rename(filepath.Join(test_dir_path, "dot_git"), filepath.Join(test_dir_path, ".git")) + if err != nil { + panic(fmt.Sprintf("failed to rename test data git dir: %s", err)) + } + } + } + } + fmt.Println("=== INIT") + fmt.Println("tmpDir:", tmpDir) + fmt.Println("builtBinaryPath:", builtBinaryPath) + + code := m.Run() + defer os.Exit(code) +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..7a09f6c --- /dev/null +++ b/main.go @@ -0,0 +1,149 @@ +package main + +import ( + "flag" + "fmt" + "os" + "path" + "runtime" + "strings" + + "github.com/mikesmithgh/bgps/pkg/color" + "github.com/mikesmithgh/bgps/pkg/config" + "github.com/mikesmithgh/bgps/pkg/git" + "github.com/mikesmithgh/bgps/pkg/util" + "github.com/pelletier/go-toml/v2" +) + +var ( + configPath = flag.String("config", "", "") + promptPrefix = flag.String("prompt-prefix", " \ue0a0 ", "") + promptSuffix = flag.String("prompt-suffix", "", "") + aheadFormat = flag.String("ahead-format", "↑[%d]", "") + behindFormat = flag.String("behind-format", "↓[%d]", "") + divergedFormat = flag.String("diverged-format", "↕ ↑[%d] ↓[%d]", "") + noUpstreamRemoteFormat = flag.String("no-upstream-remote-format", " → %s/%s", "") + colorEnabled = flag.Bool("color-enabled", true, "") + colorClean = flag.String("color-clean", "green", "") + colorConflict = flag.String("color-conflict", "yellow", "") + colorDirty = flag.String("color-dirty", "red", "") + colorUntracked = flag.String("color-untracked", "magenta", "") + colorNoUpstream = flag.String("color-no-upstream", "bright-black", "") + colorMerging = flag.String("color-merging", "blue", "") +) + +func main() { + cfg := config.BgpsConfig{ + PromptPrefix: *promptPrefix, + PromptSuffix: *promptSuffix, + AheadFormat: *aheadFormat, + BehindFormat: *behindFormat, + DivergedFormat: *divergedFormat, + NoUpstreamRemoteFormat: *noUpstreamRemoteFormat, + ColorEnabled: *colorEnabled, + ColorClean: *colorClean, + ColorConflict: *colorConflict, + ColorDirty: *colorDirty, + ColorUntracked: *colorUntracked, + ColorNoUpstream: *colorNoUpstream, + ColorMerging: *colorMerging, + } + + flag.Parse() + + var bgpsConfigPath string + bgpsConfigEnv := os.Getenv("BGPS_CONFIG") + if *configPath == "" { + bgpsConfigPath = bgpsConfigEnv + } else { + bgpsConfigPath = *configPath + } + if bgpsConfigPath == "" { + xdgConfigHome := os.Getenv("XDG_CONFIG_HOME") + if xdgConfigHome == "" { + home, err := os.UserHomeDir() + if err != nil { + util.ErrMsg("user home", err, 0) + } + if runtime.GOOS == "windows" { + xdgConfigHome = path.Join(home, "AppData", "Local") + } else { + xdgConfigHome = path.Join(home, ".config") + } + } + bgpsConfigPath = path.Join(xdgConfigHome, "bgps", "config.toml") + } + + if bgpsConfigPath != "NONE" { + bgpsConfigRaw, err := os.ReadFile(bgpsConfigPath) + if err != nil && !os.IsNotExist(err) { + util.ErrMsg("read config exists", err, 0) + } + + if err != nil && (*configPath != "" || bgpsConfigEnv != "") { + util.ErrMsg("read config", err, 0) + } + + err = toml.Unmarshal(bgpsConfigRaw, &cfg) + if err != nil { + util.ErrMsg("unmarshal config", err, 0) + } + } + + flag.Visit(func(f *flag.Flag) { + switch f.Name { + case "prompt-prefix": + cfg.PromptPrefix = f.Value.String() + case "prompt-suffix": + cfg.PromptSuffix = f.Value.String() + case "ahead-format": + cfg.AheadFormat = f.Value.String() + case "behind-format": + cfg.BehindFormat = f.Value.String() + case "diverged-format": + cfg.DivergedFormat = f.Value.String() + case "no-upstream-remote-format": + cfg.NoUpstreamRemoteFormat = f.Value.String() + case "color-enabled": + cfg.ColorEnabled = f.Value.String() == f.DefValue + case "color-clean": + cfg.ColorClean = f.Value.String() + case "color-conflict": + cfg.ColorConflict = f.Value.String() + case "color-dirty": + cfg.ColorDirty = f.Value.String() + case "color-untracked": + cfg.ColorUntracked = f.Value.String() + case "color-no-upstream": + cfg.ColorUntracked = f.Value.String() + case "color-merging": + cfg.ColorMerging = f.Value.String() + } + }) + if !cfg.ColorEnabled { + color.Disable() + } + clearColor, err := color.Color("none") + if err != nil { + util.ErrMsg("color none", err, 0) + } + + gitRepo, stderr, err := git.RevParse() + if err != nil { + if strings.Contains(string(stderr), "not a git repository") { + os.Exit(0) + } + // allow other errors to pass through, the git repo may not have upstream + } + + branchInfo, err := gitRepo.BranchInfo(cfg) + if err != nil { + util.ErrMsg("branch info", err, 0) + } + branchStatus, promptColor, err := gitRepo.BranchStatus(cfg) + if err != nil { + util.ErrMsg("branch status", err, 0) + } + + fmt.Printf("%s%s%s%s%s%s", promptColor, cfg.PromptPrefix, branchInfo, branchStatus, cfg.PromptSuffix, clearColor) +} diff --git a/pkg/color/color.go b/pkg/color/color.go new file mode 100644 index 0000000..c1d7097 --- /dev/null +++ b/pkg/color/color.go @@ -0,0 +1,139 @@ +package color + +import ( + "fmt" + "strconv" + "strings" +) + +const ( + esc = "\x1b" +) + +var enabled bool = true + +func codeToEscapeSequence(n int) string { + return fmt.Sprintf("%s[%dm", esc, n) +} + +var standardColors = map[string]string{ + "black": codeToEscapeSequence(30), + "red": codeToEscapeSequence(31), + "green": codeToEscapeSequence(32), + "yellow": codeToEscapeSequence(33), + "blue": codeToEscapeSequence(34), + "magenta": codeToEscapeSequence(35), + "cyan": codeToEscapeSequence(36), + "white": codeToEscapeSequence(37), + + "fg:black": codeToEscapeSequence(30), + "fg:red": codeToEscapeSequence(31), + "fg:green": codeToEscapeSequence(32), + "fg:yellow": codeToEscapeSequence(33), + "fg:blue": codeToEscapeSequence(34), + "fg:magenta": codeToEscapeSequence(35), + "fg:cyan": codeToEscapeSequence(36), + "fg:white": codeToEscapeSequence(37), + + "bright-black": codeToEscapeSequence(90), + "bright-red": codeToEscapeSequence(91), + "bright-green": codeToEscapeSequence(92), + "bright-yellow": codeToEscapeSequence(93), + "bright-blue": codeToEscapeSequence(94), + "bright-magenta": codeToEscapeSequence(95), + "bright-cyan": codeToEscapeSequence(96), + "bright-white": codeToEscapeSequence(97), + + "fg:bright-black": codeToEscapeSequence(90), + "fg:bright-red": codeToEscapeSequence(91), + "fg:bright-green": codeToEscapeSequence(92), + "fg:bright-yellow": codeToEscapeSequence(93), + "fg:bright-blue": codeToEscapeSequence(94), + "fg:bright-magenta": codeToEscapeSequence(95), + "fg:bright-cyan": codeToEscapeSequence(96), + "fg:bright-white": codeToEscapeSequence(97), + + "bg:black": codeToEscapeSequence(40), + "bg:red": codeToEscapeSequence(41), + "bg:green": codeToEscapeSequence(42), + "bg:yellow": codeToEscapeSequence(43), + "bg:blue": codeToEscapeSequence(44), + "bg:magenta": codeToEscapeSequence(45), + "bg:cyan": codeToEscapeSequence(46), + "bg:white": codeToEscapeSequence(47), + + "bg:bright-black": codeToEscapeSequence(100), + "bg:bright-red": codeToEscapeSequence(101), + "bg:bright-green": codeToEscapeSequence(102), + "bg:bright-yellow": codeToEscapeSequence(103), + "bg:bright-blue": codeToEscapeSequence(104), + "bg:bright-magenta": codeToEscapeSequence(105), + "bg:bright-cyan": codeToEscapeSequence(106), + "bg:bright-white": codeToEscapeSequence(107), + + "none": codeToEscapeSequence(0), +} + +func hexToRGB(hex string) (int, int, int, error) { + if !strings.HasPrefix(hex, "#") { + return 0, 0, 0, fmt.Errorf("hex must start with #, got %s", hex) + } + + hex = strings.TrimPrefix(hex, "#") + + if len(hex) != 6 { + return 0, 0, 0, fmt.Errorf("hex must be 6 digits, got %s", hex) + } + // Parse the hex string into RGB components + r, err := strconv.ParseInt(hex[0:2], 16, 32) + if err != nil { + return 0, 0, 0, err + } + g, err := strconv.ParseInt(hex[2:4], 16, 32) + if err != nil { + return 0, 0, 0, err + } + b, err := strconv.ParseInt(hex[4:6], 16, 32) + if err != nil { + return 0, 0, 0, err + } + + return int(r), int(g), int(b), nil +} + +func rgbToEscapeSequence(r, g, b int, isBg bool) string { + var colorType string + if isBg { + colorType = "48" + } else { + colorType = "38" + } + return fmt.Sprintf("\x1b[%s;2;%d;%d;%dm", colorType, r, g, b) +} + +func Disable() { + enabled = false +} + +func Color(colors ...string) (string, error) { + seq := "" + if !enabled { + return seq, nil + } + for _, color := range colors { + if strings.HasPrefix(color, "#") || strings.HasPrefix(color, "fg:#") || strings.HasPrefix(color, "bg:#") { + r, g, b, err := hexToRGB(strings.TrimPrefix(strings.TrimPrefix(color, "fg:"), "bg:")) + if err != nil { + return "", err + } + seq += rgbToEscapeSequence(r, g, b, strings.HasPrefix(color, "bg:#")) + } else { + s, exists := standardColors[color] + if !exists { + return "", fmt.Errorf("color %s not found", color) + } + seq += s + } + } + return seq, nil +} diff --git a/pkg/config/config.go b/pkg/config/config.go new file mode 100644 index 0000000..881809a --- /dev/null +++ b/pkg/config/config.go @@ -0,0 +1,17 @@ +package config + +type BgpsConfig struct { + PromptPrefix string `toml:"prompt_prefix"` + PromptSuffix string `toml:"prompt_suffix"` + AheadFormat string `toml:"ahead_format"` + BehindFormat string `toml:"behind_format"` + DivergedFormat string `toml:"diverged_format"` + NoUpstreamRemoteFormat string `toml:"no_upstream_remote_format"` + ColorEnabled bool `toml:"color_enabled"` + ColorClean string `toml:"color_clean"` + ColorConflict string `toml:"color_conflict"` + ColorDirty string `toml:"color_dirty"` + ColorUntracked string `toml:"color_untracked"` + ColorNoUpstream string `toml:"color_no_upstream"` + ColorMerging string `toml:"color_merging"` +} diff --git a/pkg/git/git.go b/pkg/git/git.go new file mode 100644 index 0000000..a4a822b --- /dev/null +++ b/pkg/git/git.go @@ -0,0 +1,278 @@ +package git + +import ( + "errors" + "fmt" + "io" + "os/exec" + "strconv" + "strings" +) + +func CommitCounts() (int, int, error) { + cmd := exec.Command( + "git", + "rev-list", + "--left-right", + "--count", + "...@{upstream}", + ) + stdCombined, err := cmd.CombinedOutput() + if err != nil { + return 0, 0, err + } + fields := strings.Fields(string(stdCombined)) + if len(fields) != 2 { + return 0, 0, fmt.Errorf("expected field length of 2 got %d", len(fields)) + } + ahead, _ := strconv.Atoi(fields[0]) + behind, _ := strconv.Atoi(fields[1]) + return ahead, behind, nil +} + +func LsFilesUnmerged() (string, error) { + cmd := exec.Command( + "git", + "ls-files", + "--unmerged", + ) + stdCombined, err := cmd.CombinedOutput() + if err != nil { + return string(stdCombined), err + } + return strings.TrimSuffix(string(stdCombined), "\n"), err +} + +func SparseCheckout() (bool, error) { + cmd := exec.Command( + "git", + "config", + "--bool", + "core.sparseCheckout", + ) + stdCombined, err := cmd.CombinedOutput() + if err != nil && len(stdCombined) != 0 { + return false, err + } + isSparseCheckout, _ := strconv.ParseBool(strings.TrimSuffix(string(stdCombined), "\n")) + return isSparseCheckout, nil +} + +func SymbolicRef(ref string) (string, error) { + cmd := exec.Command( + "git", + "symbolic-ref", + ref, + ) + stdCombined, err := cmd.CombinedOutput() + if err != nil { + return string(stdCombined), err + } + return strings.TrimSuffix(string(stdCombined), "\n"), err +} + +func DescribeTag(ref string) (string, error) { + cmd := exec.Command( + "git", + "describe", + "--tags", + "--exact-match", + ref, + ) + stdCombined, err := cmd.CombinedOutput() + if err != nil { + return string(stdCombined), err + } + return strings.TrimSuffix(string(stdCombined), "\n"), err +} + +func HasUntracked() (bool, error) { + exitCode := 0 + cmd := exec.Command( + "git", + "ls-files", + "--others", + "--exclude-standard", + "--directory", + "--no-empty-directory", + "--error-unmatch", + "--", + ":/*", + ) + err := cmd.Run() + if err != nil { + var exitError *exec.ExitError + if errors.As(err, &exitError) { + exitCode = exitError.ExitCode() + } + } + if exitCode != 0 && exitCode != 1 { + return false, err + } + return exitCode == 0, nil +} + +func RevParseShort() (string, []byte, error) { + cmd := exec.Command( + "git", + "rev-parse", + "--short", + "@{upstream}", + ) + + stderrPipe, err := cmd.StderrPipe() + if err != nil { + return "", nil, err + } + stdoutPipe, err := cmd.StdoutPipe() + if err != nil { + return "", nil, err + } + if err := cmd.Start(); err != nil { + return "", nil, err + } + + stderr, err := io.ReadAll(stderrPipe) + if err != nil { + return "", stderr, err + } + + stdout, err := io.ReadAll(stdoutPipe) + if err != nil { + return "", stderr, err + } + + err = cmd.Wait() + + return strings.TrimSuffix(string(stdout), "\n"), stderr, err +} + +func RevParse() (*GitRepo, []byte, error) { + g := GitRepo{} + cmd := exec.Command( + "git", + "rev-parse", + "--verify", + "--absolute-git-dir", + "--is-inside-git-dir", + "--is-inside-work-tree", + "--is-bare-repository", + "--is-shallow-repository", + "--abbrev-ref", + "@{upstream}", + ) + + stderrPipe, err := cmd.StderrPipe() + if err != nil { + return nil, nil, err + } + stdoutPipe, err := cmd.StdoutPipe() + if err != nil { + return nil, nil, err + } + if err := cmd.Start(); err != nil { + return nil, nil, err + } + + stderr, err := io.ReadAll(stderrPipe) + if err != nil { + return nil, stderr, err + } + + stdout, err := io.ReadAll(stdoutPipe) + if err != nil { + return nil, stderr, err + } + + err = cmd.Wait() + + if len(stdout) > 0 { + result := strings.Split(strings.TrimSuffix(string(stdout), "\n"), "\n") + resultLen := len(result) + if resultLen == 5 || resultLen == 6 { + g.GitDir = result[0] + g.IsInGitDir, _ = strconv.ParseBool(result[1]) + g.IsInWorkTree, _ = strconv.ParseBool(result[2]) + g.IsInBareRepo, _ = strconv.ParseBool(result[3]) + g.IsInShallowRepo, _ = strconv.ParseBool(result[4]) + if resultLen == 6 { + g.AbbrevRef = result[5] + shortSha, shortStderr, shortErr := RevParseShort() + g.ShortSha = shortSha + err = errors.Join(err, shortErr) + stderr = append(stderr, shortStderr...) + } + } else { + return nil, []byte{}, fmt.Errorf("expected result length of 5 or 6, got %d", resultLen) + } + } + + return &g, stderr, err +} + +func HasCleanWorkingTree() (bool, error) { + exitCode := 0 + cmd := exec.Command( + "git", + "diff", + "--no-ext-diff", + "--quiet", + "HEAD", + ) + err := cmd.Run() + if err != nil { + var exitError *exec.ExitError + if errors.As(err, &exitError) { + exitCode = exitError.ExitCode() + } + } + cachedExitCode := 0 + cachedCmd := exec.Command( + "git", + "diff", + "--cached", + "--no-ext-diff", + "--quiet", + ) + cachedErr := cachedCmd.Run() + if cachedErr != nil { + var exitError *exec.ExitError + if errors.As(cachedErr, &exitError) { + cachedExitCode = exitError.ExitCode() + } + } + + if exitCode != 0 && exitCode != 1 && cachedExitCode != 0 && cachedExitCode != 1 { + return false, errors.Join(err, cachedErr) + } + + return exitCode != 1 && cachedExitCode != 1, nil +} + +func BranchRemote(branch string) (string, error) { + cmd := exec.Command( + "git", + "config", + fmt.Sprintf("branch.%s.remote", branch), + ) + stdCombined, err := cmd.CombinedOutput() + if err != nil { + return "", err + } + + return strings.TrimSuffix(string(stdCombined), "\n"), nil +} + +func BranchMerge(branch string) (string, error) { + cmd := exec.Command( + "git", + "config", + fmt.Sprintf("branch.%s.merge", branch), + ) + stdCombined, err := cmd.CombinedOutput() + if err != nil { + return "", err + } + + return strings.TrimSuffix(string(stdCombined), "\n"), nil +} diff --git a/pkg/git/repo.go b/pkg/git/repo.go new file mode 100644 index 0000000..3a04b0f --- /dev/null +++ b/pkg/git/repo.go @@ -0,0 +1,281 @@ +package git + +import ( + "errors" + "fmt" + "os" + "strings" + + "github.com/mikesmithgh/bgps/pkg/color" + "github.com/mikesmithgh/bgps/pkg/config" + "github.com/mikesmithgh/bgps/pkg/util" +) + +type GitRepo struct { + GitDir string + IsInGitDir bool + IsInWorkTree bool + IsInBareRepo bool + IsInShallowRepo bool + IsSparseCheckout bool + Tag string + AbbrevRef string + ShortSha string + PromptMergeStatus string + PromptSparseCheckoutStatus string + PromptBranch string + PromptBareRepoStatus string +} + +func (g *GitRepo) GitDirFileExists(name string) (bool, error) { + _, err := os.Stat(g.GitDirPath(name)) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + return false, err + } + return true, nil +} + +func (g *GitRepo) GitDirFileExistsExitOnError(name string) bool { + exists, err := g.GitDirFileExists(name) + if err != nil { + util.ErrMsg(fmt.Sprintf("dir exists %s", name), err, 0) + } + return exists +} + +func (g *GitRepo) IsGitDir(name string) bool { + return util.IsDir(g.GitDirPath(name)) +} + +func (g *GitRepo) IsGitDirSymlink(name string) bool { + return util.IsSymlink(g.GitDirPath(name)) +} + +func (g *GitRepo) GitDirPath(path string) string { + return fmt.Sprintf("%s/%s", g.GitDir, path) +} + +func (g *GitRepo) ReadGitDirFile(name string) (string, error) { + return util.ReadFileTrimNewline(g.GitDirPath(name)) +} + +func (g *GitRepo) ReadGitDirFileExitOnError(name string) string { + content, err := g.ReadGitDirFile(name) + if err != nil { + util.ErrMsg(fmt.Sprintf("read file %s", name), err, 0) + } + return content +} + +func (g *GitRepo) BranchInfo(cfg config.BgpsConfig) (string, error) { + var err error + ref := "" + step := "" + total := "" + + if g.IsGitDir("rebase-merge") { + ref = g.ReadGitDirFileExitOnError("rebase-merge/head-name") + step = g.ReadGitDirFileExitOnError("rebase-merge/msgnum") + total = g.ReadGitDirFileExitOnError("rebase-merge/end") + g.PromptMergeStatus = "|REBASE-m" + if g.GitDirFileExistsExitOnError("rebase-merge/interactive") { + g.PromptMergeStatus = "|REBASE-i" + } + } else { + switch { + case g.IsGitDir("rebase-apply"): + step = g.ReadGitDirFileExitOnError("rebase-apply/next") + total = g.ReadGitDirFileExitOnError("rebase-apply/last") + switch { + case g.GitDirFileExistsExitOnError("rebase-apply/rebasing"): + ref = g.ReadGitDirFileExitOnError("rebase-apply/head-name") + g.PromptMergeStatus = "|REBASE" + case g.GitDirFileExistsExitOnError("rebase-apply/applying"): + g.PromptMergeStatus = "|AM" + default: + g.PromptMergeStatus = "|AM/REBASE" + } + case g.GitDirFileExistsExitOnError("MERGE_HEAD"): + g.PromptMergeStatus = "|MERGING" + case g.GitDirFileExistsExitOnError("CHERRY_PICK_HEAD"): + g.PromptMergeStatus = "|CHERRY-PICKING" + case g.GitDirFileExistsExitOnError("REVERT_HEAD"): + g.PromptMergeStatus = "|REVERTING" + case g.GitDirFileExistsExitOnError("BISECT_LOG"): + g.PromptMergeStatus = "|BISECTING" + } + + if ref == "" { + if g.IsGitDirSymlink("HEAD") { + if ref, err = SymbolicRef("HEAD"); err != nil { + return "", err + } + } else { + head := g.ReadGitDirFileExitOnError("HEAD") + ref = strings.TrimPrefix(head, "ref: ") + if head == ref { + tag, err := DescribeTag("HEAD") + switch { + case err == nil: + ref = tag + g.Tag = ref + case g.ShortSha == "" && len(head) > 7: + ref = head[:7] + default: + ref = g.ShortSha + } + ref = fmt.Sprintf("(%s)", ref) + } + } + } + } + + if step != "" && total != "" { + g.PromptMergeStatus += fmt.Sprintf(" %s/%s", step, total) + } + + if g.PromptMergeStatus != "" { + unmerged, err := LsFilesUnmerged() + if err != nil { + return "", err + } + if unmerged != "" { + g.PromptMergeStatus += "|CONFLICT" + } + } + + if g.IsInGitDir { + if g.IsInBareRepo { + g.PromptBareRepoStatus = "BARE:" + } else { + ref = "GIT_DIR!" + } + } + + g.PromptBranch = strings.TrimPrefix(ref, "refs/heads/") + + g.IsSparseCheckout, err = SparseCheckout() + if err != nil { + return "", err + } + + if g.IsSparseCheckout { + g.PromptSparseCheckoutStatus = "|SPARSE" + } + + if g.Tag == "" && g.ShortSha == "" && g.PromptMergeStatus == "" { + branch_remote, err := BranchRemote(g.PromptBranch) + var branch_merge string + if err == nil { + branch_merge, err = BranchMerge(g.PromptBranch) + } + if err == nil { + remoteParts := strings.SplitN(branch_remote, ":", 2) + if len(remoteParts) == 2 { + branch_remote = strings.TrimSuffix(remoteParts[1], ".git") + } + + if branch_merge != "" { + g.PromptBranch += fmt.Sprintf(cfg.NoUpstreamRemoteFormat, branch_remote, strings.TrimPrefix(branch_merge, "refs/heads/")) + } + } + } + + prompt := fmt.Sprintf("%s%s%s%s", g.PromptBareRepoStatus, g.PromptBranch, g.PromptSparseCheckoutStatus, g.PromptMergeStatus) + + return prompt, nil +} + +func (g *GitRepo) BranchStatus(cfg config.BgpsConfig) (string, string, error) { + status := "" + statusColor := "" + + if g.IsInBareRepo || g.IsInGitDir { + c, err := color.Color(strings.Split(cfg.ColorNoUpstream, " ")...) + if err != nil { + util.ErrMsg("color no upstream", err, 0) + } + return status, c, nil + } + + cleanWorkingTree, err := HasCleanWorkingTree() + if err != nil { + return "", "", err + } + hasUntracked, err := HasUntracked() + if err != nil { + return "", "", err + } + + ahead, behind := 0, 0 + if g.Tag == "" && g.ShortSha != "" { + ahead, behind, err = CommitCounts() + } + if err != nil { + return "", "", err + } + + if cleanWorkingTree { + statusColor, err = color.Color(strings.Split(cfg.ColorClean, " ")...) + if err != nil { + util.ErrMsg("color clean", err, 0) + } + } + + if ahead > 0 { + statusColor, err = color.Color(strings.Split(cfg.ColorConflict, " ")...) + if err != nil { + util.ErrMsg("color conflict", err, 0) + } + status = fmt.Sprintf(cfg.AheadFormat, ahead) + } + if behind > 0 { + statusColor, err = color.Color(strings.Split(cfg.ColorConflict, " ")...) + if err != nil { + util.ErrMsg("color conflict", err, 0) + } + status = fmt.Sprintf(cfg.BehindFormat, behind) + } + + if ahead > 0 && behind > 0 { + status = fmt.Sprintf(cfg.DivergedFormat, ahead, behind) + } + + if g.ShortSha == "" { + statusColor, err = color.Color(strings.Split(cfg.ColorNoUpstream, " ")...) + if err != nil { + util.ErrMsg("color no upstream", err, 0) + } + } + + if g.PromptMergeStatus != "" { + statusColor, err = color.Color(strings.Split(cfg.ColorMerging, " ")...) + if err != nil { + util.ErrMsg("color merging", err, 0) + } + } + + if hasUntracked { + statusColor, err = color.Color(strings.Split(cfg.ColorUntracked, " ")...) + if err != nil { + util.ErrMsg("color untracked", err, 0) + } + status = fmt.Sprintf("*%s", status) + } + + if !cleanWorkingTree && !hasUntracked { + statusColor, err = color.Color(strings.Split(cfg.ColorDirty, " ")...) + if err != nil { + util.ErrMsg("color dirty", err, 0) + } + status = fmt.Sprintf("*%s", status) + } + if status != "" { + status = " " + status + } + + return status, statusColor, nil +} diff --git a/pkg/util/util.go b/pkg/util/util.go new file mode 100644 index 0000000..5f2dcb7 --- /dev/null +++ b/pkg/util/util.go @@ -0,0 +1,47 @@ +package util + +import ( + "fmt" + "io/fs" + "os" + "strings" + + "github.com/mikesmithgh/bgps/pkg/color" +) + +func IsDir(name string) bool { + fileInfo, err := os.Stat(name) + if err != nil { + return false + } + return fileInfo.IsDir() +} + +func IsSymlink(name string) bool { + fileInfo, err := os.Lstat(name) + if err != nil { + return false + } + return fileInfo.Mode()&fs.ModeSymlink != 0 // bitwise check if mode has symlink +} + +func ReadFileTrimNewline(name string) (string, error) { + result, err := os.ReadFile(name) + if err != nil { + return "", err + } + return strings.TrimSuffix(string(result), "\n"), err +} + +func ErrMsg(hint string, e error, exitCode int) { + errorColor, _ := color.Color("red") + clearColor, _ := color.Color("none") + var error_msg string + if e == nil { + error_msg = "no error message provided" + } else { + error_msg = strings.ReplaceAll(e.Error(), "\n", "") + } + fmt.Printf("%s bgps error(%s): %s%s", errorColor, hint, error_msg, clearColor) + os.Exit(exitCode) +} diff --git a/screenshots/demo.gif b/screenshots/demo.gif deleted file mode 100644 index b3d120b..0000000 Binary files a/screenshots/demo.gif and /dev/null differ diff --git a/scripts/bgps-unofficial-v2.sh b/scripts/bgps-unofficial-v2.sh new file mode 100755 index 0000000..25be3bd --- /dev/null +++ b/scripts/bgps-unofficial-v2.sh @@ -0,0 +1,306 @@ +#!/usr/bin/env bash + +# this is a temporary bash script that will be removed +# this is an intermediate rewrite of bgps before the go rewrite +# +# +# Copyright (C) 2017 Michael Smith +# Copyright (C) 2006,2007 Shawn O. Pearce +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +# A better bash prompt for git. bgps provides a convenient way to customize +# the PS1 prompt and to determine information about the current git branch. +# bgps can indicate if the branch has a clean or dirty working tree, whether +# or not it is tracking a remote branch, and the number of commits the local +# branch is ahead or behind the remote branch. +# +# Parts of this program were copied and modified from +# +# + +####################################### +# Read contents of file to variables +# Arguments: +# $filepath the path of the file to read +# $variable_names... the name of the variables to store the contents +####################################### +_eread() { + local filepath="${1}" + shift + [[ -r "${filepath}" ]] && read -r "$@" <"${filepath}" +} + +####################################### +# Get current git branch and additional repository information +# Returns: 0 on success +# Returns: 2 on success and in a detached head state +####################################### +_branch_info() { + + local git_dir="$1" + local inside_gitdir="$2" + local bare_repo="$3" + local inside_worktree="$4" + local short_sha="$5" + + local is_detached="false" + local merge_status="" + local sparse="" + local branch="" + local step="" + local total="" + if [[ -d "${git_dir}/rebase-merge" ]]; then + + _eread "${git_dir}/rebase-merge/head-name" branch + _eread "${git_dir}/rebase-merge/msgnum" step + _eread "${git_dir}/rebase-merge/end" total + + if [[ -f "${git_dir}/rebase-merge/interactive" ]]; then + merge_status="|REBASE-i" + else + merge_status="|REBASE-m" + fi + + else + + if [[ -d "${git_dir}/rebase-apply" ]]; then + + _eread "${git_dir}/rebase-apply/next" step + _eread "${git_dir}/rebase-apply/last" total + + if [[ -f "${git_dir}/rebase-apply/rebasing" ]]; then + _eread "${git_dir}/rebase-apply/head-name" branch + merge_status="|REBASE" + elif [[ -f "${git_dir}/rebase-apply/applying" ]]; then + merge_status="|AM" + else + merge_status="|AM/REBASE" + fi + + elif [[ -f "${git_dir}/MERGE_HEAD" ]]; then + merge_status="|MERGING" + elif [[ -f "${git_dir}/CHERRY_PICK_HEAD" ]]; then + merge_status="|CHERRY-PICKING" + elif [[ -f "${git_dir}/REVERT_HEAD" ]]; then + merge_status="|REVERTING" + elif [[ -f "${git_dir}/BISECT_LOG" ]]; then + merge_status="|BISECTING" + fi + + if [[ "${branch}" ]]; then + : + elif [[ -L "${git_dir}/HEAD" ]]; then + # symlink symbolic ref + branch="$(git symbolic-ref HEAD 2>/dev/null)" + else + local head="" + if ! _eread "${git_dir}/HEAD" head; then + return 1 + fi + branch="${head#ref: }" + local upstream_info + upstream_info="$(git rev-parse --abbrev-ref '@{upstream}' 2>/dev/null)" + if [[ "${head}" == "${branch}" ]]; then + is_detached="true" + branch="$(git describe --tags --exact-match HEAD 2>/dev/null)" || branch="${head:0:7}..." # was short + branch="(${branch})" + elif [[ "$upstream_info" == '@{upstream}' ]] || [[ "$upstream_info" == '' ]]; then + is_detached="true" + fi + fi + fi + + if [[ -n "${step}" ]] && [[ -n "${total}" ]]; then + merge_status="${merge_status} ${step}/${total}" + fi + + if [[ "$merge_status" ]] && [[ $(git ls-files --unmerged 2>/dev/null) ]]; then + merge_status="$merge_status|CONFLICT" + fi + + local prefix="" + + if [[ "${inside_gitdir}" == "true" ]]; then + if [[ "${bare_repo}" == "true" ]]; then + prefix="BARE:" + else + branch="GIT_DIR!" + fi + fi + + branch="${branch##refs/heads/}" + + if [[ "$(git config --bool core.sparseCheckout)" == "true" ]]; then + sparse="|SPARSE" + fi + printf -- "%s%s%s%s" "${prefix}" "${branch}" "${sparse}" "${merge_status}" + + if [[ "$is_detached" == "true" ]]; then + return 2 + fi + + return 0 +} + +####################################### +# Get formatted git status +# Globals: +# $stop_color +# Returns: 0 on success +####################################### +_bgps_git_status() { + local color_clean='\x1b[38;2;167;192;128m' + + local color_no_upstream='\x1b[38;2;146;131;116m' + local color_untracked='\x1b[38;2;211;134;155m' + local color_dirty='\x1b[38;2;255;105;97m' + local color_conflict='\x1b[38;2;219;188;95m' + local prefix='  ' + local postfix='' + local git_ahead='↑[%s]' + local git_behind='↓[%s]' + local git_diverged='↕ ↑[%a] ↓[%b]' + local git_bare='󱣻' + local git_color="${stop_color}" + + local git_symbol="" + + local repo_info + repo_info="$(git rev-parse --git-dir --is-inside-git-dir --is-bare-repository --is-inside-work-tree --short '@{upstream}' 2>/dev/null)" + + local repo_info_arr + readarray -t repo_info_arr <<<"$repo_info" + local git_dir="${repo_info_arr[0]}" + local inside_gitdir="${repo_info_arr[1]}" + local bare_repo="${repo_info_arr[2]}" + local inside_worktree="${repo_info_arr[3]}" + local short_sha="${repo_info_arr[4]}" + + local is_detached="false" + local git_branch_exit + local git_branch + git_branch=$(_branch_info "$git_dir" "$inside_gitdir" "$bare_repo" "$inside_worktree" "$short_sha") + git_branch_exit="$?" + + if (("$git_branch_exit" == 2)); then + is_detached="true" + elif (("$git_branch_exit")); then + return 1 + fi + + if [[ "$bare_repo" == "true" ]]; then + git_symbol="${git_bare}" + fi + if [[ "$bare_repo" == "true" ]] || [[ "$inside_gitdir" == "true" ]]; then + git_color="${color_no_upstream}" + printf -- "%s" "${git_color}" + printf -- "%s%s%s%s" "${prefix:+${prefix}}" "${git_branch}" "${git_symbol:+ ${git_symbol}}" "${postfix:+${postfix}}" + return 0 + fi + + local diff_error + diff_error=$(git diff --no-ext-diff --quiet HEAD 2>&1) + local dirty_exit_code="${?}" # code == 0 clean working tree, code == 1 dirty working tree + + local empty_git_error="ambiguous argument 'HEAD'" + local no_upstream_git_error="no upstream configured" + local no_such_branch_git_error="no such branch" + local no_upstream=0 + if [[ "$short_sha" == "" ]]; then + no_upstream=1 + fi + if [[ "${diff_error}" == *"${empty_git_error}"* ]] || [[ "${diff_error}" == *"${no_upstream_git_error}"* ]] || [[ "${diff_error}" == *"${no_such_branch_git_error}"* ]]; then + no_upstream=1 + # there is no upstream so compare against staging area + diff_error=$(git diff --cached --no-ext-diff --quiet 2>&1) + dirty_exit_code="${?}" # code == 0 clean working tree, code == 1 dirty working tree + fi + + local untracked_exit_code="1" # code == 0 untracked files exist, code > 0 no untracked files + # allow no upstream error to passthrough to apply coloring and formatting + if (("${dirty_exit_code}" == 0)) || (("${dirty_exit_code}" == 1)) || (("${no_upstream}")); then + + git ls-files --others --exclude-standard --directory --no-empty-directory --error-unmatch -- ':/*' >/dev/null 2>/dev/null + untracked_exit_code="${?}" # code == 0 untracked files exist, code > 0 no untracked files + + local commit_counts + local commit_counts_exit_code=1 + if [[ "$is_detached" == "true" ]]; then + commit_counts=(0 0) + elif ((no_upstream)); then + ahead_count="$(git rev-list --count HEAD 2>/dev/null)" + commit_counts=("$ahead_count" 0) + else + IFS=$'\t' read -r -a commit_counts <<<"$(git rev-list --left-right --count ...'@{upstream}' 2>/dev/null)" + commit_counts_exit_code="$?" + fi + + if ((!dirty_exit_code)); then + git_color="${color_clean}" + fi + + if ((commit_counts[0])); then + git_color="${color_conflict}" + git_symbol="${git_ahead/\%s/${commit_counts[0]}}" + fi + + if ((commit_counts[1])); then + git_color="${color_conflict}" + git_symbol="${git_behind/\%s/${commit_counts[1]}}" + fi + + if ((commit_counts[0] && commit_counts[1])); then + git_symbol="${git_diverged/\%a/${commit_counts[0]}}" + git_symbol="${git_symbol/\%b/${commit_counts[1]}}" + fi + + # continue to check for untracked and dirty because + # it is still possible even without an upstream + + if ((no_upstream)) || ((commit_counts_exit_code)); then + # no upstream configured for branch + git_color="${color_no_upstream}" + fi + + if ((!untracked_exit_code)); then + git_color="${color_untracked}" + git_symbol="*${git_symbol#\*}" + fi + + if ((dirty_exit_code == 1)) && ((untracked_exit_code)); then + git_color="${color_dirty}" + git_symbol="*${git_symbol#\*}" + fi + + printf -- "%s" "${git_color}" + printf -- "%s%s%s%s" "${prefix:+${prefix}}" "${git_branch}" "${git_symbol:+ ${git_symbol}}" "${postfix:+${postfix}}" + else + printf -- "%s" "${color_dirty}" + printf -- "ERROR(bgps): %s" "${diff_error}" + fi + printf -- '' + + return 0 +} + +stop_color="\033[0m" +# shellcheck disable=SC2059 +printf -- "$(_bgps_git_status)$stop_color" + +# unset variables and functions +unset stop_color +unset -f _bgps_git_status +unset -f _branch_info +unset -f _eread diff --git a/scripts/release_publish.sh b/scripts/release_publish.sh new file mode 100755 index 0000000..23f314d --- /dev/null +++ b/scripts/release_publish.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euxo pipefail + +release_notes="$1" +printf "%s" "$release_notes" >/tmp/release-notes.md +goreleaser release --clean --release-notes /tmp/release-notes.md diff --git a/testdata/am/README.md b/testdata/am/README.md new file mode 100644 index 0000000..a60a2fa --- /dev/null +++ b/testdata/am/README.md @@ -0,0 +1,3 @@ +# Test Repo + +Modified line diff --git a/testdata/am/dot_git/COMMIT_EDITMSG b/testdata/am/dot_git/COMMIT_EDITMSG new file mode 100644 index 0000000..87fc1c3 --- /dev/null +++ b/testdata/am/dot_git/COMMIT_EDITMSG @@ -0,0 +1,21 @@ +chore: ahead +# Please enter the commit message for your changes. Lines starting +# with '#' will be ignored, and an empty message aborts the commit. +# +# On branch main +# Your branch is up to date with 'origin/main'. +# +# Changes to be committed: +# modified: README.md +# +# ------------------------ >8 ------------------------ +# Do not modify or remove the line above. +# Everything below it will be ignored. +diff --git a/README.md b/README.md +index a8cdb91..a60a2fa 100644 +--- a/README.md ++++ b/README.md +@@ -1 +1,3 @@ + # Test Repo ++ ++Modified line diff --git a/testdata/am/dot_git/FETCH_HEAD b/testdata/am/dot_git/FETCH_HEAD new file mode 100644 index 0000000..e69de29 diff --git a/testdata/am/dot_git/HEAD b/testdata/am/dot_git/HEAD new file mode 100644 index 0000000..78633bd --- /dev/null +++ b/testdata/am/dot_git/HEAD @@ -0,0 +1 @@ +b69e688b26a7ca0498b0cbd8b3e6e189d987b661 diff --git a/testdata/am/dot_git/ORIG_HEAD b/testdata/am/dot_git/ORIG_HEAD new file mode 100644 index 0000000..78633bd --- /dev/null +++ b/testdata/am/dot_git/ORIG_HEAD @@ -0,0 +1 @@ +b69e688b26a7ca0498b0cbd8b3e6e189d987b661 diff --git a/testdata/am/dot_git/REBASE_HEAD b/testdata/am/dot_git/REBASE_HEAD new file mode 100644 index 0000000..78633bd --- /dev/null +++ b/testdata/am/dot_git/REBASE_HEAD @@ -0,0 +1 @@ +b69e688b26a7ca0498b0cbd8b3e6e189d987b661 diff --git a/testdata/am/dot_git/config b/testdata/am/dot_git/config new file mode 100644 index 0000000..0b453be --- /dev/null +++ b/testdata/am/dot_git/config @@ -0,0 +1,13 @@ +[core] + repositoryformatversion = 0 + filemode = true + bare = false + logallrefupdates = true + ignorecase = true + precomposeunicode = true +[remote "origin"] + url = git@github.com:mikesmithgh/test.git + fetch = +refs/heads/*:refs/remotes/origin/* +[branch "main"] + remote = origin + merge = refs/heads/main diff --git a/testdata/am/dot_git/description b/testdata/am/dot_git/description new file mode 100644 index 0000000..498b267 --- /dev/null +++ b/testdata/am/dot_git/description @@ -0,0 +1 @@ +Unnamed repository; edit this file 'description' to name the repository. diff --git a/testdata/am/dot_git/hooks/applypatch-msg.sample b/testdata/am/dot_git/hooks/applypatch-msg.sample new file mode 100755 index 0000000..a5d7b84 --- /dev/null +++ b/testdata/am/dot_git/hooks/applypatch-msg.sample @@ -0,0 +1,15 @@ +#!/bin/sh +# +# An example hook script to check the commit log message taken by +# applypatch from an e-mail message. +# +# The hook should exit with non-zero status after issuing an +# appropriate message if it wants to stop the commit. The hook is +# allowed to edit the commit message file. +# +# To enable this hook, rename this file to "applypatch-msg". + +. git-sh-setup +commitmsg="$(git rev-parse --git-path hooks/commit-msg)" +test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"} +: diff --git a/testdata/am/dot_git/hooks/commit-msg.sample b/testdata/am/dot_git/hooks/commit-msg.sample new file mode 100755 index 0000000..b58d118 --- /dev/null +++ b/testdata/am/dot_git/hooks/commit-msg.sample @@ -0,0 +1,24 @@ +#!/bin/sh +# +# An example hook script to check the commit log message. +# Called by "git commit" with one argument, the name of the file +# that has the commit message. The hook should exit with non-zero +# status after issuing an appropriate message if it wants to stop the +# commit. The hook is allowed to edit the commit message file. +# +# To enable this hook, rename this file to "commit-msg". + +# Uncomment the below to add a Signed-off-by line to the message. +# Doing this in a hook is a bad idea in general, but the prepare-commit-msg +# hook is more suited to it. +# +# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') +# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" + +# This example catches duplicate Signed-off-by lines. + +test "" = "$(grep '^Signed-off-by: ' "$1" | + sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { + echo >&2 Duplicate Signed-off-by lines. + exit 1 +} diff --git a/testdata/am/dot_git/hooks/fsmonitor-watchman.sample b/testdata/am/dot_git/hooks/fsmonitor-watchman.sample new file mode 100755 index 0000000..23e856f --- /dev/null +++ b/testdata/am/dot_git/hooks/fsmonitor-watchman.sample @@ -0,0 +1,174 @@ +#!/usr/bin/perl + +use strict; +use warnings; +use IPC::Open2; + +# An example hook script to integrate Watchman +# (https://facebook.github.io/watchman/) with git to speed up detecting +# new and modified files. +# +# The hook is passed a version (currently 2) and last update token +# formatted as a string and outputs to stdout a new update token and +# all files that have been modified since the update token. Paths must +# be relative to the root of the working tree and separated by a single NUL. +# +# To enable this hook, rename this file to "query-watchman" and set +# 'git config core.fsmonitor .git/hooks/query-watchman' +# +my ($version, $last_update_token) = @ARGV; + +# Uncomment for debugging +# print STDERR "$0 $version $last_update_token\n"; + +# Check the hook interface version +if ($version ne 2) { + die "Unsupported query-fsmonitor hook version '$version'.\n" . + "Falling back to scanning...\n"; +} + +my $git_work_tree = get_working_dir(); + +my $retry = 1; + +my $json_pkg; +eval { + require JSON::XS; + $json_pkg = "JSON::XS"; + 1; +} or do { + require JSON::PP; + $json_pkg = "JSON::PP"; +}; + +launch_watchman(); + +sub launch_watchman { + my $o = watchman_query(); + if (is_work_tree_watched($o)) { + output_result($o->{clock}, @{$o->{files}}); + } +} + +sub output_result { + my ($clockid, @files) = @_; + + # Uncomment for debugging watchman output + # open (my $fh, ">", ".git/watchman-output.out"); + # binmode $fh, ":utf8"; + # print $fh "$clockid\n@files\n"; + # close $fh; + + binmode STDOUT, ":utf8"; + print $clockid; + print "\0"; + local $, = "\0"; + print @files; +} + +sub watchman_clock { + my $response = qx/watchman clock "$git_work_tree"/; + die "Failed to get clock id on '$git_work_tree'.\n" . + "Falling back to scanning...\n" if $? != 0; + + return $json_pkg->new->utf8->decode($response); +} + +sub watchman_query { + my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty') + or die "open2() failed: $!\n" . + "Falling back to scanning...\n"; + + # In the query expression below we're asking for names of files that + # changed since $last_update_token but not from the .git folder. + # + # To accomplish this, we're using the "since" generator to use the + # recency index to select candidate nodes and "fields" to limit the + # output to file names only. Then we're using the "expression" term to + # further constrain the results. + my $last_update_line = ""; + if (substr($last_update_token, 0, 1) eq "c") { + $last_update_token = "\"$last_update_token\""; + $last_update_line = qq[\n"since": $last_update_token,]; + } + my $query = <<" END"; + ["query", "$git_work_tree", {$last_update_line + "fields": ["name"], + "expression": ["not", ["dirname", ".git"]] + }] + END + + # Uncomment for debugging the watchman query + # open (my $fh, ">", ".git/watchman-query.json"); + # print $fh $query; + # close $fh; + + print CHLD_IN $query; + close CHLD_IN; + my $response = do {local $/; }; + + # Uncomment for debugging the watch response + # open ($fh, ">", ".git/watchman-response.json"); + # print $fh $response; + # close $fh; + + die "Watchman: command returned no output.\n" . + "Falling back to scanning...\n" if $response eq ""; + die "Watchman: command returned invalid output: $response\n" . + "Falling back to scanning...\n" unless $response =~ /^\{/; + + return $json_pkg->new->utf8->decode($response); +} + +sub is_work_tree_watched { + my ($output) = @_; + my $error = $output->{error}; + if ($retry > 0 and $error and $error =~ m/unable to resolve root .* directory (.*) is not watched/) { + $retry--; + my $response = qx/watchman watch "$git_work_tree"/; + die "Failed to make watchman watch '$git_work_tree'.\n" . + "Falling back to scanning...\n" if $? != 0; + $output = $json_pkg->new->utf8->decode($response); + $error = $output->{error}; + die "Watchman: $error.\n" . + "Falling back to scanning...\n" if $error; + + # Uncomment for debugging watchman output + # open (my $fh, ">", ".git/watchman-output.out"); + # close $fh; + + # Watchman will always return all files on the first query so + # return the fast "everything is dirty" flag to git and do the + # Watchman query just to get it over with now so we won't pay + # the cost in git to look up each individual file. + my $o = watchman_clock(); + $error = $output->{error}; + + die "Watchman: $error.\n" . + "Falling back to scanning...\n" if $error; + + output_result($o->{clock}, ("/")); + $last_update_token = $o->{clock}; + + eval { launch_watchman() }; + return 0; + } + + die "Watchman: $error.\n" . + "Falling back to scanning...\n" if $error; + + return 1; +} + +sub get_working_dir { + my $working_dir; + if ($^O =~ 'msys' || $^O =~ 'cygwin') { + $working_dir = Win32::GetCwd(); + $working_dir =~ tr/\\/\//; + } else { + require Cwd; + $working_dir = Cwd::cwd(); + } + + return $working_dir; +} diff --git a/testdata/am/dot_git/hooks/post-update.sample b/testdata/am/dot_git/hooks/post-update.sample new file mode 100755 index 0000000..ec17ec1 --- /dev/null +++ b/testdata/am/dot_git/hooks/post-update.sample @@ -0,0 +1,8 @@ +#!/bin/sh +# +# An example hook script to prepare a packed repository for use over +# dumb transports. +# +# To enable this hook, rename this file to "post-update". + +exec git update-server-info diff --git a/testdata/am/dot_git/hooks/pre-applypatch.sample b/testdata/am/dot_git/hooks/pre-applypatch.sample new file mode 100755 index 0000000..4142082 --- /dev/null +++ b/testdata/am/dot_git/hooks/pre-applypatch.sample @@ -0,0 +1,14 @@ +#!/bin/sh +# +# An example hook script to verify what is about to be committed +# by applypatch from an e-mail message. +# +# The hook should exit with non-zero status after issuing an +# appropriate message if it wants to stop the commit. +# +# To enable this hook, rename this file to "pre-applypatch". + +. git-sh-setup +precommit="$(git rev-parse --git-path hooks/pre-commit)" +test -x "$precommit" && exec "$precommit" ${1+"$@"} +: diff --git a/testdata/am/dot_git/hooks/pre-commit.sample b/testdata/am/dot_git/hooks/pre-commit.sample new file mode 100755 index 0000000..29ed5ee --- /dev/null +++ b/testdata/am/dot_git/hooks/pre-commit.sample @@ -0,0 +1,49 @@ +#!/bin/sh +# +# An example hook script to verify what is about to be committed. +# Called by "git commit" with no arguments. The hook should +# exit with non-zero status after issuing an appropriate message if +# it wants to stop the commit. +# +# To enable this hook, rename this file to "pre-commit". + +if git rev-parse --verify HEAD >/dev/null 2>&1 +then + against=HEAD +else + # Initial commit: diff against an empty tree object + against=$(git hash-object -t tree /dev/null) +fi + +# If you want to allow non-ASCII filenames set this variable to true. +allownonascii=$(git config --type=bool hooks.allownonascii) + +# Redirect output to stderr. +exec 1>&2 + +# Cross platform projects tend to avoid non-ASCII filenames; prevent +# them from being added to the repository. We exploit the fact that the +# printable range starts at the space character and ends with tilde. +if [ "$allownonascii" != "true" ] && + # Note that the use of brackets around a tr range is ok here, (it's + # even required, for portability to Solaris 10's /usr/bin/tr), since + # the square bracket bytes happen to fall in the designated range. + test $(git diff-index --cached --name-only --diff-filter=A -z $against | + LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 +then + cat <<\EOF +Error: Attempt to add a non-ASCII file name. + +This can cause problems if you want to work with people on other platforms. + +To be portable it is advisable to rename the file. + +If you know what you are doing you can disable this check using: + + git config hooks.allownonascii true +EOF + exit 1 +fi + +# If there are whitespace errors, print the offending file names and fail. +exec git diff-index --check --cached $against -- diff --git a/testdata/am/dot_git/hooks/pre-merge-commit.sample b/testdata/am/dot_git/hooks/pre-merge-commit.sample new file mode 100755 index 0000000..399eab1 --- /dev/null +++ b/testdata/am/dot_git/hooks/pre-merge-commit.sample @@ -0,0 +1,13 @@ +#!/bin/sh +# +# An example hook script to verify what is about to be committed. +# Called by "git merge" with no arguments. The hook should +# exit with non-zero status after issuing an appropriate message to +# stderr if it wants to stop the merge commit. +# +# To enable this hook, rename this file to "pre-merge-commit". + +. git-sh-setup +test -x "$GIT_DIR/hooks/pre-commit" && + exec "$GIT_DIR/hooks/pre-commit" +: diff --git a/testdata/am/dot_git/hooks/pre-push.sample b/testdata/am/dot_git/hooks/pre-push.sample new file mode 100755 index 0000000..4ce688d --- /dev/null +++ b/testdata/am/dot_git/hooks/pre-push.sample @@ -0,0 +1,53 @@ +#!/bin/sh + +# An example hook script to verify what is about to be pushed. Called by "git +# push" after it has checked the remote status, but before anything has been +# pushed. If this script exits with a non-zero status nothing will be pushed. +# +# This hook is called with the following parameters: +# +# $1 -- Name of the remote to which the push is being done +# $2 -- URL to which the push is being done +# +# If pushing without using a named remote those arguments will be equal. +# +# Information about the commits which are being pushed is supplied as lines to +# the standard input in the form: +# +# +# +# This sample shows how to prevent push of commits where the log message starts +# with "WIP" (work in progress). + +remote="$1" +url="$2" + +zero=$(git hash-object --stdin &2 "Found WIP commit in $local_ref, not pushing" + exit 1 + fi + fi +done + +exit 0 diff --git a/testdata/am/dot_git/hooks/pre-rebase.sample b/testdata/am/dot_git/hooks/pre-rebase.sample new file mode 100755 index 0000000..6cbef5c --- /dev/null +++ b/testdata/am/dot_git/hooks/pre-rebase.sample @@ -0,0 +1,169 @@ +#!/bin/sh +# +# Copyright (c) 2006, 2008 Junio C Hamano +# +# The "pre-rebase" hook is run just before "git rebase" starts doing +# its job, and can prevent the command from running by exiting with +# non-zero status. +# +# The hook is called with the following parameters: +# +# $1 -- the upstream the series was forked from. +# $2 -- the branch being rebased (or empty when rebasing the current branch). +# +# This sample shows how to prevent topic branches that are already +# merged to 'next' branch from getting rebased, because allowing it +# would result in rebasing already published history. + +publish=next +basebranch="$1" +if test "$#" = 2 +then + topic="refs/heads/$2" +else + topic=`git symbolic-ref HEAD` || + exit 0 ;# we do not interrupt rebasing detached HEAD +fi + +case "$topic" in +refs/heads/??/*) + ;; +*) + exit 0 ;# we do not interrupt others. + ;; +esac + +# Now we are dealing with a topic branch being rebased +# on top of master. Is it OK to rebase it? + +# Does the topic really exist? +git show-ref -q "$topic" || { + echo >&2 "No such branch $topic" + exit 1 +} + +# Is topic fully merged to master? +not_in_master=`git rev-list --pretty=oneline ^master "$topic"` +if test -z "$not_in_master" +then + echo >&2 "$topic is fully merged to master; better remove it." + exit 1 ;# we could allow it, but there is no point. +fi + +# Is topic ever merged to next? If so you should not be rebasing it. +only_next_1=`git rev-list ^master "^$topic" ${publish} | sort` +only_next_2=`git rev-list ^master ${publish} | sort` +if test "$only_next_1" = "$only_next_2" +then + not_in_topic=`git rev-list "^$topic" master` + if test -z "$not_in_topic" + then + echo >&2 "$topic is already up to date with master" + exit 1 ;# we could allow it, but there is no point. + else + exit 0 + fi +else + not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"` + /usr/bin/perl -e ' + my $topic = $ARGV[0]; + my $msg = "* $topic has commits already merged to public branch:\n"; + my (%not_in_next) = map { + /^([0-9a-f]+) /; + ($1 => 1); + } split(/\n/, $ARGV[1]); + for my $elem (map { + /^([0-9a-f]+) (.*)$/; + [$1 => $2]; + } split(/\n/, $ARGV[2])) { + if (!exists $not_in_next{$elem->[0]}) { + if ($msg) { + print STDERR $msg; + undef $msg; + } + print STDERR " $elem->[1]\n"; + } + } + ' "$topic" "$not_in_next" "$not_in_master" + exit 1 +fi + +<<\DOC_END + +This sample hook safeguards topic branches that have been +published from being rewound. + +The workflow assumed here is: + + * Once a topic branch forks from "master", "master" is never + merged into it again (either directly or indirectly). + + * Once a topic branch is fully cooked and merged into "master", + it is deleted. If you need to build on top of it to correct + earlier mistakes, a new topic branch is created by forking at + the tip of the "master". This is not strictly necessary, but + it makes it easier to keep your history simple. + + * Whenever you need to test or publish your changes to topic + branches, merge them into "next" branch. + +The script, being an example, hardcodes the publish branch name +to be "next", but it is trivial to make it configurable via +$GIT_DIR/config mechanism. + +With this workflow, you would want to know: + +(1) ... if a topic branch has ever been merged to "next". Young + topic branches can have stupid mistakes you would rather + clean up before publishing, and things that have not been + merged into other branches can be easily rebased without + affecting other people. But once it is published, you would + not want to rewind it. + +(2) ... if a topic branch has been fully merged to "master". + Then you can delete it. More importantly, you should not + build on top of it -- other people may already want to + change things related to the topic as patches against your + "master", so if you need further changes, it is better to + fork the topic (perhaps with the same name) afresh from the + tip of "master". + +Let's look at this example: + + o---o---o---o---o---o---o---o---o---o "next" + / / / / + / a---a---b A / / + / / / / + / / c---c---c---c B / + / / / \ / + / / / b---b C \ / + / / / / \ / + ---o---o---o---o---o---o---o---o---o---o---o "master" + + +A, B and C are topic branches. + + * A has one fix since it was merged up to "next". + + * B has finished. It has been fully merged up to "master" and "next", + and is ready to be deleted. + + * C has not merged to "next" at all. + +We would want to allow C to be rebased, refuse A, and encourage +B to be deleted. + +To compute (1): + + git rev-list ^master ^topic next + git rev-list ^master next + + if these match, topic has not merged in next at all. + +To compute (2): + + git rev-list master..topic + + if this is empty, it is fully merged to "master". + +DOC_END diff --git a/testdata/am/dot_git/hooks/pre-receive.sample b/testdata/am/dot_git/hooks/pre-receive.sample new file mode 100755 index 0000000..a1fd29e --- /dev/null +++ b/testdata/am/dot_git/hooks/pre-receive.sample @@ -0,0 +1,24 @@ +#!/bin/sh +# +# An example hook script to make use of push options. +# The example simply echoes all push options that start with 'echoback=' +# and rejects all pushes when the "reject" push option is used. +# +# To enable this hook, rename this file to "pre-receive". + +if test -n "$GIT_PUSH_OPTION_COUNT" +then + i=0 + while test "$i" -lt "$GIT_PUSH_OPTION_COUNT" + do + eval "value=\$GIT_PUSH_OPTION_$i" + case "$value" in + echoback=*) + echo "echo from the pre-receive-hook: ${value#*=}" >&2 + ;; + reject) + exit 1 + esac + i=$((i + 1)) + done +fi diff --git a/testdata/am/dot_git/hooks/prepare-commit-msg.sample b/testdata/am/dot_git/hooks/prepare-commit-msg.sample new file mode 100755 index 0000000..10fa14c --- /dev/null +++ b/testdata/am/dot_git/hooks/prepare-commit-msg.sample @@ -0,0 +1,42 @@ +#!/bin/sh +# +# An example hook script to prepare the commit log message. +# Called by "git commit" with the name of the file that has the +# commit message, followed by the description of the commit +# message's source. The hook's purpose is to edit the commit +# message file. If the hook fails with a non-zero status, +# the commit is aborted. +# +# To enable this hook, rename this file to "prepare-commit-msg". + +# This hook includes three examples. The first one removes the +# "# Please enter the commit message..." help message. +# +# The second includes the output of "git diff --name-status -r" +# into the message, just before the "git status" output. It is +# commented because it doesn't cope with --amend or with squashed +# commits. +# +# The third example adds a Signed-off-by line to the message, that can +# still be edited. This is rarely a good idea. + +COMMIT_MSG_FILE=$1 +COMMIT_SOURCE=$2 +SHA1=$3 + +/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE" + +# case "$COMMIT_SOURCE,$SHA1" in +# ,|template,) +# /usr/bin/perl -i.bak -pe ' +# print "\n" . `git diff --cached --name-status -r` +# if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;; +# *) ;; +# esac + +# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') +# git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE" +# if test -z "$COMMIT_SOURCE" +# then +# /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE" +# fi diff --git a/testdata/am/dot_git/hooks/push-to-checkout.sample b/testdata/am/dot_git/hooks/push-to-checkout.sample new file mode 100755 index 0000000..af5a0c0 --- /dev/null +++ b/testdata/am/dot_git/hooks/push-to-checkout.sample @@ -0,0 +1,78 @@ +#!/bin/sh + +# An example hook script to update a checked-out tree on a git push. +# +# This hook is invoked by git-receive-pack(1) when it reacts to git +# push and updates reference(s) in its repository, and when the push +# tries to update the branch that is currently checked out and the +# receive.denyCurrentBranch configuration variable is set to +# updateInstead. +# +# By default, such a push is refused if the working tree and the index +# of the remote repository has any difference from the currently +# checked out commit; when both the working tree and the index match +# the current commit, they are updated to match the newly pushed tip +# of the branch. This hook is to be used to override the default +# behaviour; however the code below reimplements the default behaviour +# as a starting point for convenient modification. +# +# The hook receives the commit with which the tip of the current +# branch is going to be updated: +commit=$1 + +# It can exit with a non-zero status to refuse the push (when it does +# so, it must not modify the index or the working tree). +die () { + echo >&2 "$*" + exit 1 +} + +# Or it can make any necessary changes to the working tree and to the +# index to bring them to the desired state when the tip of the current +# branch is updated to the new commit, and exit with a zero status. +# +# For example, the hook can simply run git read-tree -u -m HEAD "$1" +# in order to emulate git fetch that is run in the reverse direction +# with git push, as the two-tree form of git read-tree -u -m is +# essentially the same as git switch or git checkout that switches +# branches while keeping the local changes in the working tree that do +# not interfere with the difference between the branches. + +# The below is a more-or-less exact translation to shell of the C code +# for the default behaviour for git's push-to-checkout hook defined in +# the push_to_deploy() function in builtin/receive-pack.c. +# +# Note that the hook will be executed from the repository directory, +# not from the working tree, so if you want to perform operations on +# the working tree, you will have to adapt your code accordingly, e.g. +# by adding "cd .." or using relative paths. + +if ! git update-index -q --ignore-submodules --refresh +then + die "Up-to-date check failed" +fi + +if ! git diff-files --quiet --ignore-submodules -- +then + die "Working directory has unstaged changes" +fi + +# This is a rough translation of: +# +# head_has_history() ? "HEAD" : EMPTY_TREE_SHA1_HEX +if git cat-file -e HEAD 2>/dev/null +then + head=HEAD +else + head=$(git hash-object -t tree --stdin &2 + exit 1 +} + +unset GIT_DIR GIT_WORK_TREE +cd "$worktree" && + +if grep -q "^diff --git " "$1" +then + validate_patch "$1" +else + validate_cover_letter "$1" +fi && + +if test "$GIT_SENDEMAIL_FILE_COUNTER" = "$GIT_SENDEMAIL_FILE_TOTAL" +then + git config --unset-all sendemail.validateWorktree && + trap 'git worktree remove -ff "$worktree"' EXIT && + validate_series +fi diff --git a/testdata/am/dot_git/hooks/update.sample b/testdata/am/dot_git/hooks/update.sample new file mode 100755 index 0000000..c4d426b --- /dev/null +++ b/testdata/am/dot_git/hooks/update.sample @@ -0,0 +1,128 @@ +#!/bin/sh +# +# An example hook script to block unannotated tags from entering. +# Called by "git receive-pack" with arguments: refname sha1-old sha1-new +# +# To enable this hook, rename this file to "update". +# +# Config +# ------ +# hooks.allowunannotated +# This boolean sets whether unannotated tags will be allowed into the +# repository. By default they won't be. +# hooks.allowdeletetag +# This boolean sets whether deleting tags will be allowed in the +# repository. By default they won't be. +# hooks.allowmodifytag +# This boolean sets whether a tag may be modified after creation. By default +# it won't be. +# hooks.allowdeletebranch +# This boolean sets whether deleting branches will be allowed in the +# repository. By default they won't be. +# hooks.denycreatebranch +# This boolean sets whether remotely creating branches will be denied +# in the repository. By default this is allowed. +# + +# --- Command line +refname="$1" +oldrev="$2" +newrev="$3" + +# --- Safety check +if [ -z "$GIT_DIR" ]; then + echo "Don't run this script from the command line." >&2 + echo " (if you want, you could supply GIT_DIR then run" >&2 + echo " $0 )" >&2 + exit 1 +fi + +if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then + echo "usage: $0 " >&2 + exit 1 +fi + +# --- Config +allowunannotated=$(git config --type=bool hooks.allowunannotated) +allowdeletebranch=$(git config --type=bool hooks.allowdeletebranch) +denycreatebranch=$(git config --type=bool hooks.denycreatebranch) +allowdeletetag=$(git config --type=bool hooks.allowdeletetag) +allowmodifytag=$(git config --type=bool hooks.allowmodifytag) + +# check for no description +projectdesc=$(sed -e '1q' "$GIT_DIR/description") +case "$projectdesc" in +"Unnamed repository"* | "") + echo "*** Project description file hasn't been set" >&2 + exit 1 + ;; +esac + +# --- Check types +# if $newrev is 0000...0000, it's a commit to delete a ref. +zero=$(git hash-object --stdin &2 + echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2 + exit 1 + fi + ;; + refs/tags/*,delete) + # delete tag + if [ "$allowdeletetag" != "true" ]; then + echo "*** Deleting a tag is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/tags/*,tag) + # annotated tag + if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1 + then + echo "*** Tag '$refname' already exists." >&2 + echo "*** Modifying a tag is not allowed in this repository." >&2 + exit 1 + fi + ;; + refs/heads/*,commit) + # branch + if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then + echo "*** Creating a branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/heads/*,delete) + # delete branch + if [ "$allowdeletebranch" != "true" ]; then + echo "*** Deleting a branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/remotes/*,commit) + # tracking branch + ;; + refs/remotes/*,delete) + # delete tracking branch + if [ "$allowdeletebranch" != "true" ]; then + echo "*** Deleting a tracking branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + *) + # Anything else (is there anything else?) + echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2 + exit 1 + ;; +esac + +# --- Finished +exit 0 diff --git a/testdata/am/dot_git/index b/testdata/am/dot_git/index new file mode 100644 index 0000000..b1c3b63 Binary files /dev/null and b/testdata/am/dot_git/index differ diff --git a/testdata/am/dot_git/info/exclude b/testdata/am/dot_git/info/exclude new file mode 100644 index 0000000..a5196d1 --- /dev/null +++ b/testdata/am/dot_git/info/exclude @@ -0,0 +1,6 @@ +# git ls-files --others --exclude-from=.git/info/exclude +# Lines that start with '#' are comments. +# For a project mostly in C, the following would be a good set of +# exclude patterns (uncomment them if you want to use them): +# *.[oa] +# *~ diff --git a/testdata/am/dot_git/logs/HEAD b/testdata/am/dot_git/logs/HEAD new file mode 100644 index 0000000..b9a3bc1 --- /dev/null +++ b/testdata/am/dot_git/logs/HEAD @@ -0,0 +1,4 @@ +0000000000000000000000000000000000000000 24afc9585ad36ab4a5bcfce5fe08131e72904a5e Mike Smith <10135646+mikesmithgh@users.noreply.github.com> 1710249033 -0400 commit (initial): chore: test repo +24afc9585ad36ab4a5bcfce5fe08131e72904a5e b69e688b26a7ca0498b0cbd8b3e6e189d987b661 Mike Smith <10135646+mikesmithgh@users.noreply.github.com> 1710249375 -0400 commit: chore: ahead +b69e688b26a7ca0498b0cbd8b3e6e189d987b661 24afc9585ad36ab4a5bcfce5fe08131e72904a5e Mike Smith <10135646+mikesmithgh@users.noreply.github.com> 1710429959 -0400 rebase (start): checkout HEAD~ +24afc9585ad36ab4a5bcfce5fe08131e72904a5e b69e688b26a7ca0498b0cbd8b3e6e189d987b661 Mike Smith <10135646+mikesmithgh@users.noreply.github.com> 1710429959 -0400 rebase: fast-forward diff --git a/testdata/am/dot_git/logs/refs/heads/main b/testdata/am/dot_git/logs/refs/heads/main new file mode 100644 index 0000000..48f3491 --- /dev/null +++ b/testdata/am/dot_git/logs/refs/heads/main @@ -0,0 +1,2 @@ +0000000000000000000000000000000000000000 24afc9585ad36ab4a5bcfce5fe08131e72904a5e Mike Smith <10135646+mikesmithgh@users.noreply.github.com> 1710249033 -0400 commit (initial): chore: test repo +24afc9585ad36ab4a5bcfce5fe08131e72904a5e b69e688b26a7ca0498b0cbd8b3e6e189d987b661 Mike Smith <10135646+mikesmithgh@users.noreply.github.com> 1710249375 -0400 commit: chore: ahead diff --git a/testdata/am/dot_git/logs/refs/remotes/origin/main b/testdata/am/dot_git/logs/refs/remotes/origin/main new file mode 100644 index 0000000..93909bf --- /dev/null +++ b/testdata/am/dot_git/logs/refs/remotes/origin/main @@ -0,0 +1 @@ +0000000000000000000000000000000000000000 24afc9585ad36ab4a5bcfce5fe08131e72904a5e Mike Smith <10135646+mikesmithgh@users.noreply.github.com> 1710249042 -0400 update by push diff --git a/testdata/am/dot_git/objects/24/afc9585ad36ab4a5bcfce5fe08131e72904a5e b/testdata/am/dot_git/objects/24/afc9585ad36ab4a5bcfce5fe08131e72904a5e new file mode 100644 index 0000000..f0bb9bb --- /dev/null +++ b/testdata/am/dot_git/objects/24/afc9585ad36ab4a5bcfce5fe08131e72904a5e @@ -0,0 +1 @@ +xK!EQǬE1n+StELCܽ'y/ѮFM]&͈Nƪ(Inu+\[Xiqe+W~??ps 8TDpiU𭓏PThY|L \ No newline at end of file diff --git a/testdata/am/dot_git/objects/a6/0a2fae6d9604439a447c5f618bbaf4d4fb9c83 b/testdata/am/dot_git/objects/a6/0a2fae6d9604439a447c5f618bbaf4d4fb9c83 new file mode 100644 index 0000000..c40a00c Binary files /dev/null and b/testdata/am/dot_git/objects/a6/0a2fae6d9604439a447c5f618bbaf4d4fb9c83 differ diff --git a/testdata/am/dot_git/objects/a8/cdb9100441b47e4afc480f32bdc28777511316 b/testdata/am/dot_git/objects/a8/cdb9100441b47e4afc480f32bdc28777511316 new file mode 100644 index 0000000..7cbd852 Binary files /dev/null and b/testdata/am/dot_git/objects/a8/cdb9100441b47e4afc480f32bdc28777511316 differ diff --git a/testdata/am/dot_git/objects/b6/9e688b26a7ca0498b0cbd8b3e6e189d987b661 b/testdata/am/dot_git/objects/b6/9e688b26a7ca0498b0cbd8b3e6e189d987b661 new file mode 100644 index 0000000..a280bb4 --- /dev/null +++ b/testdata/am/dot_git/objects/b6/9e688b26a7ca0498b0cbd8b3e6e189d987b661 @@ -0,0 +1,2 @@ +xKn ЎY{| (+x%R}2=uY6! 9oZbFNxQJѤvU=ރNj|R(ɉOf +lLJ}^>]o>9/&~tq{e96m ߿HC^óɸ?=㵭*2C.Y \ No newline at end of file diff --git a/testdata/am/dot_git/objects/c8/2520f3011ecbaee5ee1eddc882bd7af6b4d14f b/testdata/am/dot_git/objects/c8/2520f3011ecbaee5ee1eddc882bd7af6b4d14f new file mode 100644 index 0000000..17f454c Binary files /dev/null and b/testdata/am/dot_git/objects/c8/2520f3011ecbaee5ee1eddc882bd7af6b4d14f differ diff --git a/testdata/am/dot_git/objects/d6/9c9ff23f98b1bd528a3b78e11da79a2f038d1f b/testdata/am/dot_git/objects/d6/9c9ff23f98b1bd528a3b78e11da79a2f038d1f new file mode 100644 index 0000000..2edd24a Binary files /dev/null and b/testdata/am/dot_git/objects/d6/9c9ff23f98b1bd528a3b78e11da79a2f038d1f differ diff --git a/testdata/am/dot_git/rebase-apply/amend b/testdata/am/dot_git/rebase-apply/amend new file mode 100644 index 0000000..78633bd --- /dev/null +++ b/testdata/am/dot_git/rebase-apply/amend @@ -0,0 +1 @@ +b69e688b26a7ca0498b0cbd8b3e6e189d987b661 diff --git a/testdata/am/dot_git/rebase-apply/applying b/testdata/am/dot_git/rebase-apply/applying new file mode 100644 index 0000000..e69de29 diff --git a/testdata/am/dot_git/rebase-apply/author-script b/testdata/am/dot_git/rebase-apply/author-script new file mode 100644 index 0000000..60759dc --- /dev/null +++ b/testdata/am/dot_git/rebase-apply/author-script @@ -0,0 +1,3 @@ +GIT_AUTHOR_NAME='Mike Smith' +GIT_AUTHOR_EMAIL='10135646+mikesmithgh@users.noreply.github.com' +GIT_AUTHOR_DATE='@1710249375 -0400' diff --git a/testdata/am/dot_git/rebase-apply/done b/testdata/am/dot_git/rebase-apply/done new file mode 100644 index 0000000..44e664e --- /dev/null +++ b/testdata/am/dot_git/rebase-apply/done @@ -0,0 +1 @@ +edit b69e688b26a7ca0498b0cbd8b3e6e189d987b661 chore: ahead diff --git a/testdata/am/dot_git/rebase-apply/git-rebase-todo b/testdata/am/dot_git/rebase-apply/git-rebase-todo new file mode 100644 index 0000000..e69de29 diff --git a/testdata/am/dot_git/rebase-apply/git-rebase-todo.backup b/testdata/am/dot_git/rebase-apply/git-rebase-todo.backup new file mode 100644 index 0000000..8dce145 --- /dev/null +++ b/testdata/am/dot_git/rebase-apply/git-rebase-todo.backup @@ -0,0 +1,32 @@ +pick b69e688b26a7ca0498b0cbd8b3e6e189d987b661 chore: ahead + +# Rebase 24afc95..b69e688 onto 24afc95 (1 command) +# +# Commands: +# p, pick = use commit +# r, reword = use commit, but edit the commit message +# e, edit = use commit, but stop for amending +# s, squash = use commit, but meld into previous commit +# f, fixup [-C | -c] = like "squash" but keep only the previous +# commit's log message, unless -C is used, in which case +# keep only this commit's message; -c is same as -C but +# opens the editor +# x, exec = run command (the rest of the line) using shell +# b, break = stop here (continue rebase later with 'git rebase --continue') +# d, drop = remove commit +# l, label