Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,23 @@ jobs:
- run: python3 scripts/test_verify_e2e.py -v


lfs-integration:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version: '1.27.3'
cache: true
- name: Install Git LFS 3.8.1
run: |
curl -sSLo git-lfs.tar.gz https://github.com/git-lfs/git-lfs/releases/download/v3.8.1/git-lfs-linux-amd64-v3.8.1.tar.gz
tar -xzf git-lfs.tar.gz
echo "$PWD/git-lfs-3.8.1" >> "$GITHUB_PATH"
git lfs version
- run: go test -race -timeout 3m -tags=lfsintegration -run '^TestLFSIntegration' ./...


binaries:
runs-on: ubuntu-latest
strategy:
Expand Down Expand Up @@ -65,4 +82,4 @@ jobs:
with:
go-version: '1.27.3'
- name: Test cache and OS locking
run: go test -timeout 3m -run 'Test(CacheLock.*|Journal.*|SyncGitCacheLifecycle|SyncGitNewObjectsAndSecondTarget|LFS.*)$' ./...
run: go test -timeout 3m -run 'Test(CacheLock.*|Journal.*|SyncGitLifecycle|SyncGitNewObjectsAndSecondTarget|LFS.*)$' ./...
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Use it to keep a mirror, a staging copy or a public fork in sync with a reposito
## What it copies

- Branches and tags. Matching destination refs are overwritten; destination-only refs are kept.
- Git LFS objects referenced by canonical spec-v1 pointers (see Limits).
- Releases, their uploaded assets and the Latest selection.
- Description, homepage and topics.
- Labels.
Expand All @@ -17,6 +18,7 @@ It does not touch issues, pull requests, discussions, wikis, permissions, secret

- GitHub CLI installed and authenticated with `gh auth login`.
- `git` 2.29 or newer in `PATH`.
- `git-lfs` 3.8.1 or newer in `PATH` — required only when the source contains Git LFS pointers.
- A destination repository that already exists and that you can write to. Changing its default branch and disabling its Actions needs administration write access.
- github.com only. GitHub Enterprise Server and cross-instance replication are not supported.

Expand Down Expand Up @@ -82,17 +84,15 @@ Both flags are optional and independent; without them the active account is used

- **Check the direction.** Source wins for matching refs. A dry run reports what would change; it does not guarantee that server-side protections will accept the push.
- **Ref renames can be blocked.** Replacing `release` with `release/v2` fails while `release` still exists in the destination, because destination-only refs are never deleted. Delete or rename it, then rerun.
- **Git LFS content is not copied.** When `refs` is selected, the run stops before any destination change if it finds a pointer using a known LFS version, including in history; do not rely on it for formats or versions it does not recognize; without `refs` no Git history is read, so this check does not run. The check reads every blob reachable from branches and tags, so it can be slow on large histories (raise `--timeout`), and it is conservative: an ordinary file containing a known LFS version line may be reported too.
- **Git LFS support is limited to canonical spec-v1 pointers.** Objects referenced by a canonical pointer (`version https://git-lfs.github.com/spec/v1`, exactly three LF lines, no extensions, smaller than 1024 bytes) are downloaded, verified and uploaded before any ref is published, using `git-lfs` 3.8.1 or newer. Anything else that looks like LFS — older version aliases, CRLF, padding, extensions, or versions it does not recognize — stops the run before any destination change, including pointers only in history. The scan reads every blob reachable from branches and tags, so it can be slow on large histories (raise `--timeout`), and it is conservative: an ordinary file containing a known LFS version line may be reported too.
- **Some assets need a second step.** A changed release asset is uploaded under a temporary name, verified, then swapped in, so its name is briefly missing. An interrupted run leaves either the previous asset or the verified replacement; a rerun finishes the work, and a leftover temporary asset may need deleting from the release.
- **Invalid input stops the run before any write.** More than 20 topics, an empty release tag or a duplicated release tag, including drafts, abort the replication. Releases are matched by tag.
- **Retries are bounded.** Read requests retry twice for selected transient failures and short rate limits; write requests are never replayed automatically, so rerun instead.
- **`--timeout 30m` applies per Git command or HTTP request**, not to the whole replication. Raise it for large repositories or assets. Ctrl-C cancels pending work.

## Local cache

The source history is kept in a bare repository under your OS user cache directory (`gh-replicate/git-v1`), so later runs and other destinations only download what is missing. The cache holds repository contents, including private history, with owner-only permissions and no credentials.

You can delete it while no replication is running; the next run downloads the history again. A per-source lock allows one run at a time: a second run fails with the lock path until the first exits. CI jobs can persist this directory between runs to avoid repeated downloads.
A per-source lock lives under your OS user cache directory (`gh-replicate/git-v1`) so a second run of the same source fails with the lock path until the first exits. Source history is no longer reused across runs: each run copies into a fresh, private, temporary repository with its own configuration, so no partial state is ever reused. Cleanup is best effort — a hard kill (SIGKILL) can leave a temporary directory behind — and a failed LFS upload can leave objects on the destination without new refs. You can delete the cache directory while no replication is running.

## License

Expand Down
28 changes: 0 additions & 28 deletions accounts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,11 @@ import (
"fmt"
"net/http"
"reflect"
"slices"
"strings"
"testing"
"time"
)

func TestGitEnvDropsInheritedTokens(t *testing.T) {
t.Setenv("GH_TOKEN", "inherited")
t.Setenv("GITHUB_TOKEN", "inherited-app")
env := gitEnv("side-token")
seen := 0
for _, entry := range env {
if entry == "GH_TOKEN=side-token" {
seen++
continue
}
if strings.HasPrefix(entry, "GH_TOKEN=") || strings.HasPrefix(entry, "GITHUB_TOKEN=") {
t.Errorf("inherited token survived: %q", entry)
}
}
if seen != 1 {
t.Fatalf("side token set %d times", seen)
}
if !slices.Contains(env, "GIT_TERMINAL_PROMPT=0") {
t.Fatal("missing GIT_TERMINAL_PROMPT=0")
}
for _, entry := range gitEnv("") {
if strings.HasPrefix(entry, "GH_TOKEN=") {
t.Fatal("inherited run must not receive a token")
}
}
}

func TestSideResolvesRequestedAccount(t *testing.T) {
old := tokenForAccount
t.Cleanup(func() { tokenForAccount = old })
Expand Down
11 changes: 0 additions & 11 deletions cache_lock.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package main

import (
"context"
"fmt"
"os"
"os/exec"
)

// Never unlink the lock file: all users must lock the same file.
Expand All @@ -15,12 +13,3 @@ func lockCache(path string) (*os.File, error) {
}
return f, nil
}

// Git retains a reference to the lock if the parent is killed mid-command.
func (r *replicator) gitCommand(ctx context.Context, token, name string, args ...string) *exec.Cmd {
cmd := gitCommand(ctx, token, name, args...)
if r.cacheLock != nil {
inheritCacheLock(cmd, r.cacheLock)
}
return cmd
}
75 changes: 14 additions & 61 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func TestCacheLockReleasedAfterProcessDeath(t *testing.T) {
f.Close()
}

func TestSyncGitCacheLifecycle(t *testing.T) {
func TestSyncGitLifecycle(t *testing.T) {
f := newGitFixture(t)
seamStub(t)
gitRemote = func(repo string) string {
Expand All @@ -84,46 +84,22 @@ func TestSyncGitCacheLifecycle(t *testing.T) {
}
}
sync()
root, err := os.UserCacheDir()
if err != nil {
t.Fatal(err)
}
caches, err := filepath.Glob(filepath.Join(root, "gh-replicate", "git-v1", "*.git"))
if err != nil || len(caches) != 1 {
t.Fatalf("caches %v: %v", caches, err)
}
marker := filepath.Join(caches[0], "reused")
if err := os.WriteFile(marker, []byte("keep"), 0600); err != nil {
t.Fatal(err)
}
base := gitTest(t, f.source, "rev-parse", "main")
gitTest(t, f.destination, "update-ref", "refs/heads/exclusive", base)
gitTest(t, f.destination, "update-ref", "refs/tags/exclusive", base)
gitTest(t, f.source, "update-ref", "refs/heads/new", base)
sync()
if _, err := os.Stat(marker); err != nil {
t.Fatal("cache was recreated", err)
}
gitTest(t, f.source, "update-ref", "-d", "refs/heads/new")
gitTest(t, f.source, "update-ref", "-d", "refs/tags/v1")
sync()
if refs := gitRefs(t, caches[0]); strings.Contains(refs, "refs/heads/new") || strings.Contains(refs, "refs/tags/v1") {
t.Fatal("stale source refs", refs)
}
// The destination push does not prune destination-only refs, and deleting a
// source ref must not delete it from the destination.
for _, ref := range []string{"refs/heads/new", "refs/tags/v1", "refs/heads/exclusive", "refs/tags/exclusive"} {
if got := gitTest(t, f.destination, "rev-parse", ref); got != base {
t.Fatalf("lost destination ref %s", ref)
}
}
// A cached ref the source renamed into its own path must not block the
// fetch: one atomic fetch cannot delete and create these refs together.
gitTest(t, caches[0], "update-ref", "refs/heads/release", base)
gitTest(t, f.source, "update-ref", "refs/heads/release/v2", base)
sync()
if got := gitTest(t, f.destination, "rev-parse", "refs/heads/release/v2"); got != base {
t.Fatalf("renamed ref %s", got)
}
// A stale push would recreate this ref, making the assertion observable.
// A failed fetch must not change the destination and must release the lock.
gitTest(t, f.destination, "update-ref", "-d", "refs/heads/main")
before := gitRefs(t, f.destination)
if err := os.Rename(f.source, f.source+".offline"); err != nil {
Expand Down Expand Up @@ -191,7 +167,12 @@ func TestCacheLockActiveChild(t *testing.T) {
r := &replicator{cacheLock: lock, ctx: context.Background(), timeout: 20 * time.Second}
// A real Git process must retain the lock while its command is active.
alias := `!"` + filepath.ToSlash(os.Args[0]) + `" -test.run=^TestCacheLockActiveChild$ cache-child`
if err := r.command(root, side{}, "git", "-c", "alias.cache-child="+alias, "cache-child"); err != nil {
cmd := r.scanGitCommand(context.Background(), "-c", "alias.cache-child="+alias, "cache-child")
cmd.Dir = root
cmd.Env = append(cmd.Env, "GH_REPLICATE_ACTIVE_CHILD="+root)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
t.Fatal(err)
}
return
Expand Down Expand Up @@ -286,42 +267,14 @@ func TestSyncGitNewObjectsAndSecondTarget(t *testing.T) {
t.Fatal(got)
}
}
root, err := os.UserCacheDir()
if err != nil {
t.Fatal(err)
}
caches, err := filepath.Glob(filepath.Join(root, "gh-replicate", "git-v1", "*.git"))
if err != nil || len(caches) != 1 {
t.Fatalf("expected shared source cache: %v %v", caches, err)
}
}

// A local SHA-256 default must not leak into the cache: GitHub serves SHA-1.
// A local SHA-256 default must not leak into the ephemeral bare: GitHub serves SHA-1.
func TestSyncGitPinsSHA1ObjectFormat(t *testing.T) {
f := newGitFixture(t)
seamStub(t)
t.Setenv("GIT_DEFAULT_HASH", "sha256")
gitRemote = func(repo string) string {
if repo == sourceRepo {
return f.source
}
return f.destination
}
s := fakeSide(t, fakeServer(t, func(w http.ResponseWriter, req *http.Request) { fmt.Fprint(w, `{"enabled":false}`) }), "token")
r := &replicator{source: s, target: s, ctx: context.Background(), timeout: time.Minute}
if err := r.syncGit(sourceRepo, targetRepo); err != nil {
t.Fatal(err)
}
root, err := os.UserCacheDir()
if err != nil {
t.Fatal(err)
}
caches, err := filepath.Glob(filepath.Join(root, "gh-replicate", "git-v1", "*.git"))
if err != nil || len(caches) != 1 {
t.Fatalf("caches %v: %v", caches, err)
}
if got := gitTest(t, caches[0], "rev-parse", "--show-object-format"); got != "sha1" {
t.Fatalf("cache object format %s", got)
a := newAux(t)
if got := gitTest(t, a.Dir, "--git-dir="+a.Dir, "rev-parse", "--show-object-format"); got != "sha1" {
t.Fatalf("ephemeral bare object format %s", got)
}
}

Expand Down
8 changes: 4 additions & 4 deletions entrypoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ const (
func seamStub(t *testing.T) {
t.Helper()
isolateCache(t)
oldSide, oldRemote := newSide, gitRemote
t.Cleanup(func() { newSide, gitRemote = oldSide, oldRemote })
oldSide, oldRemote, oldEndpoint := newSide, gitRemote, lfsEndpoint
t.Cleanup(func() { newSide, gitRemote, lfsEndpoint = oldSide, oldRemote, oldEndpoint })
}

type gitFixture struct {
Expand Down Expand Up @@ -489,8 +489,8 @@ func TestLFSSyncGitBlocksHistoricalPointerBeforeDestinationEffects(t *testing.T)
for _, dry := range []bool{false, true} {
r := &replicator{source: side, target: side, ctx: context.Background(), timeout: time.Minute, dryRun: dry}
err := r.syncGit(sourceRepo, targetRepo)
if err == nil || !strings.Contains(err.Error(), "Git LFS pointers detected") {
t.Fatalf("dryRun=%v error = %v, want LFS detection", dry, err)
if err == nil || !strings.Contains(err.Error(), "Git LFS blob") {
t.Fatalf("dryRun=%v error = %v, want LFS block", dry, err)
}
if refs := gitRefs(t, f.destination); refs != "" {
t.Fatalf("dryRun=%v destination refs published: %q", dry, refs)
Expand Down
Loading
Loading