1package git
  2
  3import (
  4	"context"
  5	"errors"
  6	"fmt"
  7	"io"
  8	"os"
  9	"os/exec"
 10	"strings"
 11
 12	"github.com/charmbracelet/log"
 13	"golang.org/x/sync/errgroup"
 14)
 15
 16// Service is a Git daemon service.
 17type Service string
 18
 19const (
 20	// UploadPackService is the upload-pack service.
 21	UploadPackService Service = "git-upload-pack"
 22	// UploadArchiveService is the upload-archive service.
 23	UploadArchiveService Service = "git-upload-archive"
 24	// ReceivePackService is the receive-pack service.
 25	ReceivePackService Service = "git-receive-pack"
 26)
 27
 28// String returns the string representation of the service.
 29func (s Service) String() string {
 30	return string(s)
 31}
 32
 33// Name returns the name of the service.
 34func (s Service) Name() string {
 35	return strings.TrimPrefix(s.String(), "git-")
 36}
 37
 38// Handler is the service handler.
 39func (s Service) Handler(ctx context.Context, cmd ServiceCommand) error {
 40	switch s {
 41	case UploadPackService, UploadArchiveService, ReceivePackService:
 42		return gitServiceHandler(ctx, s, cmd)
 43	default:
 44		return fmt.Errorf("unsupported service: %s", s)
 45	}
 46}
 47
 48// ServiceHandler is a git service command handler.
 49type ServiceHandler func(ctx context.Context, cmd ServiceCommand) error
 50
 51// gitServiceHandler is the default service handler using the git binary.
 52func gitServiceHandler(ctx context.Context, svc Service, scmd ServiceCommand) error {
 53	cmd := exec.CommandContext(ctx, "git")
 54	cmd.Dir = scmd.Dir
 55	cmd.Args = append(cmd.Args, []string{
 56		// Enable partial clones
 57		"-c", "uploadpack.allowFilter=true",
 58		// Enable push options
 59		"-c", "receive.advertisePushOptions=true",
 60		svc.Name(),
 61	}...)
 62	if len(scmd.Args) > 0 {
 63		cmd.Args = append(cmd.Args, scmd.Args...)
 64	}
 65
 66	cmd.Args = append(cmd.Args, ".")
 67
 68	cmd.Env = os.Environ()
 69	if len(scmd.Env) > 0 {
 70		cmd.Env = append(cmd.Env, scmd.Env...)
 71	}
 72
 73	if scmd.CmdFunc != nil {
 74		scmd.CmdFunc(cmd)
 75	}
 76
 77	var (
 78		err    error
 79		stdin  io.WriteCloser
 80		stdout io.ReadCloser
 81		stderr io.ReadCloser
 82	)
 83
 84	if scmd.Stdin != nil {
 85		stdin, err = cmd.StdinPipe()
 86		if err != nil {
 87			return err
 88		}
 89	}
 90
 91	if scmd.Stdout != nil {
 92		stdout, err = cmd.StdoutPipe()
 93		if err != nil {
 94			return err
 95		}
 96	}
 97
 98	if scmd.Stderr != nil {
 99		stderr, err = cmd.StderrPipe()
100		if err != nil {
101			return err
102		}
103	}
104
105	log.Debugf("git service command in %q: %s", cmd.Dir, cmd.String())
106	if err := cmd.Start(); err != nil {
107		if errors.Is(err, os.ErrNotExist) {
108			return ErrInvalidRepo
109		}
110		return err
111	}
112
113	errg, _ := errgroup.WithContext(ctx)
114
115	// stdin
116	if scmd.Stdin != nil {
117		errg.Go(func() error {
118			defer stdin.Close() // nolint: errcheck
119			_, err := io.Copy(stdin, scmd.Stdin)
120			return err
121		})
122	}
123
124	// stdout
125	if scmd.Stdout != nil {
126		errg.Go(func() error {
127			_, err := io.Copy(scmd.Stdout, stdout)
128			return err
129		})
130	}
131
132	// stderr
133	if scmd.Stderr != nil {
134		errg.Go(func() error {
135			_, erro := io.Copy(scmd.Stderr, stderr)
136			return erro
137		})
138	}
139
140	err = errors.Join(errg.Wait(), cmd.Wait())
141	if err != nil && errors.Is(err, os.ErrNotExist) {
142		return ErrInvalidRepo
143	} else if err != nil {
144		return err
145	}
146
147	return nil
148}
149
150// ServiceCommand is used to run a git service command.
151type ServiceCommand struct {
152	Stdin  io.Reader
153	Stdout io.Writer
154	Stderr io.Writer
155	Dir    string
156	Env    []string
157	Args   []string
158
159	// Modifier functions
160	CmdFunc func(*exec.Cmd)
161}
162
163// UploadPack runs the git upload-pack protocol against the provided repo.
164func UploadPack(ctx context.Context, cmd ServiceCommand) error {
165	return gitServiceHandler(ctx, UploadPackService, cmd)
166}
167
168// UploadArchive runs the git upload-archive protocol against the provided repo.
169func UploadArchive(ctx context.Context, cmd ServiceCommand) error {
170	return gitServiceHandler(ctx, UploadArchiveService, cmd)
171}
172
173// ReceivePack runs the git receive-pack protocol against the provided repo.
174func ReceivePack(ctx context.Context, cmd ServiceCommand) error {
175	return gitServiceHandler(ctx, ReceivePackService, cmd)
176}