package gitcmd import ( "context" "fmt" "os" "os/exec" "path/filepath" "github.com/klauspost/compress/zstd" ) // Archive writes -.zip, .tar.gz and .tar.zst into outDir. // Concurrency is bounded by MaxConcurrentArchives, because each job forks git // and streams the whole tree. func (g *Git) Archive(ctx context.Context, name, ref, slug, outDir string) error { p, err := g.repoDir(name) if err != nil { return err } if !ValidRef(ref) { return fmt.Errorf("%q: %w", ref, ErrInvalidRef) } select { case g.archiveSem <- struct{}{}: defer func() { <-g.archiveSem }() case <-ctx.Done(): return ctx.Err() } base := filepath.Join(outDir, slug+"-"+ref) for _, f := range []struct{ format, ext string }{ {"zip", ".zip"}, {"tar.gz", ".tar.gz"}, } { if _, err := g.run(ctx, runOpts{}, "-C", p, "archive", "--format="+f.format, "--output="+base+f.ext, "--end-of-options", ref); err != nil { return fmt.Errorf("archive %s: %w", f.format, err) } } return g.archiveZstd(ctx, p, ref, base+".tar.zst") } // archiveZstd compresses `git archive --format=tar` in-process, so the // container needs no zstd binary. A failure must not leave a truncated // artifact, so the partial file is removed. func (g *Git) archiveZstd(ctx context.Context, repo, ref, outPath string) error { cmd := exec.CommandContext(ctx, "git", "-C", repo, "archive", "--format=tar", "--end-of-options", ref) cmd.Env = g.env stdout, err := cmd.StdoutPipe() if err != nil { return err } f, err := os.Create(outPath) if err != nil { return err } err = func() error { defer f.Close() if err := cmd.Start(); err != nil { return err } enc, err := zstd.NewWriter(f) if err != nil { _ = cmd.Wait() return err } // Copy the whole stream before Wait, otherwise git blocks on a full pipe. _, copyErr := enc.ReadFrom(stdout) closeErr := enc.Close() waitErr := cmd.Wait() if copyErr != nil { return copyErr } if closeErr != nil { return closeErr } return waitErr }() if err != nil { os.Remove(outPath) return fmt.Errorf("archive tar.zst: %w", err) } return nil }