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", "-c", "uploadpack.allowFilter=true", svc.Name()) // nolint: gosec
 54	cmd.Dir = scmd.Dir
 55	if len(scmd.Args) > 0 {
 56		cmd.Args = append(cmd.Args, scmd.Args...)
 57	}
 58
 59	cmd.Args = append(cmd.Args, ".")
 60
 61	cmd.Env = os.Environ()
 62	if len(scmd.Env) > 0 {
 63		cmd.Env = append(cmd.Env, scmd.Env...)
 64	}
 65
 66	if scmd.CmdFunc != nil {
 67		scmd.CmdFunc(cmd)
 68	}
 69
 70	var (
 71		err    error
 72		stdin  io.WriteCloser
 73		stdout io.ReadCloser
 74		stderr io.ReadCloser
 75	)
 76
 77	if scmd.Stdin != nil {
 78		stdin, err = cmd.StdinPipe()
 79		if err != nil {
 80			return err
 81		}
 82	}
 83
 84	if scmd.Stdout != nil {
 85		stdout, err = cmd.StdoutPipe()
 86		if err != nil {
 87			return err
 88		}
 89	}
 90
 91	if scmd.Stderr != nil {
 92		stderr, err = cmd.StderrPipe()
 93		if err != nil {
 94			return err
 95		}
 96	}
 97
 98	log.Debugf("git service command in %q: %s", cmd.Dir, cmd.String())
 99	if err := cmd.Start(); err != nil {
100		if errors.Is(err, os.ErrNotExist) {
101			return ErrInvalidRepo
102		}
103		return err
104	}
105
106	errg, _ := errgroup.WithContext(ctx)
107
108	// stdin
109	if scmd.Stdin != nil {
110		errg.Go(func() error {
111			defer stdin.Close() // nolint: errcheck
112			_, err := io.Copy(stdin, scmd.Stdin)
113			return err
114		})
115	}
116
117	// stdout
118	if scmd.Stdout != nil {
119		errg.Go(func() error {
120			_, err := io.Copy(scmd.Stdout, stdout)
121			return err
122		})
123	}
124
125	// stderr
126	if scmd.Stderr != nil {
127		errg.Go(func() error {
128			_, erro := io.Copy(scmd.Stderr, stderr)
129			return erro
130		})
131	}
132
133	err = errors.Join(errg.Wait(), cmd.Wait())
134	if err != nil && errors.Is(err, os.ErrNotExist) {
135		return ErrInvalidRepo
136	} else if err != nil {
137		return err
138	}
139
140	return nil
141}
142
143// ServiceCommand is used to run a git service command.
144type ServiceCommand struct {
145	Stdin  io.Reader
146	Stdout io.Writer
147	Stderr io.Writer
148	Dir    string
149	Env    []string
150	Args   []string
151
152	// Modifier functions
153	CmdFunc func(*exec.Cmd)
154}
155
156// UploadPack runs the git upload-pack protocol against the provided repo.
157func UploadPack(ctx context.Context, cmd ServiceCommand) error {
158	return gitServiceHandler(ctx, UploadPackService, cmd)
159}
160
161// UploadArchive runs the git upload-archive protocol against the provided repo.
162func UploadArchive(ctx context.Context, cmd ServiceCommand) error {
163	return gitServiceHandler(ctx, UploadArchiveService, cmd)
164}
165
166// ReceivePack runs the git receive-pack protocol against the provided repo.
167func ReceivePack(ctx context.Context, cmd ServiceCommand) error {
168	return gitServiceHandler(ctx, ReceivePackService, cmd)
169}